tic;    
[VOI, STATES, ALGEBRAIC, CONSTANTS] = mainFunction();
toc;

function [VOI, STATES, ALGEBRAIC, CONSTANTS] = mainFunction()
    % This is the "main function".  In Matlab, things work best if you rename this function to match the filename.
   [VOI, STATES, ALGEBRAIC, CONSTANTS] = solveModel();
end

function [algebraicVariableCount] = getAlgebraicVariableCount()
    % Used later when setting a global variable with the number of algebraic variables.
    % Note: This is not the "main method".
    algebraicVariableCount =36;
end
% There are a total of 11 entries in each of the rate and state variable arrays.
% There are a total of 39 entries in the constant variable array.
%

function [VOI, STATES, ALGEBRAIC, CONSTANTS] = solveModel()
    [LEGEND_STATES, LEGEND_ALGEBRAIC, LEGEND_VOI, LEGEND_CONSTANTS] = createLegends();
    % Create ALGEBRAIC of correct size
    global algebraicVariableCount;  algebraicVariableCount = getAlgebraicVariableCount();
    % Initialise constants and state variables
    [INIT_STATES, CONSTANTS] = initConsts;

    % Set timespan to solve over
    tspan = [0, 3.6];

    % Set numerical accuracy options for ODE solver
    options = odeset('RelTol', 1e-05, 'AbsTol', 1e-06, 'MaxStep', 1e-3);

    % Solve model with ODE solver
    [VOI, STATES] = ode15s(@(VOI, STATES)computeRates(VOI, STATES, CONSTANTS), tspan, INIT_STATES, options);

    % Compute algebraic variables
    [RATES, ALGEBRAIC] = computeRates(VOI, STATES, CONSTANTS);
    ALGEBRAIC = computeAlgebraic(ALGEBRAIC, CONSTANTS, STATES, VOI);

    vlabels = {'q_Ca_i in component environment (fmol)',...
        'q_TRPN in component environment (fmol)',...
        'q_Ca_TRPN in component environment (fmol)',...
        'q_B_XB in component environment (fmol)',...
        'q_U_XB in component environment (fmol)',...
        'q_W_XB in component environment (fmol)',...
        'q_S_XB in component environment (fmol)',...
        'G_w in component crossbridge_TRPN (metre)',...
        'G_s in component crossbridge_TRPN (metre)',...
        'SL in component crossbridge_TRPN (metre)',...
        'dSL in component environment (m_per_s)',...
        'T_active in component crossbridge_TRPN (kPa)',...
        'T_passive in component crossbridge_TRPN (kPa)',...
        'T_total in component crossbridge_TRPN (kPa)'};
    [~, i_st, i_alg] = find_indices(vlabels, cellstr(LEGEND_CONSTANTS), cellstr(LEGEND_STATES), cellstr(LEGEND_ALGEBRAIC));
    if i_st
        plot_selected(i_st,VOI,STATES,'s',LEGEND_STATES,'STATES',ceil(sqrt(length(i_st))))
    end
    plot_selected(i_alg,VOI,ALGEBRAIC,'s',LEGEND_ALGEBRAIC,'ALGEBRAIC',ceil(sqrt(length(i_alg))))

    vlabels = {'v_R_TRPNCa in component crossbridge_TRPN (fmol_per_sec)',...
        'mu_Ca_i in component crossbridge_TRPN (J_per_mol)',...
        'mu_TRPN in component crossbridge_TRPN (J_per_mol)',...
        'mu_Ca_TRPN in component crossbridge_TRPN (J_per_mol)'};
    [~, ~, i_alg] = find_indices(vlabels, cellstr(LEGEND_CONSTANTS), cellstr(LEGEND_STATES), cellstr(LEGEND_ALGEBRAIC));
    plot_selected(i_alg,VOI,ALGEBRAIC,'s',LEGEND_ALGEBRAIC,'\mu',ceil(sqrt(length(i_alg))))

    % find total mu for v_R_TrpnCa
    if true
        istart = 150;
        Af = ALGEBRAIC(istart:end,i_alg(2)) + ALGEBRAIC(istart:end,i_alg(3));
        Ar = ALGEBRAIC(istart:end,i_alg(4));
        tpos = exp(( CONSTANTS(:,1).*ALGEBRAIC(:,4)+ALGEBRAIC(:,1))./( CONSTANTS(:,15).*CONSTANTS(:,16)));
        tneg = exp(ALGEBRAIC(:,8)./( CONSTANTS(:,15).*CONSTANTS(:,16)));
        figure,
        subplot(2,3,1)
        plot(VOI(istart:end), Af)
        title('Af (J_per_mol)')
        subplot(2,3,2)
        plot(VOI(istart:end), Ar)
        title('Ar (J_per_mol)')
        subplot(2,3,3)
        plot(VOI(istart:end), Af-Ar)
        title('net Af-Ar (J_per_mol)')
        subplot(2,3,4)
        plot(VOI(istart:end), tpos(istart:end))
        title('tpos')
        subplot(2,3,5)
        plot(VOI(istart:end), tneg(istart:end))
        title('tneg')
        subplot(2,3,6)
        plot(VOI(istart:end), ALGEBRAIC(istart:end,i_alg(1)))
        title(LEGEND_ALGEBRAIC(i_alg(1),:))
        sgtitle('v_R_TrpnCa mu')    
    end

    if false
        % check rootsolver variables
        i_aroot = 22:26;
        plot_selected(i_aroot,VOI,ALGEBRAIC,'s',LEGEND_ALGEBRAIC,'Root finder variables',ceil(sqrt(length(i_aroot))))
    end
