Refactored main loop