Main loop Refactoring