optimized main loop