function [res,un,J,con,l] = rsr_optres(d,param)

%RSR_OPTRES takes given values of disturbances d, carries out optimization
%of the reactor-separator-recycle model and returns the sum of the desired
%constraint value and the corresponding Lagrange multiplier - this sum is
%negative when the constraint is inactive, positive when it is active, and
%zero when it switches.

load un0.mat %Initial values to be used at every optimization. NB: These are scaled values!
un0_opt = un0./param.scale_un;

variable = param.variable ; %Which variable are we changing (energy cost or maximum feed)
switch variable
    case('pv')
        param.prices(2) = d ; % We vary energy cost 
    case('fmax')
        param.Fmax = d ; 
    case('pp')
        param.prices(4) = d ; % Varying value of purge stream
end

options = param.options ; % Options for fmincon

[un,J,exitflag,output,lambda] = fmincon(@rsr_obj,un0_opt,[],[],[],[],zeros(size(un0_opt)),[],@reaseprec,options,param) ; % Run optimization

con = reaseprec(un,param) ; % Get values of nonlinear constraint functions at optimum

un = param.scale_un.*un ;
con = con./[1 1e-4 1e-2 1e-1 1 1 1 1]';

con = [con ; -un(10) ; -un(11)];

l = [lambda.ineqnonlin ; lambda.lower(10:11)] ; % Lagrange multipliers corresponding to the nonlinear equality constraints
k = param.constraintID ;

if exitflag <= 0
    disp('Optimization failed')
    disp(['exitflag = ' num2str(exitflag)])
    res = NaN ;
else
    res = con(k) + l(k) ;
end