main loop refactoring