Implemented main optimization logic