Make a start on refactoring JS code