improved main loop control flow