Refactor main loop

It's slightly weird.  This makes it a bit less weird, though still weird...