function [x,b,exflg,Uout] = SampMakeUp(initMakeUp,Uin,opt,par,scl,con,ther,def,itg)

% This function defines the MakeUp section for the simple ammonia cycle
% in the case of sampling.
%
% Written by Julian Straus, Trondheim 09.12.2018
%
% The needed input for this function are
%   initMakeUp: Solution of the system around the nominal point
%
%   Uin:        A column matrix or column vector defining the input values 
%               for the sampling of the variables.
%
%   opt:        Options for fsolve, defined for all iterations of the
%               sampling in the same way.
%
%   opt:        Options for fsolve, defined for all iterations of the
%               sampling in the same way.
%
% The output is defined as
%  	x:          States of the system, calculated via the non-linear system
%               of equations.
%
%   b:      	Residual in the Newton-Raphson approach
%
%   exflg:      Exitflag of fsolve.
%
%   Uout:       A column matrix or column vector defining the input values 
%               for the sampling of the variables. Uout equals Uin except
%               in the HYSYS cases.
%
% The necessary structures are defined as
%   par:        Parameters used in the calculation, output of the system
%
%   scl:        Scaling factors of the system, must include:
%               .Q      Scaling factor for the flow
%               .p      Scaling factor for the pressure
%               .T      Scaling factor for the temperature
%               .W      Scaling factor for the power
%
%   con:        Physical constants, must contain
%               .R      Ideal Gas constant
%
%   ther:       Thermodynamical values to calculate henry coefficients of
%               the supercritical components, must include:
%               .Hi    	Henry coefficient, i = 1-3
%
%   def:        Defined stream values, e.g pressure and composition for all
%               inlets and the pressure of the outlets or the flow of the
%               inlets
%
%   itg:        Intiger values, which should include
%               .k      Total number of variables per stream
%               .j      Total number of components in each stream

% Redefinition of the screening values
Uout = Uin(end,:)';
def.FMake(2:3) = Uout(1:2);
def.FMix(1:3)  = Uout(3:5);
def.HEx1(1:3)  = Uout(6:8);
par{1}.S = Uout(9);
par{5}.S = Uout(9);
par{9}.S = Uout(9);

def.fun = @(nvar,into,colind) DefMakeUp(nvar,into,colind,scl,def);
ConAnMakeUp = @(x) ConMakeUp(x,par,scl,con,ther,def,itg);
[x,b,exflg] = fsolve(ConAnMakeUp,initMakeUp',opt);