end            


function [i_con, i_st, i_alg] = find_indices(labels, LEGEND_CONSTANTS, LEGEND_STATES, LEGEND_ALGEBRAIC)
% return the indices for the selected labels
    all_legends = [LEGEND_CONSTANTS; LEGEND_STATES; LEGEND_ALGEBRAIC];
    
    i_con = [];
    for i = 1:length(labels)
        i_con = [i_con; find(strcmp(labels{i},LEGEND_CONSTANTS))];
    end
    i_st = [];
    for i = 1:length(labels)
        i_st = [i_st; find(strcmp(labels{i},LEGEND_STATES))];
    end
    i_alg = [];
    for i = 1:length(labels)
        i_alg = [i_alg; find(strcmp(labels{i},LEGEND_ALGEBRAIC))];
    end
    
    if length(i_con) + length(i_st) + length(i_alg) < length(labels)
        error('missing index');
    end
end


function [] = plot_selected(ids,x,y,legend_x,legend_y,titlestr,ns)
    istart = 1;
    figure();
%     plot stimuli
    for i = 1:length(ids)
        subplot(ns,ns,i)
        plotting_x = x(istart:end);
        plotting_y = y(istart:end,ids(i));
        if isempty(plotting_y) % probably a constant scalar
            plotting_y = repmat(y(ids(i)),2);
            plotting_x = [x(istart), x(end)];
        end
        plot(plotting_x, plotting_y);
        xlabel('time (s)');
        str = split(legend_y(ids(i),:), ' ');
        str = legend_y(ids(i),:);
        l = legend(str);
        set(l,'interpreter','none');
    end
    if verLessThan('matlab','9.5')
        suptitle(titlestr)    
    else
        sgtitle(titlestr)    
    end
end

