Fix bug with duplicates being sent.

- Also refactored the code into a js module.