moved optimization into the run loop