Refactored JS version considerably. Much more readable, and easier to use