main loop rewriting