Refactor main loop