function varargout = MCHE_UA_RES(T,x,d,parameters)

% MCHE_UA_RES: Gives residuals of UA - UA_specified so we can solve the
% MCHE model for temperatures T, given UA values and inlet temperatures.

global h

hyCase = h.Activedocument;
sol=hyCase.Solver;
f = hyCase.Flowsheet;

sol.CanSolve = 0 ;

%Merge temperature vector and the other variables again

x = [x(1:3) ; T ; x(4:end)] ;

x = parameters.scale_x*x ;

%Reset optimization variables

f.MaterialStreams.Item('MR10').PressureValue = x(1) ;
f.MaterialStreams.Item('MR17').PressureValue = x(2) ; 
f.MaterialStreams.Item('MR10').MolarFlowValue = x(3) ;
f.MaterialStreams.Item('NG5').TemperatureValue = x(4) ;
f.MaterialStreams.Item('MR12').TemperatureValue = x(5) ;
f.MaterialStreams.Item('MR15').TemperatureValue = x(6) ;
f.MaterialStreams.Item('Subcooled NG').TemperatureValue = x(7) ;
f.MaterialStreams.Item('MR16').TemperatureValue = x(8) ;
f.MaterialStreams.Item('C2').MolarFlowValue = x(9) ;
f.MaterialStreams.Item('C3').MolarFlowValue = x(10) ;
f.MaterialStreams.Item('N2').MolarFlowValue = x(11) ;

%Reset disturbances
f.MaterialStreams.Item('NG4').TemperatureValue = d(1) ; % degrees C
f.MaterialStreams.Item('NG4').PressureValue = d(2) ; % kilopascal
f.MaterialStreams.Item('NG4').MolarFlowValue = d(3); %mol/s
f.MaterialStreams.Item('MR10').TemperatureValue = d(1);

sol.CanSolve = 1 ;

UA = parameters.ua;
if f.Operations.Item('MCHE, warm part').Duty.IsKnown==1 && f.Operations.Item('MCHE, cold part').Duty.IsKnown==1 ;
res = [f.Operations.Item('MCHE, warm part').Specifications.Item('UA1').CurrentValue-UA(1);
	f.Operations.Item('MCHE, warm part').Specifications.Item('UA2').CurrentValue-UA(2);
	f.Operations.Item('MCHE, warm part').Specifications.Item('UA3').CurrentValue-UA(3) ;
	f.Operations.Item('MCHE, cold part').Specifications.Item('UA1').CurrentValue-UA(4) ;
	f.Operations.Item('MCHE, cold part').Specifications.Item('UA2').CurrentValue-UA(5)];
else
    res = ones(5,1) ;
end

switch parameters.solver
    case('fsolve')
        varargout = {res} ;
    case('lsqnonlin')
        norm = res'*res ;
        varargout = {norm} ;
    case('fmincon')
        c = [];
        varargout ={c,res} ; 
end