fix main loop logic