Fixed main loop logic