Move the main loop into a function.

I think this is cleaner as it's a step toward removing some globals.