Separated main loop logic for modularization