Refactored main loop.