refactoring of the whole event-handling mechanism with a new state machine.