function [LEGEND_STATES, LEGEND_ALGEBRAIC, LEGEND_VOI, LEGEND_CONSTANTS] = createLegends()
    LEGEND_STATES = ''; LEGEND_ALGEBRAIC = ''; LEGEND_VOI = ''; LEGEND_CONSTANTS = '';
    LEGEND_VOI = strpad('time in component environment (second)');
    LEGEND_CONSTANTS(:,1) = strpad('n_CaTRPN in component crossbridge_TRPN_parameters (dimensionless)');
    LEGEND_STATES(:,1) = strpad('q_TRPN in component environment (fmol)');
    LEGEND_STATES(:,2) = strpad('q_Ca_i in component environment (fmol)');
    LEGEND_STATES(:,3) = strpad('q_Ca_TRPN in component environment (fmol)');
    LEGEND_STATES(:,4) = strpad('q_B_XB in component environment (fmol)');
    LEGEND_STATES(:,5) = strpad('q_U_XB in component environment (fmol)');
    LEGEND_STATES(:,6) = strpad('q_W_XB in component environment (fmol)');
    LEGEND_STATES(:,7) = strpad('q_S_XB in component environment (fmol)');
    LEGEND_ALGEBRAIC(:,23) = strpad('v_R_TRPNCa in component crossbridge_TRPN (fmol_per_sec)');
    LEGEND_ALGEBRAIC(:,33) = strpad('v_R_BU in component crossbridge_TRPN (fmol_per_sec)');
    LEGEND_ALGEBRAIC(:,34) = strpad('v_R_UW in component crossbridge_TRPN (fmol_per_sec)');
    LEGEND_ALGEBRAIC(:,35) = strpad('v_R_WS in component crossbridge_TRPN (fmol_per_sec)');
    LEGEND_ALGEBRAIC(:,36) = strpad('v_R_SU in component crossbridge_TRPN (fmol_per_sec)');
    LEGEND_ALGEBRAIC(:,31) = strpad('T_total in component crossbridge_TRPN (kPa)');
    LEGEND_STATES(:,8) = strpad('SL in component crossbridge_TRPN (metre)');
    LEGEND_ALGEBRAIC(:,4) = strpad('v_Ca_stim in component environment (fmol_per_sec)');
    LEGEND_CONSTANTS(:,2) = strpad('stimPeriod in component environment (second)');
    LEGEND_CONSTANTS(:,3) = strpad('stimDuration in component environment (second)');
    LEGEND_ALGEBRAIC(:,1) = strpad('tPeriod in component environment (second)');
    LEGEND_ALGEBRAIC(:,2) = strpad('dSL in component environment (m_per_s)');
    LEGEND_CONSTANTS(:,4) = strpad('V_max in component environment (m_per_s)');
    LEGEND_CONSTANTS(:,5) = strpad('kappa_R_TRPNCa in component crossbridge_TRPN_parameters (fmol_per_sec)');
    LEGEND_CONSTANTS(:,6) = strpad('kappa_R_BU in component crossbridge_TRPN_parameters (fmol_per_sec)');
    LEGEND_CONSTANTS(:,7) = strpad('kappa_R_UW in component crossbridge_TRPN_parameters (fmol_per_sec)');
    LEGEND_CONSTANTS(:,8) = strpad('kappa_R_WS in component crossbridge_TRPN_parameters (fmol_per_sec)');
    LEGEND_CONSTANTS(:,9) = strpad('kappa_R_SU in component crossbridge_TRPN_parameters (fmol_per_sec)');
    LEGEND_CONSTANTS(:,10) = strpad('K_TRPN in component crossbridge_TRPN_parameters (per_fmol)');
    LEGEND_CONSTANTS(:,11) = strpad('K_Ca_i in component crossbridge_TRPN_parameters (per_fmol)');
    LEGEND_CONSTANTS(:,12) = strpad('K_Ca_TRPN in component crossbridge_TRPN_parameters (per_fmol)');
    LEGEND_CONSTANTS(:,13) = strpad('K_B_XB in component crossbridge_TRPN_parameters (per_fmol)');
    LEGEND_CONSTANTS(:,14) = strpad('K_U_XB in component crossbridge_TRPN_parameters (per_fmol)');
    LEGEND_CONSTANTS(:,15) = strpad('K_W_XB in component crossbridge_TRPN_parameters (per_fmol)');
    LEGEND_CONSTANTS(:,16) = strpad('K_S_XB in component crossbridge_TRPN_parameters (per_fmol)');
    LEGEND_CONSTANTS(:,17) = strpad('n_Tm in component crossbridge_TRPN_parameters (dimensionless)');
    LEGEND_CONSTANTS(:,18) = strpad('R in component constants (J_per_K_per_mol)');
    LEGEND_CONSTANTS(:,19) = strpad('T in component constants (kelvin)');
    LEGEND_ALGEBRAIC(:,7) = strpad('mu_TRPN in component crossbridge_TRPN (J_per_mol)');
    LEGEND_ALGEBRAIC(:,11) = strpad('mu_Ca_i in component crossbridge_TRPN (J_per_mol)');
    LEGEND_ALGEBRAIC(:,15) = strpad('mu_Ca_TRPN in component crossbridge_TRPN (J_per_mol)');
    LEGEND_ALGEBRAIC(:,24) = strpad('mu_B_XB in component crossbridge_TRPN (J_per_mol)');
    LEGEND_ALGEBRAIC(:,28) = strpad('mu_U_XB in component crossbridge_TRPN (J_per_mol)');
    LEGEND_ALGEBRAIC(:,30) = strpad('mu_W_XB in component crossbridge_TRPN (J_per_mol)');
    LEGEND_ALGEBRAIC(:,32) = strpad('mu_S_XB in component crossbridge_TRPN (J_per_mol)');
    LEGEND_CONSTANTS(:,20) = strpad('SL_0 in component crossbridge_TRPN (metre)');
    LEGEND_CONSTANTS(:,21) = strpad('q_MS in component crossbridge_TRPN (fmol)');
    LEGEND_CONSTANTS(:,22) = strpad('r_s in component crossbridge_TRPN (dimensionless)');
    LEGEND_CONSTANTS(:,23) = strpad('r_w in component crossbridge_TRPN (dimensionless)');
    LEGEND_CONSTANTS(:,24) = strpad('A_eff in component crossbridge_TRPN (dimensionless)');
    LEGEND_CONSTANTS(:,25) = strpad('phi in component crossbridge_TRPN (dimensionless)');
    LEGEND_CONSTANTS(:,26) = strpad('k_uw in component crossbridge_TRPN (per_sec)');
    LEGEND_CONSTANTS(:,27) = strpad('k_ws in component crossbridge_TRPN (per_sec)');
    LEGEND_STATES(:,9) = strpad('G_w in component crossbridge_TRPN (metre)');
    LEGEND_STATES(:,10) = strpad('G_s in component crossbridge_TRPN (metre)');
    LEGEND_CONSTANTS(:,37) = strpad('c_w in component crossbridge_TRPN (per_sec)');
    LEGEND_CONSTANTS(:,38) = strpad('c_s in component crossbridge_TRPN (per_sec)');
    LEGEND_CONSTANTS(:,36) = strpad('A_w in component crossbridge_TRPN (dimensionless)');
    LEGEND_CONSTANTS(:,39) = strpad('A_s in component crossbridge_TRPN (dimensionless)');
    LEGEND_ALGEBRAIC(:,16) = strpad('nu_1 in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,8) = strpad('nu_2 in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,12) = strpad('nu_3 in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,17) = strpad('nu_4 in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,9) = strpad('nu_5 in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,13) = strpad('nu_6 in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,25) = strpad('v_1 in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,5) = strpad('v_2 in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,26) = strpad('v_4 in component crossbridge_TRPN (m_per_s)');
    LEGEND_CONSTANTS(:,28) = strpad('v_to_mu in component crossbridge_TRPN (Js_per_m2)');
    LEGEND_ALGEBRAIC(:,10) = strpad('T_active in component crossbridge_TRPN (kPa)');
    LEGEND_CONSTANTS(:,29) = strpad('T_ref in component crossbridge_TRPN (kPa)');
    LEGEND_ALGEBRAIC(:,3) = strpad('F_T_S in component crossbridge_TRPN (kPa)');
    LEGEND_ALGEBRAIC(:,6) = strpad('F_T_W in component crossbridge_TRPN (kPa)');
    LEGEND_STATES(:,11) = strpad('Cdd in component crossbridge_TRPN (metre)');
    LEGEND_ALGEBRAIC(:,18) = strpad('eta in component crossbridge_TRPN (second)');
    LEGEND_CONSTANTS(:,30) = strpad('eta_l in component crossbridge_TRPN (second)');
    LEGEND_CONSTANTS(:,31) = strpad('eta_s in component crossbridge_TRPN (second)');
    LEGEND_CONSTANTS(:,32) = strpad('k in component crossbridge_TRPN (dimensionless)');
    LEGEND_CONSTANTS(:,33) = strpad('alpha in component crossbridge_TRPN (kPa)');
    LEGEND_ALGEBRAIC(:,19) = strpad('v_Cdd in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,20) = strpad('nu_d in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,21) = strpad('nu_k in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,22) = strpad('nu_f in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,27) = strpad('F_d in component crossbridge_TRPN (kPa)');
    LEGEND_ALGEBRAIC(:,14) = strpad('F_1 in component crossbridge_TRPN (kPa)');
    LEGEND_ALGEBRAIC(:,29) = strpad('T_passive in component crossbridge_TRPN (kPa)');
    LEGEND_CONSTANTS(:,34) = strpad('b in component crossbridge_TRPN (dimensionless)');
    LEGEND_CONSTANTS(:,35) = strpad('F in component constants (C_per_mol)');
    LEGEND_RATES(:,2) = strpad('d/dt q_Ca_i in component environment (fmol)');
    LEGEND_RATES(:,1) = strpad('d/dt q_TRPN in component environment (fmol)');
    LEGEND_RATES(:,3) = strpad('d/dt q_Ca_TRPN in component environment (fmol)');
    LEGEND_RATES(:,4) = strpad('d/dt q_B_XB in component environment (fmol)');
    LEGEND_RATES(:,5) = strpad('d/dt q_U_XB in component environment (fmol)');
    LEGEND_RATES(:,6) = strpad('d/dt q_W_XB in component environment (fmol)');
    LEGEND_RATES(:,7) = strpad('d/dt q_S_XB in component environment (fmol)');
    LEGEND_RATES(:,9) = strpad('d/dt G_w in component crossbridge_TRPN (metre)');
    LEGEND_RATES(:,8) = strpad('d/dt SL in component crossbridge_TRPN (metre)');
    LEGEND_RATES(:,10) = strpad('d/dt G_s in component crossbridge_TRPN (metre)');
    LEGEND_RATES(:,11) = strpad('d/dt Cdd in component crossbridge_TRPN (metre)');
    LEGEND_STATES  = LEGEND_STATES';
    LEGEND_ALGEBRAIC = LEGEND_ALGEBRAIC';
    LEGEND_RATES = LEGEND_RATES';
    LEGEND_CONSTANTS = LEGEND_CONSTANTS';
