refactor to simplify main loop