Refactoring, better event handling, some bug fixes