Refactored a bit, to keep the event handlers small.