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 =35;
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.60];

    % 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)',...
        '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(:,24) = strpad('v_R_TRPNCa in component crossbridge_TRPN (fmol_per_sec)');
    LEGEND_ALGEBRAIC(:,32) = strpad('v_R_BU in component crossbridge_TRPN (fmol_per_sec)');
    LEGEND_ALGEBRAIC(:,33) = strpad('v_R_UW in component crossbridge_TRPN (fmol_per_sec)');
    LEGEND_ALGEBRAIC(:,34) = strpad('v_R_WS in component crossbridge_TRPN (fmol_per_sec)');
    LEGEND_ALGEBRAIC(:,35) = strpad('v_R_SU in component crossbridge_TRPN (fmol_per_sec)');
    LEGEND_ALGEBRAIC(:,30) = 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_CONSTANTS(:,4) = strpad('kappa_R_TRPNCa in component crossbridge_TRPN_parameters (fmol_per_sec)');
    LEGEND_CONSTANTS(:,5) = strpad('kappa_R_BU in component crossbridge_TRPN_parameters (fmol_per_sec)');
    LEGEND_CONSTANTS(:,6) = strpad('kappa_R_UW in component crossbridge_TRPN_parameters (fmol_per_sec)');
    LEGEND_CONSTANTS(:,7) = strpad('kappa_R_WS in component crossbridge_TRPN_parameters (fmol_per_sec)');
    LEGEND_CONSTANTS(:,8) = strpad('kappa_R_SU in component crossbridge_TRPN_parameters (fmol_per_sec)');
    LEGEND_CONSTANTS(:,9) = strpad('K_TRPN in component crossbridge_TRPN_parameters (per_fmol)');
    LEGEND_CONSTANTS(:,10) = strpad('K_Ca_i in component crossbridge_TRPN_parameters (per_fmol)');
    LEGEND_CONSTANTS(:,11) = strpad('K_Ca_TRPN in component crossbridge_TRPN_parameters (per_fmol)');
    LEGEND_CONSTANTS(:,12) = strpad('K_B_XB in component crossbridge_TRPN_parameters (per_fmol)');
    LEGEND_CONSTANTS(:,13) = strpad('K_U_XB in component crossbridge_TRPN_parameters (per_fmol)');
    LEGEND_CONSTANTS(:,14) = strpad('K_W_XB in component crossbridge_TRPN_parameters (per_fmol)');
    LEGEND_CONSTANTS(:,15) = strpad('K_S_XB in component crossbridge_TRPN_parameters (per_fmol)');
    LEGEND_CONSTANTS(:,16) = strpad('n_Tm in component crossbridge_TRPN_parameters (dimensionless)');
    LEGEND_CONSTANTS(:,17) = strpad('R in component constants (J_per_K_per_mol)');
    LEGEND_CONSTANTS(:,18) = strpad('T in component constants (kelvin)');
    LEGEND_ALGEBRAIC(:,8) = strpad('mu_TRPN in component crossbridge_TRPN (J_per_mol)');
    LEGEND_ALGEBRAIC(:,12) = strpad('mu_Ca_i in component crossbridge_TRPN (J_per_mol)');
    LEGEND_ALGEBRAIC(:,16) = strpad('mu_Ca_TRPN in component crossbridge_TRPN (J_per_mol)');
    LEGEND_ALGEBRAIC(:,25) = strpad('mu_B_XB in component crossbridge_TRPN (J_per_mol)');
    LEGEND_ALGEBRAIC(:,27) = strpad('mu_U_XB in component crossbridge_TRPN (J_per_mol)');
    LEGEND_ALGEBRAIC(:,29) = strpad('mu_W_XB in component crossbridge_TRPN (J_per_mol)');
    LEGEND_ALGEBRAIC(:,31) = strpad('mu_S_XB in component crossbridge_TRPN (J_per_mol)');
    LEGEND_CONSTANTS(:,19) = strpad('SL_0 in component crossbridge_TRPN (metre)');
    LEGEND_CONSTANTS(:,20) = strpad('q_MS in component crossbridge_TRPN (fmol)');
    LEGEND_CONSTANTS(:,21) = strpad('r_s in component crossbridge_TRPN (dimensionless)');
    LEGEND_CONSTANTS(:,22) = strpad('r_w in component crossbridge_TRPN (dimensionless)');
    LEGEND_CONSTANTS(:,23) = strpad('A_eff in component crossbridge_TRPN (dimensionless)');
    LEGEND_CONSTANTS(:,24) = strpad('phi in component crossbridge_TRPN (dimensionless)');
    LEGEND_CONSTANTS(:,25) = strpad('k_uw in component crossbridge_TRPN (per_sec)');
    LEGEND_CONSTANTS(:,26) = 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(:,36) = strpad('c_w in component crossbridge_TRPN (per_sec)');
    LEGEND_CONSTANTS(:,37) = strpad('c_s in component crossbridge_TRPN (per_sec)');
    LEGEND_CONSTANTS(:,38) = strpad('A_w in component crossbridge_TRPN (dimensionless)');
    LEGEND_CONSTANTS(:,39) = strpad('A_s in component crossbridge_TRPN (dimensionless)');
    LEGEND_ALGEBRAIC(:,13) = strpad('nu_1 in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,5) = strpad('nu_2 in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,9) = strpad('nu_3 in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,14) = strpad('nu_4 in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,6) = strpad('nu_5 in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,10) = strpad('nu_6 in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,17) = strpad('v_1 in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,2) = strpad('v_2 in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,18) = strpad('v_4 in component crossbridge_TRPN (m_per_s)');
    LEGEND_CONSTANTS(:,27) = strpad('v_to_mu in component crossbridge_TRPN (Js_per_m2)');
    LEGEND_CONSTANTS(:,28) = strpad('V_max in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,11) = 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(:,7) = strpad('F_T_W in component crossbridge_TRPN (kPa)');
    LEGEND_STATES(:,11) = strpad('Cdd in component crossbridge_TRPN (metre)');
    LEGEND_ALGEBRAIC(:,19) = 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(:,20) = strpad('v_Cdd in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,21) = strpad('nu_d in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,22) = strpad('nu_k in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,23) = strpad('nu_f in component crossbridge_TRPN (m_per_s)');
    LEGEND_ALGEBRAIC(:,26) = strpad('F_d in component crossbridge_TRPN (kPa)');
    LEGEND_ALGEBRAIC(:,15) = strpad('F_1 in component crossbridge_TRPN (kPa)');
    LEGEND_ALGEBRAIC(:,28) = 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) = 22.8658;
    CONSTANTS(:,5) = 2.56831;
    CONSTANTS(:,6) = 0.338467;
    CONSTANTS(:,7) = 0.00796392;
    CONSTANTS(:,8) = 143351;
    CONSTANTS(:,9) = 0.428971;
    CONSTANTS(:,10) = 6.33016;
    CONSTANTS(:,11) = 0.127132;
    CONSTANTS(:,12) = 5.95481;
    CONSTANTS(:,13) = 2.23305;
    CONSTANTS(:,14) = 14.6007;
    CONSTANTS(:,15) = 3.65018e-06;
    CONSTANTS(:,16) = 1.1;
    CONSTANTS(:,17) = 8.31;
    CONSTANTS(:,18) = 310;
    CONSTANTS(:,19) = 2e-6;
    CONSTANTS(:,20) = 1e-6;
    CONSTANTS(:,21) = 0.25;
    CONSTANTS(:,22) = 0.5;
    CONSTANTS(:,23) = 25;
    CONSTANTS(:,24) = 2.23;
    CONSTANTS(:,25) = 26;
    CONSTANTS(:,26) = 4;
    STATES(:,9) = 1e-6;
    STATES(:,10) = 1e-6;
    CONSTANTS(:,27) = 1;
    CONSTANTS(:,28) = 19e-6;
    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(:,25).*(1.00000 - CONSTANTS(:,22)))./CONSTANTS(:,22);
    CONSTANTS(:,37) = ( CONSTANTS(:,24).*CONSTANTS(:,26).*(1.00000 - CONSTANTS(:,21)).*CONSTANTS(:,22))./CONSTANTS(:,21);
    CONSTANTS(:,38) = ( CONSTANTS(:,23).*CONSTANTS(:,21))./( (1.00000 - CONSTANTS(:,21)).*CONSTANTS(:,22)+CONSTANTS(:,21));
    CONSTANTS(:,39) = CONSTANTS(:,38);
    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(:,28) , VOI>0.500000&VOI<0.560000,   - 1.00000.*CONSTANTS(:,28) },  0.00000.*CONSTANTS(:,28));
    RATES(:,8) = ALGEBRAIC(:,2);
    ALGEBRAIC(:,5) =   - CONSTANTS(:,38).*ALGEBRAIC(:,2);
    ALGEBRAIC(:,9) =  CONSTANTS(:,36).*STATES(:,9);
    ALGEBRAIC(:,13) =  - ALGEBRAIC(:,5) - ALGEBRAIC(:,9);
    ALGEBRAIC(:,17) = ALGEBRAIC(:,13);
    RATES(:,9) = ALGEBRAIC(:,17);
    ALGEBRAIC(:,6) =   - CONSTANTS(:,39).*ALGEBRAIC(:,2);
    ALGEBRAIC(:,10) =  CONSTANTS(:,37).*STATES(:,10);
    ALGEBRAIC(:,14) =  - ALGEBRAIC(:,6) - ALGEBRAIC(:,10);
    ALGEBRAIC(:,18) = ALGEBRAIC(:,14);
    RATES(:,10) = ALGEBRAIC(:,18);
    [CONSTANTS, STATES, ALGEBRAIC] = rootfind_0(VOI, CONSTANTS, STATES, ALGEBRAIC);
    RATES(:,11) = ALGEBRAIC(:,20);
    ALGEBRAIC(:,8) =  CONSTANTS(:,17).*CONSTANTS(:,18).*log( CONSTANTS(:,9).*STATES(:,1));
    ALGEBRAIC(:,12) =  CONSTANTS(:,17).*CONSTANTS(:,18).*log( CONSTANTS(:,10).*STATES(:,2));
    ALGEBRAIC(:,16) =  CONSTANTS(:,17).*CONSTANTS(:,18).*log( CONSTANTS(:,11).*STATES(:,3));
    ALGEBRAIC(:,24) =  CONSTANTS(:,4).*(exp(( CONSTANTS(:,1).*ALGEBRAIC(:,12)+ALGEBRAIC(:,8))./( CONSTANTS(:,17).*CONSTANTS(:,18))) - exp(ALGEBRAIC(:,16)./( CONSTANTS(:,17).*CONSTANTS(:,18))));
    ALGEBRAIC(:,1) = VOI -  floor(VOI./CONSTANTS(:,2)).*CONSTANTS(:,2);
    ALGEBRAIC(:,4) = piecewise({ALGEBRAIC(:,1)>=0.300000&ALGEBRAIC(:,1)<=0.300000+CONSTANTS(:,3),  0.00000.*80.00000 }, 0.00000);
    RATES(:,2) =   - ALGEBRAIC(:,24).*CONSTANTS(:,1)+ALGEBRAIC(:,4);
    RATES(:,1) =  - ALGEBRAIC(:,24);
    RATES(:,3) = ALGEBRAIC(:,24);
    ALGEBRAIC(:,25) =  CONSTANTS(:,17).*CONSTANTS(:,18).*log( CONSTANTS(:,12).*STATES(:,4));
    ALGEBRAIC(:,27) =  CONSTANTS(:,17).*CONSTANTS(:,18).*log( CONSTANTS(:,13).*STATES(:,5));
    ALGEBRAIC(:,32) =  CONSTANTS(:,5).*(exp((ALGEBRAIC(:,25)+ CONSTANTS(:,16).*ALGEBRAIC(:,16))./( CONSTANTS(:,17).*CONSTANTS(:,18))) - exp((ALGEBRAIC(:,27)+ CONSTANTS(:,16).*ALGEBRAIC(:,16))./( CONSTANTS(:,17).*CONSTANTS(:,18))));
    RATES(:,4) =  - ALGEBRAIC(:,32);
    ALGEBRAIC(:,29) =  CONSTANTS(:,17).*CONSTANTS(:,18).*log( CONSTANTS(:,14).*STATES(:,6));
    ALGEBRAIC(:,33) =  CONSTANTS(:,6).*(exp(ALGEBRAIC(:,27)./( CONSTANTS(:,17).*CONSTANTS(:,18))) - exp(ALGEBRAIC(:,29)./( CONSTANTS(:,17).*CONSTANTS(:,18))));
    ALGEBRAIC(:,31) =  CONSTANTS(:,17).*CONSTANTS(:,18).*log( CONSTANTS(:,15).*STATES(:,7));
    ALGEBRAIC(:,34) =  CONSTANTS(:,7).*(exp(ALGEBRAIC(:,29)./( CONSTANTS(:,17).*CONSTANTS(:,18))) - exp(ALGEBRAIC(:,31)./( CONSTANTS(:,17).*CONSTANTS(:,18))));
    RATES(:,6) = ALGEBRAIC(:,33) - ALGEBRAIC(:,34);
    ALGEBRAIC(:,35) =  CONSTANTS(:,8).*(exp(ALGEBRAIC(:,31)./( CONSTANTS(:,17).*CONSTANTS(:,18))) - exp(ALGEBRAIC(:,27)./( CONSTANTS(:,17).*CONSTANTS(:,18))));
    RATES(:,5) = (ALGEBRAIC(:,32) - ALGEBRAIC(:,33))+ALGEBRAIC(:,35);
    RATES(:,7) = ALGEBRAIC(:,34) - ALGEBRAIC(:,35);
   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(:,28) , VOI>0.500000&VOI<0.560000,   - 1.00000.*CONSTANTS(:,28) },  0.00000.*CONSTANTS(:,28));
    ALGEBRAIC(:,5) =   - CONSTANTS(:,38).*ALGEBRAIC(:,2);
    ALGEBRAIC(:,9) =  CONSTANTS(:,36).*STATES(:,9);
    ALGEBRAIC(:,13) =  - ALGEBRAIC(:,5) - ALGEBRAIC(:,9);
    ALGEBRAIC(:,17) = ALGEBRAIC(:,13);
    ALGEBRAIC(:,6) =   - CONSTANTS(:,39).*ALGEBRAIC(:,2);
    ALGEBRAIC(:,10) =  CONSTANTS(:,37).*STATES(:,10);
    ALGEBRAIC(:,14) =  - ALGEBRAIC(:,6) - ALGEBRAIC(:,10);
    ALGEBRAIC(:,18) = ALGEBRAIC(:,14);
    ALGEBRAIC(:,8) =  CONSTANTS(:,17).*CONSTANTS(:,18).*log( CONSTANTS(:,9).*STATES(:,1));
    ALGEBRAIC(:,12) =  CONSTANTS(:,17).*CONSTANTS(:,18).*log( CONSTANTS(:,10).*STATES(:,2));
    ALGEBRAIC(:,16) =  CONSTANTS(:,17).*CONSTANTS(:,18).*log( CONSTANTS(:,11).*STATES(:,3));
    ALGEBRAIC(:,24) =  CONSTANTS(:,4).*(exp(( CONSTANTS(:,1).*ALGEBRAIC(:,12)+ALGEBRAIC(:,8))./( CONSTANTS(:,17).*CONSTANTS(:,18))) - exp(ALGEBRAIC(:,16)./( CONSTANTS(:,17).*CONSTANTS(:,18))));
    ALGEBRAIC(:,1) = VOI -  floor(VOI./CONSTANTS(:,2)).*CONSTANTS(:,2);
    ALGEBRAIC(:,4) = piecewise({ALGEBRAIC(:,1)>=0.300000&ALGEBRAIC(:,1)<=0.300000+CONSTANTS(:,3),  0.00000.*80.00000 }, 0.00000);
    ALGEBRAIC(:,25) =  CONSTANTS(:,17).*CONSTANTS(:,18).*log( CONSTANTS(:,12).*STATES(:,4));
    ALGEBRAIC(:,27) =  CONSTANTS(:,17).*CONSTANTS(:,18).*log( CONSTANTS(:,13).*STATES(:,5));
    ALGEBRAIC(:,32) =  CONSTANTS(:,5).*(exp((ALGEBRAIC(:,25)+ CONSTANTS(:,16).*ALGEBRAIC(:,16))./( CONSTANTS(:,17).*CONSTANTS(:,18))) - exp((ALGEBRAIC(:,27)+ CONSTANTS(:,16).*ALGEBRAIC(:,16))./( CONSTANTS(:,17).*CONSTANTS(:,18))));
    ALGEBRAIC(:,29) =  CONSTANTS(:,17).*CONSTANTS(:,18).*log( CONSTANTS(:,14).*STATES(:,6));
    ALGEBRAIC(:,33) =  CONSTANTS(:,6).*(exp(ALGEBRAIC(:,27)./( CONSTANTS(:,17).*CONSTANTS(:,18))) - exp(ALGEBRAIC(:,29)./( CONSTANTS(:,17).*CONSTANTS(:,18))));
    ALGEBRAIC(:,31) =  CONSTANTS(:,17).*CONSTANTS(:,18).*log( CONSTANTS(:,15).*STATES(:,7));
    ALGEBRAIC(:,34) =  CONSTANTS(:,7).*(exp(ALGEBRAIC(:,29)./( CONSTANTS(:,17).*CONSTANTS(:,18))) - exp(ALGEBRAIC(:,31)./( CONSTANTS(:,17).*CONSTANTS(:,18))));
    ALGEBRAIC(:,35) =  CONSTANTS(:,8).*(exp(ALGEBRAIC(:,31)./( CONSTANTS(:,17).*CONSTANTS(:,18))) - exp(ALGEBRAIC(:,27)./( CONSTANTS(:,17).*CONSTANTS(:,18))));
    ALGEBRAIC(:,3) =  (CONSTANTS(:,29)./( CONSTANTS(:,19).*CONSTANTS(:,20).*CONSTANTS(:,21))).*STATES(:,7).*(STATES(:,10)+CONSTANTS(:,19));
    ALGEBRAIC(:,7) =  (CONSTANTS(:,29)./( CONSTANTS(:,19).*CONSTANTS(:,20).*CONSTANTS(:,21))).*STATES(:,6).*STATES(:,9);
    ALGEBRAIC(:,11) = ALGEBRAIC(:,3)+ALGEBRAIC(:,7);
    ALGEBRAIC(:,15) =  CONSTANTS(:,33).*(exp(( CONSTANTS(:,34).*STATES(:,8))./CONSTANTS(:,19)) - 1.00000);
    ALGEBRAIC(:,26) =  (( CONSTANTS(:,33).*ALGEBRAIC(:,19))./CONSTANTS(:,19)).*ALGEBRAIC(:,20);
    ALGEBRAIC(:,28) = ALGEBRAIC(:,15)+ALGEBRAIC(:,26);
    ALGEBRAIC(:,30) = ALGEBRAIC(:,11)+ALGEBRAIC(:,28);
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(:,19) = soln(1);
        ALGEBRAIC(:,20) = soln(2);
        ALGEBRAIC(:,21) = soln(3);
        ALGEBRAIC(:,22) = soln(4);
        ALGEBRAIC(:,23) = soln(5);
    else
        SET_ALGEBRAIC(:,19) = logical(1);
        SET_ALGEBRAIC(:,20) = logical(1);
        SET_ALGEBRAIC(:,21) = logical(1);
        SET_ALGEBRAIC(:,22) = logical(1);
        SET_ALGEBRAIC(:,23) = 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(:,19) = soln(1);
            TEMP_ALGEBRAIC(:,20) = soln(2);
            TEMP_ALGEBRAIC(:,21) = soln(3);
            TEMP_ALGEBRAIC(:,22) = soln(4);
            TEMP_ALGEBRAIC(:,23) = soln(5);
            ALGEBRAIC(i,SET_ALGEBRAIC) = TEMP_ALGEBRAIC(SET_ALGEBRAIC);
        end
    end
end

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

