Fixed some bugs in event handling and added test