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

function [sys] = gensec(t,x,u,flag,L,V,Nt)
holdup = [x(2 * Nt + 1:3 * Nt) x(2 * Nt + 1:3 * Nt)];


x = x(1:2 * Nt);

x = reshape(x,Nt,2);

if (flag == 1)
    % Derivatives
    L_in = u(1); x_in = u(2:3);
    V_in = u(4); y_in = u(5:6);
    % Vapour compositions
    [y] = termo(x,flag,Nt);
    
    dx = zeros(Nt,2);
    % Top stage
    dx(1,:) = ...
        (L_in * (x_in' - x(1,:)) - ...
        V(1) * (y(1,:) - x(1,:)) + ...
        V(2) * (y(2,:) - 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,:)) + ...
            V(k + 1) * (y(k + 1,:) - 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,:)) + ...
        V(Nt) * (y(Nt,:) - x(Nt - 1,:))) ./ holdup(Nt - 1,:);
    % Bottom stage
    dx(Nt,:) = ...
        (L(Nt - 1) * (x(Nt - 1,:) - x(Nt,:)) - ...
        V(Nt) * (y(Nt,:) - x(Nt,:)) + ...
        V_in(1) * (y_in(1:2)' - x(Nt,:))) ./ holdup(Nt,:);

    sys = dx(:);
elseif (flag == 3)
    % Measurements
    
    [y_out1] = termo(x(1,:),flag);
    [y_out2] = termo(x(2,:),flag);
    sys = [y_out1'; y_out2'; x(Nt,:)'];
else
    sys = [];
end