refactor so that the main loop handles less logic