function sf_columnA(block)

% ******* Program written by Antonio Araujo in March, 2008 **********
% In order to know more on Level-2 M-file S-function, refer to the MatLab documentation.

setup(block);

function setup(block)

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

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

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

for i = 1:nu
    block.InputPort(i).Dimensions = 1;
    block.InputPort(i).DirectFeedthrough = true;
end
%block.InputPort(3).Dimensions =1; % Feed composition

for i = 1:ny
    block.OutputPort(i).Dimensions = 1;
end
block.OutputPort(1).Dimensions = 1;
block.OutputPort(2).Dimensions = 1;
block.OutputPort(5).Dimensions = NT;
block.OutputPort(6).Dimensions = NT;


block.SampleTimes = [0 0];

% Setup Dwork
block.NumContStates = NT*NC;

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)

load SS_data_columnA.mat;
parameters
block.ContStates.Data = [x_ss';M_ss'];


function Outputs(block)

parameters
% State variables
X = block.ContStates.Data;
x = X(1:(NC-1)*NT);                    % Liquid compositions from btm to top
M = X((NC-1)*NT+1:NC*NT);              % Liquid hold up from btm to top

% Rearrange elements of composition vector (x) for later use
Iu = reshape(1:(NC-1)*NT,NT,NC-1);
x  = x(Iu);

% Output variables
block.OutputPort(1).Data = [x(NT,:)];
block.OutputPort(2).Data = [x(1,:)];
block.OutputPort(3).Data = M(NT);
block.OutputPort(4).Data = M(1);
block.OutputPort(5).Data = x;
block.OutputPort(6).Data = M;


function Derivatives(block)

parameters
% State variables
X = block.ContStates.Data;
x = X(1:(NC-1)*NT);                    % Liquid compositions from btm to top
M = X((NC-1)*NT+1:NC*NT);              % Liquid hold up from btm to top

% Rearrange elements of composition vector (x) for later use
Iu = reshape(1:(NC-1)*NT,NT,NC-1);
x  = x(Iu);                          

% Disturbances
F   = block.InputPort(1).Data;
qF  = block.InputPort(3).Data;
zF  = block.InputPort(2).Data';

% Manipulation
LT  = block.InputPort(4).Data ;
VB  = block.InputPort(5).Data ;
D   = block.InputPort(6).Data ;
B   = block.InputPort(7).Data ;

% Non-linear model
modelColumnA
block.Derivatives.Data = [dxdt; dMdt];

