% GENSEC.M %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Column section

function [sys,temp,dT] = gensec(t,x,u,flag,L,V,Nt)

global termodata

holdup = [x(3 * Nt + 1:4 * Nt) x(3 * Nt + 1:4 * Nt) x(3 * Nt + 1:4 * Nt)];
temp  = x(4 * Nt + 1:end);
x = x(1:3 * Nt);
x = reshape(x,Nt,3);

L_in = u(1); x_in = u(2:4);
V_in = u(5:6); y_in = u(7:12);

if (flag == 1)
    % Derivatives
    
    % Vapour compositions
    [y,dT] = termo(x,temp,flag,Nt);
    
    dx = zeros(Nt,3);
    % Top stage
    dx(1,:) = ...
        (L_in * (x_in' - x(1,:)) - ...
        V(1) * (y(1,:) - x(1,:)) + ...
        (1 - termodata.alpha) * V(2) * (y(2,:) - x(1,:)) + ...
        termodata.alpha * V(3) * (y(3,:) - x(1,:))) ./ holdup(1,:);
    % Middle stages
    for k = 2:(Nt - 2)
        dx(k,:) = ...
            (L(k - 1) * (x(k - 1,:) - x(k,:)) - ...
            V(k) * (y(k,:) - x(k,:)) + ...
            (1 - termodata.alpha) * V(k + 1) * (y(k + 1,:) - x(k,:)) + ...
            termodata.alpha * V(k + 2) * (y(k + 2,:) - x(k,:))) ./ holdup(k,:);
    end
    % Second stage from below
    dx(Nt - 1,:) = ...
        (L(Nt - 2) * (x(Nt - 2,:) - x(Nt - 1,:)) - ...
        V(Nt - 1) * (y(Nt - 1,:) - x(Nt - 1,:)) + ...
        (1 - termodata.alpha) * V(Nt) * (y(Nt,:) - x(Nt - 1,:)) + ...
        termodata.alpha * V_in(1) * (y_in(1:3)' - x(Nt - 1,:))) ./ holdup(Nt - 1,:);
    % Bottom stage
    dx(Nt,:) = ...
        (L(Nt - 1) * (x(Nt - 1,:) - x(Nt,:)) - ...
        V(Nt) * (y(Nt,:) - x(Nt,:)) + ...
        (1 - termodata.alpha) * V_in(1) * (y_in(1:3)' - x(Nt,:)) + ...
        termodata.alpha * V_in(2) * (y_in(4:6)' - x(Nt,:))) ./ holdup(Nt,:);

    sys = dx(:);
elseif (flag == 3)
    % Measurements
    
    [y_out1,dT1] = termo(x(1,:),temp,flag);
    [y_out2,dT2] = termo(x(2,:),temp,flag);

    sys = [y_out1'; y_out2'; x(Nt,:)'];
else
    sys = [];
end