Refactor mainloop into handlers