Refactor mainloop, extract types. WIP.