Cleanup code optimize algorithm