Improved event handling.

Also refactored some of the code to use private state instead of passing state around everywhere.