Completely refactored main js file