end

function [STATES, CONSTANTS] = initConsts()
    VOI = 0; CONSTANTS = []; STATES = []; ALGEBRAIC = [];
    CONSTANTS(:,1) = 2;
    STATES(:,1) = 2.57;
    STATES(:,2) = 6.82e-1;
    STATES(:,3) = 1e-6;
    STATES(:,4) = 1;
    STATES(:,5) = 0;
    STATES(:,6) = 0;
    STATES(:,7) = 0;
    STATES(:,8) = 2e-6;
    CONSTANTS(:,2) = 1;
    CONSTANTS(:,3) = 0.001;
    CONSTANTS(:,4) = 19e-6;
    CONSTANTS(:,5) = 22.8658;
    CONSTANTS(:,6) = 2.56831;
    CONSTANTS(:,7) = 0.338467;
    CONSTANTS(:,8) = 0.00796392;
    CONSTANTS(:,9) = 143351;
    CONSTANTS(:,10) = 0.428971;
    CONSTANTS(:,11) = 6.33016;
    CONSTANTS(:,12) = 0.127132;
    CONSTANTS(:,13) = 5.95481;
    CONSTANTS(:,14) = 2.23305;
    CONSTANTS(:,15) = 14.6007;
    CONSTANTS(:,16) = 3.65018e-06;
    CONSTANTS(:,17) = 1.1;
    CONSTANTS(:,18) = 8.31;
    CONSTANTS(:,19) = 310;
    CONSTANTS(:,20) = 2e-6;
    CONSTANTS(:,21) = 1e-6;
    CONSTANTS(:,22) = 0.25;
    CONSTANTS(:,23) = 0.5;
    CONSTANTS(:,24) = 25;
    CONSTANTS(:,25) = 2.23;
    CONSTANTS(:,26) = 26;
    CONSTANTS(:,27) = 4;
    STATES(:,9) = 1e-6;
    STATES(:,10) = 1e-6;
    CONSTANTS(:,28) = 1;
    CONSTANTS(:,29) = 40.5;
    STATES(:,11) = 0;
    CONSTANTS(:,30) = 200e3;
    CONSTANTS(:,31) = 20e3;
    CONSTANTS(:,32) = 7;
    CONSTANTS(:,33) = 2.1;
    CONSTANTS(:,34) = 9.1;
    CONSTANTS(:,35) = 96485;
    CONSTANTS(:,36) = ( CONSTANTS(:,24).*CONSTANTS(:,22))./( (1.00000 - CONSTANTS(:,22)).*CONSTANTS(:,23)+CONSTANTS(:,22));
    CONSTANTS(:,37) = ( CONSTANTS(:,25).*CONSTANTS(:,26).*(1.00000 - CONSTANTS(:,23)))./CONSTANTS(:,23);
    CONSTANTS(:,38) = ( CONSTANTS(:,25).*CONSTANTS(:,27).*(1.00000 - CONSTANTS(:,22)).*CONSTANTS(:,23))./CONSTANTS(:,22);
    CONSTANTS(:,39) = CONSTANTS(:,36);
    if (isempty(STATES)), warning('Initial values for states not set');, end
