main loop refactor