Code refactored

Cleaned up the code and organized the code into variables, functions and
event handlers.