end

function [RATES, ALGEBRAIC] = computeRates(VOI, STATES, CONSTANTS)
	disp(VOI)
    global algebraicVariableCount;
    statesSize = size(STATES);
    statesColumnCount = statesSize(2);
    if ( statesColumnCount == 1)
        STATES = STATES';
        ALGEBRAIC = zeros(1, algebraicVariableCount);
        utilOnes = 1;
    else
        statesRowCount = statesSize(1);
        ALGEBRAIC = zeros(statesRowCount, algebraicVariableCount);
        RATES = zeros(statesRowCount, statesColumnCount);
        utilOnes = ones(statesRowCount, 1);
    end
    ALGEBRAIC(:,2) = piecewise({VOI<0.0600000,  1.00000.*CONSTANTS(:,4) , VOI>0.500000&VOI<1.10000,   - 0.10000.*CONSTANTS(:,4) },  0.00000.*CONSTANTS(:,4));
    ALGEBRAIC(:,5) = ALGEBRAIC(:,2);
    RATES(:,8) = ALGEBRAIC(:,5);
    [CONSTANTS, STATES, ALGEBRAIC] = rootfind_0(VOI, CONSTANTS, STATES, ALGEBRAIC);
    RATES(:,11) = ALGEBRAIC(:,19);
    ALGEBRAIC(:,7) =  CONSTANTS(:,18).*CONSTANTS(:,19).*log( CONSTANTS(:,10).*STATES(:,1));
    ALGEBRAIC(:,11) =  CONSTANTS(:,18).*CONSTANTS(:,19).*log( CONSTANTS(:,11).*STATES(:,2));
    ALGEBRAIC(:,15) =  CONSTANTS(:,18).*CONSTANTS(:,19).*log( CONSTANTS(:,12).*STATES(:,3));
    ALGEBRAIC(:,23) =  CONSTANTS(:,5).*(exp(( CONSTANTS(:,1).*ALGEBRAIC(:,11)+ALGEBRAIC(:,7))./( CONSTANTS(:,18).*CONSTANTS(:,19))) - exp(ALGEBRAIC(:,15)./( CONSTANTS(:,18).*CONSTANTS(:,19))));
    ALGEBRAIC(:,1) = VOI -  floor(VOI./CONSTANTS(:,2)).*CONSTANTS(:,2);
    ALGEBRAIC(:,4) = piecewise({ALGEBRAIC(:,1)>=0.300000&ALGEBRAIC(:,1)<=0.300000+CONSTANTS(:,3),  1.00000.*80.0000 }, 0.00000);
    RATES(:,2) =   - ALGEBRAIC(:,23).*CONSTANTS(:,1)+ALGEBRAIC(:,4);
    RATES(:,1) =  - ALGEBRAIC(:,23);
    RATES(:,3) = ALGEBRAIC(:,23);
    ALGEBRAIC(:,8) =   - CONSTANTS(:,36).*ALGEBRAIC(:,5);
    ALGEBRAIC(:,12) =  CONSTANTS(:,37).*STATES(:,9);
    ALGEBRAIC(:,16) =  - ALGEBRAIC(:,8) - ALGEBRAIC(:,12);
    ALGEBRAIC(:,25) = ALGEBRAIC(:,16);
    RATES(:,9) = ALGEBRAIC(:,25);
    ALGEBRAIC(:,9) =   - CONSTANTS(:,39).*ALGEBRAIC(:,5);
    ALGEBRAIC(:,13) =  CONSTANTS(:,38).*STATES(:,10);
    ALGEBRAIC(:,17) =  - ALGEBRAIC(:,9) - ALGEBRAIC(:,13);
    ALGEBRAIC(:,26) = ALGEBRAIC(:,17);
    RATES(:,10) = ALGEBRAIC(:,26);
    ALGEBRAIC(:,24) =  CONSTANTS(:,18).*CONSTANTS(:,19).*log( CONSTANTS(:,13).*STATES(:,4));
    ALGEBRAIC(:,28) =  CONSTANTS(:,18).*CONSTANTS(:,19).*log( CONSTANTS(:,14).*STATES(:,5));
    ALGEBRAIC(:,33) =  CONSTANTS(:,6).*(exp((ALGEBRAIC(:,24)+ CONSTANTS(:,17).*ALGEBRAIC(:,15))./( CONSTANTS(:,18).*CONSTANTS(:,19))) - exp((ALGEBRAIC(:,28)+ CONSTANTS(:,17).*ALGEBRAIC(:,15))./( CONSTANTS(:,18).*CONSTANTS(:,19))));
    RATES(:,4) =  - ALGEBRAIC(:,33);
    ALGEBRAIC(:,30) =  CONSTANTS(:,18).*CONSTANTS(:,19).*log( CONSTANTS(:,15).*STATES(:,6));
    ALGEBRAIC(:,34) =  CONSTANTS(:,7).*(exp(ALGEBRAIC(:,28)./( CONSTANTS(:,18).*CONSTANTS(:,19))) - exp(ALGEBRAIC(:,30)./( CONSTANTS(:,18).*CONSTANTS(:,19))));
    ALGEBRAIC(:,32) =  CONSTANTS(:,18).*CONSTANTS(:,19).*log( CONSTANTS(:,16).*STATES(:,7));
    ALGEBRAIC(:,35) =  CONSTANTS(:,8).*(exp(ALGEBRAIC(:,30)./( CONSTANTS(:,18).*CONSTANTS(:,19))) - exp(ALGEBRAIC(:,32)./( CONSTANTS(:,18).*CONSTANTS(:,19))));
    RATES(:,6) = ALGEBRAIC(:,34) - ALGEBRAIC(:,35);
    ALGEBRAIC(:,36) =  CONSTANTS(:,9).*(exp(ALGEBRAIC(:,32)./( CONSTANTS(:,18).*CONSTANTS(:,19))) - exp(ALGEBRAIC(:,28)./( CONSTANTS(:,18).*CONSTANTS(:,19))));
    RATES(:,5) = (ALGEBRAIC(:,33) - ALGEBRAIC(:,34))+ALGEBRAIC(:,36);
    RATES(:,7) = ALGEBRAIC(:,35) - ALGEBRAIC(:,36);
   RATES = RATES';
