refactored main loop