Final version of optimization algorithm