end

% Calculate algebraic variables
function ALGEBRAIC = computeAlgebraic(ALGEBRAIC, CONSTANTS, STATES, VOI)
    statesSize = size(STATES);
    statesColumnCount = statesSize(2);
    if ( statesColumnCount == 1)
        STATES = STATES';
        utilOnes = 1;
    else
        statesRowCount = statesSize(1);
        utilOnes = ones(statesRowCount, 1);
    end
    ALGEBRAIC(:,2) = piecewise({VOI<0.0600000,  1.00000.*CONSTANTS(:,4) , VOI>0.500000&VOI<1.10000,   - 0.10000.*CONSTANTS(:,4) },  0.00000.*CONSTANTS(:,4));
    ALGEBRAIC(:,5) = ALGEBRAIC(:,2);
    ALGEBRAIC(:,7) =  CONSTANTS(:,18).*CONSTANTS(:,19).*log( CONSTANTS(:,10).*STATES(:,1));
    ALGEBRAIC(:,11) =  CONSTANTS(:,18).*CONSTANTS(:,19).*log( CONSTANTS(:,11).*STATES(:,2));
    ALGEBRAIC(:,15) =  CONSTANTS(:,18).*CONSTANTS(:,19).*log( CONSTANTS(:,12).*STATES(:,3));
    ALGEBRAIC(:,23) =  CONSTANTS(:,5).*(exp(( CONSTANTS(:,1).*ALGEBRAIC(:,11)+ALGEBRAIC(:,7))./( CONSTANTS(:,18).*CONSTANTS(:,19))) - exp(ALGEBRAIC(:,15)./( CONSTANTS(:,18).*CONSTANTS(:,19))));
    ALGEBRAIC(:,1) = VOI -  floor(VOI./CONSTANTS(:,2)).*CONSTANTS(:,2);
    ALGEBRAIC(:,4) = piecewise({ALGEBRAIC(:,1)>=0.300000&ALGEBRAIC(:,1)<=0.300000+CONSTANTS(:,3),  1.00000.*80.0000 }, 0.00000);
    ALGEBRAIC(:,8) =   - CONSTANTS(:,36).*ALGEBRAIC(:,5);
    ALGEBRAIC(:,12) =  CONSTANTS(:,37).*STATES(:,9);
    ALGEBRAIC(:,16) =  - ALGEBRAIC(:,8) - ALGEBRAIC(:,12);
    ALGEBRAIC(:,25) = ALGEBRAIC(:,16);
    ALGEBRAIC(:,9) =   - CONSTANTS(:,39).*ALGEBRAIC(:,5);
    ALGEBRAIC(:,13) =  CONSTANTS(:,38).*STATES(:,10);
    ALGEBRAIC(:,17) =  - ALGEBRAIC(:,9) - ALGEBRAIC(:,13);
    ALGEBRAIC(:,26) = ALGEBRAIC(:,17);
    ALGEBRAIC(:,24) =  CONSTANTS(:,18).*CONSTANTS(:,19).*log( CONSTANTS(:,13).*STATES(:,4));
    ALGEBRAIC(:,28) =  CONSTANTS(:,18).*CONSTANTS(:,19).*log( CONSTANTS(:,14).*STATES(:,5));
    ALGEBRAIC(:,33) =  CONSTANTS(:,6).*(exp((ALGEBRAIC(:,24)+ CONSTANTS(:,17).*ALGEBRAIC(:,15))./( CONSTANTS(:,18).*CONSTANTS(:,19))) - exp((ALGEBRAIC(:,28)+ CONSTANTS(:,17).*ALGEBRAIC(:,15))./( CONSTANTS(:,18).*CONSTANTS(:,19))));
    ALGEBRAIC(:,30) =  CONSTANTS(:,18).*CONSTANTS(:,19).*log( CONSTANTS(:,15).*STATES(:,6));
    ALGEBRAIC(:,34) =  CONSTANTS(:,7).*(exp(ALGEBRAIC(:,28)./( CONSTANTS(:,18).*CONSTANTS(:,19))) - exp(ALGEBRAIC(:,30)./( CONSTANTS(:,18).*CONSTANTS(:,19))));
    ALGEBRAIC(:,32) =  CONSTANTS(:,18).*CONSTANTS(:,19).*log( CONSTANTS(:,16).*STATES(:,7));
    ALGEBRAIC(:,35) =  CONSTANTS(:,8).*(exp(ALGEBRAIC(:,30)./( CONSTANTS(:,18).*CONSTANTS(:,19))) - exp(ALGEBRAIC(:,32)./( CONSTANTS(:,18).*CONSTANTS(:,19))));
    ALGEBRAIC(:,36) =  CONSTANTS(:,9).*(exp(ALGEBRAIC(:,32)./( CONSTANTS(:,18).*CONSTANTS(:,19))) - exp(ALGEBRAIC(:,28)./( CONSTANTS(:,18).*CONSTANTS(:,19))));
    ALGEBRAIC(:,3) =  (CONSTANTS(:,29)./( CONSTANTS(:,20).*CONSTANTS(:,21).*CONSTANTS(:,22))).*STATES(:,7).*(STATES(:,10)+CONSTANTS(:,20));
    ALGEBRAIC(:,6) =  (CONSTANTS(:,29)./( CONSTANTS(:,20).*CONSTANTS(:,21).*CONSTANTS(:,22))).*STATES(:,6).*STATES(:,9);
    ALGEBRAIC(:,10) = ALGEBRAIC(:,3)+ALGEBRAIC(:,6);
    ALGEBRAIC(:,14) =  CONSTANTS(:,33).*(exp(( CONSTANTS(:,34).*STATES(:,8))./CONSTANTS(:,20)) - 1.00000);
    ALGEBRAIC(:,27) =  (( CONSTANTS(:,33).*ALGEBRAIC(:,18))./CONSTANTS(:,20)).*ALGEBRAIC(:,19);
    ALGEBRAIC(:,29) = ALGEBRAIC(:,14)+ALGEBRAIC(:,27);
    ALGEBRAIC(:,31) = ALGEBRAIC(:,10)+ALGEBRAIC(:,29);
