Feature/refactor mainloop

`func loop()` is more and more complicated after #48 changes, so refactored.