split main loop into separate functions