function varargout = constraints_prico_temp(x,d,par)

% Calculate constraint functions for optimization of PRICO model where
% temperatures are specified.

global h

hyCase = h.Activedocument;
sol=hyCase.Solver;
f = hyCase.Flowsheet;
UA = par.ua ;
d0 = par.d0 ;


sol.CanSolve = 0 ;
f.Operations.Item('RCY-1').IsIgnored = 1 ; % Make sure recycle is ignored

% Disturbances: Feed conditions and cooling temperature
f.MaterialStreams.Item('MR4').TemperatureValue = d(1) ; 
f.MaterialStreams.Item('NG1').TemperatureValue = d(1) ; % Assume MR and NG are cooled to the same temperature
f.MaterialStreams.Item('NG1').PressureValue = d(2) ; 
f.MaterialStreams.Item('NG1').MolarFlowValue = d(3)*d0(3) ; 


% Inputs

x = par.scalex\x ;

f.MaterialStreams.Item('MR1').TemperatureValue = x(1) ; % Temperature guess for recycle (C)
f.MaterialStreams.Item('MR5').TemperatureValue = x(2) ; % Temperature of hot MR after HX (C)
f.MaterialStreams.Item('MR7').PressureValue = x(3) ; % Pressure after MR turbine (kPa)
f.MaterialStreams.Item('MR9').PressureValue = x(4) ; % Pressure before compressor (kPa)
f.Operations.Item('K-100').CompressorSpeedValue = x(5) ; % Compressor speed (NB! Hz, not rpm)
f.MaterialStreams.Item('MR1').MolarFlowValue = x(6) ;

sol.CanSolve = 1 ;


if f.Operations.Item('K-100').Energy.IsKnown == 1 && f.Operations.Item('HX').UA.IsKnown == 1
%Retrieve values of inequality constraint functions

dpsat = f.Operations.Item('SPRDSHT-1').Cell('D3').CellValue ; % Margin to saturation at turbine outlet (should be liquid only)
dtsup = f.Operations.Item('SPRDSHT-1').Cell('A6').CellValue ; % Superheating of cold refrigerant after HX
dmsurge = f.Operations.Item('SPRDSHT-2').Cell('D7').CellValue ; % flow margin to compressor surge
dtmin = -10^(-2) +  f.Operations.Item('HX').MinApproachValue ; % DTmin in heat exchanger. Must be positive.
dW = 1.32e5 - f.Operations.Item('K-100').EnergyValue; % Maximum compressor work - nominal plus 10 percent

%Scale the inequality constraints

c = par.scalec*[-dpsat ; 5-dtsup ; -dmsurge ; -dtmin ; -dW] ;


% Retrieve values of equality constraint functions

dt = f.MaterialStreams.Item('MR1').TemperatureValue - f.MaterialStreams.Item('MR9').TemperatureValue ; % Temperature difference over recycle
res_1 = f.Operations.Item('HX').Specifications.Item('UA_MR').CurrentValue - UA(1) ;
res_2 = f.Operations.Item('HX').Specifications.Item('UA_NG').CurrentValue - UA(2) ;

%Scale equality constraints
ceq = par.scaleceq*[dt ; res_1 ; res_2] ;

else    
    c = ones(5,1) ;    
    ceq = ones(3,1) ;
end



%What to return? If we use the function for equation solving, we need only
%return the equality constraints.
switch par.what
    case('optim')
        varargout = {c,ceq} ;
    case('solve')
        varargout = {ceq} ;
end