end

% Functions required for solving differential algebraic equation
function [CONSTANTS, STATES, ALGEBRAIC] = rootfind_0(VOI, CONSTANTS_IN, STATES_IN, ALGEBRAIC_IN)
    ALGEBRAIC = ALGEBRAIC_IN;
    CONSTANTS = CONSTANTS_IN;
    STATES = STATES_IN;
    global initialGuess_0;
    if (length(initialGuess_0) ~= 5), initialGuess_0 = [0.1,0.1,0.1,0.1,0.1];, end
    options = optimset('Display', 'off', 'TolX', 1E-6);
    if length(VOI) == 1
        residualfn = @(algebraicCandidate)residualSN_0(algebraicCandidate, ALGEBRAIC, VOI, CONSTANTS, STATES);
        soln = fsolve(residualfn, initialGuess_0, options);
        initialGuess_0 = soln;
        ALGEBRAIC(:,18) = soln(1);
        ALGEBRAIC(:,19) = soln(2);
        ALGEBRAIC(:,20) = soln(3);
        ALGEBRAIC(:,21) = soln(4);
        ALGEBRAIC(:,22) = soln(5);
    else
        SET_ALGEBRAIC(:,18) = logical(1);
        SET_ALGEBRAIC(:,19) = logical(1);
        SET_ALGEBRAIC(:,20) = logical(1);
        SET_ALGEBRAIC(:,21) = logical(1);
        SET_ALGEBRAIC(:,22) = logical(1);
        for i=1:length(VOI)
            residualfn = @(algebraicCandidate)residualSN_0(algebraicCandidate, ALGEBRAIC(i,:), VOI(i), CONSTANTS, STATES(i,:));
            soln = fsolve(residualfn, initialGuess_0, options);
            initialGuess_0 = soln;
            TEMP_ALGEBRAIC(:,18) = soln(1);
            TEMP_ALGEBRAIC(:,19) = soln(2);
            TEMP_ALGEBRAIC(:,20) = soln(3);
            TEMP_ALGEBRAIC(:,21) = soln(4);
            TEMP_ALGEBRAIC(:,22) = soln(5);
            ALGEBRAIC(i,SET_ALGEBRAIC) = TEMP_ALGEBRAIC(SET_ALGEBRAIC);
        end
    end
