Refactor mainLoop.
Now running event handling in a separate thread.