Cleaned up the main loop and made it more event-driven.