refactored optimizePhi