Refactored parts of the main loop