Moved a lot of logic to functions instead of leaving it in one big funciton. Fixed event listeners, so they weren't set multiple times