function sf_CSTR(block)


setup(block);

function setup(block)

% Register number of dialog parameters
block.NumDialogPrms = 0;

% Register number of ports
parameters
nu = 6; ny = 3; % Output = [composition at both ends (2 vectors)] + [MD and MB (2)]
block.NumInputPorts  = nu;
block.NumOutputPorts = ny;

% Setup port properties to be inherited or dynamic
block.SetPreCompInpPortInfoToDynamic;
block.SetPreCompOutPortInfoToDynamic;

block.InputPort(1).Dimensions = 1;
block.InputPort(2).Dimensions = 1; % Feed composition
block.InputPort(3).Dimensions = 1;
block.InputPort(4).Dimensions = NC;
block.InputPort(5).Dimensions = 1;
block.InputPort(6).Dimensions = 1;

block.OutputPort(1).Dimensions = 1;
block.OutputPort(2).Dimensions = 1;
block.OutputPort(3).Dimensions = 1;

block.SampleTimes = [0 0];

% Setup Dwork
block.NumContStates = 2;

block.RegBlockMethod('InitializeConditions',    @InitializeConditions);
block.RegBlockMethod('Outputs',                 @Outputs);
block.RegBlockMethod('Derivatives',             @Derivatives);
block.RegBlockMethod('SetInputPortSamplingMode',@SetInpPortFrameData);


function SetInpPortFrameData(block, idx, fd)
  
block.InputPort(idx).SamplingMode = fd;
for i = 1:block.NumOutputPorts
    block.OutputPort(i).SamplingMode = fd;
end


function InitializeConditions(block)

parameters
load SS_data_columnA.mat % y0
block.ContStates.Data = [2800*0.42855 2800];


function Outputs(block)

parameters
% State variables
X = block.ContStates.Data;

% Output variables
F=block.InputPort(6).Data;

zF=X(1)/X(2);

block.OutputPort(1).Data = F;
block.OutputPort(2).Data = zF;
block.OutputPort(3).Data = X(2);


function Derivatives(block)

D = block.InputPort(1).Data;
xD = block.InputPort(2).Data;
F0 = block.InputPort(3).Data;
zF0 = block.InputPort(4).Data;
k1 = block.InputPort(5).Data;
F = block.InputPort(6).Data;


%state variables
X = block.ContStates.Data;

MrA=X(1);
Mr=X(2);
%output variables expressed as functions of state variables

zFA=MrA/Mr;

%Dynamic component balances
dMrAdt=F0*zF0(1)+D*xD-F*zFA-k1*MrA;
dMrdt = F0+D-F;

block.Derivatives.Data = [dMrAdt;dMrdt];



