Refactor out the main loop