Simplify the main loop code by separating work in different functions.