Fix looping logic error in main loop