Fixed bugs with event handling. New unit tests to cover all cases.