Split main loop logic into functions