Moved main loop into separate method.