Refactor main loop.