Finish the logic of optimize.