end

function resid = residualSN_0(algebraicCandidate, ALGEBRAIC, VOI, CONSTANTS, STATES)
    ALGEBRAIC(:,18) = algebraicCandidate(1);
    ALGEBRAIC(:,19) = algebraicCandidate(2);
    ALGEBRAIC(:,20) = algebraicCandidate(3);
    ALGEBRAIC(:,21) = algebraicCandidate(4);
    ALGEBRAIC(:,22) = algebraicCandidate(5);
    resid(1) = ALGEBRAIC(:,18) - piecewise({ALGEBRAIC(:,19)>0.00000, CONSTANTS(:,30) }, CONSTANTS(:,31));
    resid(2) = ALGEBRAIC(:,19) - ALGEBRAIC(:,20);
    resid(3) = ALGEBRAIC(:,21) -  (CONSTANTS(:,32)./ALGEBRAIC(:,18)).*STATES(:,11);
    resid(4) = ALGEBRAIC(:,22) -  (CONSTANTS(:,32)./ALGEBRAIC(:,18)).*(STATES(:,8) - CONSTANTS(:,20));
    resid(5) = ALGEBRAIC(:,20) - ( - ALGEBRAIC(:,21)+ALGEBRAIC(:,22));
end

% Compute result of a piecewise function
function x = piecewise(cases, default)
    set = [0];
    for i = 1:2:length(cases)
        if (length(cases{i+1}) == 1)
            x(cases{i} & ~set,:) = cases{i+1};
        else
            x(cases{i} & ~set,:) = cases{i+1}(cases{i} & ~set);
        end
        set = set | cases{i};
        if(set), break, end
    end
    if (length(default) == 1)
        x(~set,:) = default;
    else
        x(~set,:) = default(~set);
    end
end

% Pad out or shorten strings to a set length
function strout = strpad(strin)
    req_length = 160;
    insize = size(strin,2);
    if insize > req_length
        strout = strin(1:req_length);
    else
        strout = [strin, blanks(req_length - insize)];
    end
end

