Moved Main Event Handler to its own function.

Main event handler is now outside of the main loop. Did this to make the
main loop more readable.