Refactor the main loop of the program