optimize main loop