function [res,xopt,jopt,con,l,exitflag,eta,ph] = prico_optres(di,par)

load start.mat

%x_0 = par.x0 ;
lb = par.lb ;
ub = par.ub ;

variable = par.var ;

d = par.d ;

switch variable
    case('tamb')
        d(1) = di ; % We vary cooling temperature
    case('feed')
        d(3) = di ;  % We vary feed flow rate
end

runwhat = par.runwhat;
opt_options = par.options ; 

exitflag = par.exitflag ;

switch(runwhat)
    case('optimize') %In this case always try to use the x0 supplied from previous optimization
 % If the exitflag from previous try is positive, use that solution as starting point. Otherwise, chose one of the four others (high or low T, low F or nominal)
            if d(3)<0.80 && exitflag < 1
                x_0 = par.scalex*x_low_F ;
            elseif ~(d(3)<0.80) && d(1) < 25 && exitflag < 1
                x_0 = par.scalex*x_low_T ;
            elseif ~(d(3)<0.80) && d(1) > 35 && exitflag < 1 % High T
                x_0 = par.scalex*x_high_T ;
            elseif ~(d(3)<0.80) && ~(d(1) > 35) && ~(d(1) < 35) && exitflag < 1
                x_0 = par.scalex*x0_nom ;
            else % exitflag is positive
                x_0 = par.x0 ;
            end
            [xopt,jopt,exitflag,output,lambda] = fmincon(@obj_prico_temp,x_0,[],[],[],[],lb,ub,@constraints_prico_temp,opt_options,d,par);
[J eta ph] = obj_prico_temp(xopt,d,par) ;
        
        con = constraints_prico_temp(xopt,d,par) ;
        con = [con ; xopt(5)-ub(5)] ;
        l = [lambda.ineqnonlin ; lambda.upper(5)] ; %Include the maximum speed constraint (ub(5))
        k = 1:6 ;
    case('find') % In this case first select an appropriate starting point from one of the three saved ones

            if d(3)<0.80 && exitflag < 1
                x_0 = par.scalex*x_low_F ;
            elseif ~(d(3)<0.80) && d(1) < 25 && exitflag < 1
                x_0 = par.scalex*x_low_T ;
            elseif ~(d(3)<0.80) && d(1) > 35 && exitflag < 1 % High T
                x_0 = par.scalex*x_high_T ;
            elseif ~(d(3)<0.80) && ~(d(1) > 35) && ~(d(1) < 35) && exitflag < 1
                x_0 = par.scalex*x0_nom ;
            else % exitflag is positive
                x_0 = par.x0 ;
            end

        [xopt,jopt,exitflag,output,lambda] = fmincon(@obj_prico_temp,x_0,[],[],[],[],lb,ub,@constraints_prico_temp,opt_options,d,par);
        

        
        con = constraints_prico_temp(xopt,d,par) ;
        con = [con ; xopt(5)-ub(5)] ;
        l = [lambda.ineqnonlin ; lambda.upper(5)] ; %Include the maximum speed constraint (ub(5))
        k = par.constraintID ;
end

if exitflag <= 0
%     disp('Optimization failed')
%     disp(['exitflag = ' num2str(exitflag)])
    res = NaN ;
else
    res = con(k) + l(k) ; %Return only res for one constraint
end