Refactored event handling (and probably added about 100 bugs).