Updated main_loop for better flow control.