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 =32;
end
% There are a total of 9 entries in each of the rate and state variable arrays.
% There are a total of 41 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, 1];

    % Set numerical accuracy options for ODE solver
    options = odeset('RelTol', 1e-06, '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_B in component environment (fmol)',...
    'q_U in component environment (fmol)',...
    'q_W in component environment (fmol)',...
    'q_S in component environment (fmol)',...
    'q_Ca_TRPN in component environment (fmol)',...
    'G_w in component crossbridge (metre)',...
    'G_s in component crossbridge (metre)',...
    'T_active in component crossbridge (kPa)',...
    'T_passive in component crossbridge (kPa)',...
    'T_total in component crossbridge (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))))
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
    suptitle(titlestr)    
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('q_B_init in component environment (fmol)');
    LEGEND_CONSTANTS(:,2) = strpad('q_U_init in component environment (fmol)');
    LEGEND_CONSTANTS(:,3) = strpad('q_W_init in component environment (fmol)');
    LEGEND_CONSTANTS(:,4) = strpad('q_S_init in component environment (fmol)');
    LEGEND_CONSTANTS(:,5) = strpad('q_Ca_TRPN_init in component environment (fmol)');
    LEGEND_ALGEBRAIC(:,1) = strpad('q_B in component environment (fmol)');
    LEGEND_ALGEBRAIC(:,5) = strpad('q_U in component environment (fmol)');
    LEGEND_ALGEBRAIC(:,9) = strpad('q_W in component environment (fmol)');
    LEGEND_ALGEBRAIC(:,13) = strpad('q_S in component environment (fmol)');
    LEGEND_ALGEBRAIC(:,15) = strpad('q_Ca_TRPN in component environment (fmol)');
    LEGEND_STATES(:,1) = strpad('q_B in component crossbridge (fmol)');
    LEGEND_STATES(:,2) = strpad('q_U in component crossbridge (fmol)');
    LEGEND_STATES(:,3) = strpad('q_W in component crossbridge (fmol)');
    LEGEND_STATES(:,4) = strpad('q_S in component crossbridge (fmol)');
    LEGEND_STATES(:,5) = strpad('q_Ca_TRPN in component crossbridge (fmol)');
    LEGEND_ALGEBRAIC(:,14) = strpad('T_active in component crossbridge (kPa)');
    LEGEND_STATES(:,6) = strpad('SL in component crossbridge (metre)');
    LEGEND_CONSTANTS(:,6) = strpad('kappa_R_BU in component crossbridge_parameters (fmol_per_sec)');
    LEGEND_CONSTANTS(:,7) = strpad('kappa_R_UW in component crossbridge_parameters (fmol_per_sec)');
    LEGEND_CONSTANTS(:,8) = strpad('kappa_R_WS in component crossbridge_parameters (fmol_per_sec)');
    LEGEND_CONSTANTS(:,9) = strpad('kappa_R_SU in component crossbridge_parameters (fmol_per_sec)');
    LEGEND_CONSTANTS(:,10) = strpad('K_B in component crossbridge_parameters (per_fmol)');
    LEGEND_CONSTANTS(:,11) = strpad('K_U in component crossbridge_parameters (per_fmol)');
    LEGEND_CONSTANTS(:,12) = strpad('K_W in component crossbridge_parameters (per_fmol)');
    LEGEND_CONSTANTS(:,13) = strpad('K_S in component crossbridge_parameters (per_fmol)');
    LEGEND_CONSTANTS(:,14) = strpad('K_Ca_TRPN in component crossbridge_parameters (per_fmol)');
    LEGEND_CONSTANTS(:,15) = strpad('R in component constants (J_per_K_per_mol)');
    LEGEND_CONSTANTS(:,16) = strpad('T in component constants (kelvin)');
    LEGEND_CONSTANTS(:,17) = strpad('n_Tm in component crossbridge (dimensionless)');
    LEGEND_ALGEBRAIC(:,20) = strpad('mu_B in component crossbridge (J_per_mol)');
    LEGEND_ALGEBRAIC(:,22) = strpad('mu_U in component crossbridge (J_per_mol)');
    LEGEND_ALGEBRAIC(:,24) = strpad('mu_W in component crossbridge (J_per_mol)');
    LEGEND_ALGEBRAIC(:,26) = strpad('mu_S in component crossbridge (J_per_mol)');
    LEGEND_ALGEBRAIC(:,28) = strpad('mu_Ca_TRPN in component crossbridge (J_per_mol)');
    LEGEND_ALGEBRAIC(:,29) = strpad('v_R_BU in component crossbridge (fmol_per_sec)');
    LEGEND_ALGEBRAIC(:,30) = strpad('v_R_UW in component crossbridge (fmol_per_sec)');
    LEGEND_ALGEBRAIC(:,31) = strpad('v_R_WS in component crossbridge (fmol_per_sec)');
    LEGEND_ALGEBRAIC(:,32) = strpad('v_R_SU in component crossbridge (fmol_per_sec)');
    LEGEND_CONSTANTS(:,18) = strpad('SL_0 in component crossbridge (metre)');
    LEGEND_CONSTANTS(:,19) = strpad('q_MS in component crossbridge (fmol)');
    LEGEND_CONSTANTS(:,20) = strpad('r_s in component crossbridge (dimensionless)');
    LEGEND_CONSTANTS(:,21) = strpad('r_w in component crossbridge (dimensionless)');
    LEGEND_CONSTANTS(:,22) = strpad('A_eff in component crossbridge (dimensionless)');
    LEGEND_CONSTANTS(:,23) = strpad('phi in component crossbridge (dimensionless)');
    LEGEND_CONSTANTS(:,24) = strpad('k_uw in component crossbridge (per_sec)');
    LEGEND_CONSTANTS(:,25) = strpad('k_ws in component crossbridge (per_sec)');
    LEGEND_STATES(:,7) = strpad('G_w in component crossbridge (metre)');
    LEGEND_STATES(:,8) = strpad('G_s in component crossbridge (metre)');
    LEGEND_CONSTANTS(:,34) = strpad('c_w in component crossbridge (per_sec)');
    LEGEND_CONSTANTS(:,35) = strpad('c_s in component crossbridge (per_sec)');
    LEGEND_CONSTANTS(:,36) = strpad('A_w in component crossbridge (dimensionless)');
    LEGEND_CONSTANTS(:,37) = strpad('A_s in component crossbridge (dimensionless)');
    LEGEND_ALGEBRAIC(:,6) = strpad('mu_1 in component crossbridge (J_per_m)');
    LEGEND_CONSTANTS(:,38) = strpad('mu_2 in component crossbridge (J_per_m)');
    LEGEND_ALGEBRAIC(:,2) = strpad('mu_3 in component crossbridge (J_per_m)');
    LEGEND_ALGEBRAIC(:,7) = strpad('mu_4 in component crossbridge (J_per_m)');
    LEGEND_CONSTANTS(:,39) = strpad('mu_5 in component crossbridge (J_per_m)');
    LEGEND_ALGEBRAIC(:,3) = strpad('mu_6 in component crossbridge (J_per_m)');
    LEGEND_ALGEBRAIC(:,10) = strpad('v_1 in component crossbridge (m_per_s)');
    LEGEND_CONSTANTS(:,26) = strpad('v_2 in component crossbridge (m_per_s)');
    LEGEND_ALGEBRAIC(:,11) = strpad('v_4 in component crossbridge (m_per_s)');
    LEGEND_CONSTANTS(:,27) = strpad('v_to_mu in component crossbridge (Js_per_m2)');
    LEGEND_CONSTANTS(:,28) = strpad('T_ref in component crossbridge (kPa)');
    LEGEND_ALGEBRAIC(:,12) = strpad('mu_T_a in component crossbridge (kPa)');
    LEGEND_ALGEBRAIC(:,4) = strpad('mu_T_S in component crossbridge (kPa)');
    LEGEND_ALGEBRAIC(:,8) = strpad('mu_T_W in component crossbridge (kPa)');
    LEGEND_STATES(:,9) = strpad('Cdd in component crossbridge (metre)');
    LEGEND_ALGEBRAIC(:,16) = strpad('eta in component crossbridge (per_sec)');
    LEGEND_CONSTANTS(:,29) = strpad('eta_l in component crossbridge (per_sec)');
    LEGEND_CONSTANTS(:,30) = strpad('eta_s in component crossbridge (per_sec)');
    LEGEND_CONSTANTS(:,31) = strpad('k in component crossbridge (dimensionless)');
    LEGEND_CONSTANTS(:,32) = strpad('alpha in component crossbridge (kPa)');
    LEGEND_ALGEBRAIC(:,21) = strpad('v_Cdd in component crossbridge (m_per_s)');
    LEGEND_ALGEBRAIC(:,17) = strpad('mu_d in component crossbridge (J_per_m)');
    LEGEND_ALGEBRAIC(:,18) = strpad('mu_k in component crossbridge (J_per_m)');
    LEGEND_ALGEBRAIC(:,19) = strpad('mu_f in component crossbridge (J_per_m)');
    LEGEND_ALGEBRAIC(:,23) = strpad('mu_T_passive in component crossbridge (kPa)');
    LEGEND_ALGEBRAIC(:,25) = strpad('T_passive in component crossbridge (kPa)');
    LEGEND_ALGEBRAIC(:,27) = strpad('T_total in component crossbridge (kPa)');
    LEGEND_CONSTANTS(:,33) = strpad('F in component constants (C_per_mol)');
    LEGEND_RATES(:,1) = strpad('d/dt q_B in component crossbridge (fmol)');
    LEGEND_RATES(:,2) = strpad('d/dt q_U in component crossbridge (fmol)');
    LEGEND_RATES(:,3) = strpad('d/dt q_W in component crossbridge (fmol)');
    LEGEND_RATES(:,4) = strpad('d/dt q_S in component crossbridge (fmol)');
    LEGEND_RATES(:,5) = strpad('d/dt q_Ca_TRPN in component crossbridge (fmol)');
    LEGEND_RATES(:,7) = strpad('d/dt G_w in component crossbridge (metre)');
    LEGEND_RATES(:,6) = strpad('d/dt SL in component crossbridge (metre)');
    LEGEND_RATES(:,8) = strpad('d/dt G_s in component crossbridge (metre)');
    LEGEND_RATES(:,9) = strpad('d/dt Cdd in component crossbridge (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) = 1;
    CONSTANTS(:,2) = 0;
    CONSTANTS(:,3) = 0;
    CONSTANTS(:,4) = 0;
    CONSTANTS(:,5) = 2;
    STATES(:,1) = 1e-16;
    STATES(:,2) = 1e-16;
    STATES(:,3) = 1e-16;
    STATES(:,4) = 1e-16;
    STATES(:,5) = 1e-16;
    STATES(:,6) = 1e-6;
    CONSTANTS(:,6) = 3.15188;
    CONSTANTS(:,7) = 0.32871;
    CONSTANTS(:,8) = 0.00773435;
    CONSTANTS(:,9) = 139218;
    CONSTANTS(:,10) = 6.13156;
    CONSTANTS(:,11) = 2.29933;
    CONSTANTS(:,12) = 15.0341;
    CONSTANTS(:,13) = 3.75853e-06;
    CONSTANTS(:,14) = 0.10277;
    CONSTANTS(:,15) = 8.31;
    CONSTANTS(:,16) = 310;
    CONSTANTS(:,17) = 1.1;
    CONSTANTS(:,18) = 2e-6;
    CONSTANTS(:,19) = 1e-6;
    CONSTANTS(:,20) = 0.25;
    CONSTANTS(:,21) = 0.5;
    CONSTANTS(:,22) = 25;
    CONSTANTS(:,23) = 2.23;
    CONSTANTS(:,24) = 26;
    CONSTANTS(:,25) = 4;
    STATES(:,7) = 1e-6;
    STATES(:,8) = 1e-6;
    CONSTANTS(:,26) = 0;
    CONSTANTS(:,27) = 1;
    CONSTANTS(:,28) = 40.5;
    STATES(:,9) = 0;
    CONSTANTS(:,29) = 200e3;
    CONSTANTS(:,30) = 20e3;     % eta_s
    CONSTANTS(:,31) = 7;
    CONSTANTS(:,32) = 2.1;
    CONSTANTS(:,33) = 96485;
    CONSTANTS(:,34) = ( CONSTANTS(:,23).*CONSTANTS(:,24).*(1.00000 - CONSTANTS(:,21)))./CONSTANTS(:,21);
    CONSTANTS(:,35) = ( CONSTANTS(:,23).*CONSTANTS(:,25).*(1.00000 - CONSTANTS(:,20)).*CONSTANTS(:,21))./CONSTANTS(:,20);
    CONSTANTS(:,36) = ( CONSTANTS(:,22).*CONSTANTS(:,20))./( (1.00000 - CONSTANTS(:,20)).*CONSTANTS(:,21)+CONSTANTS(:,20));
    CONSTANTS(:,39) = 0.000000;
    CONSTANTS(:,40) = CONSTANTS(:,26);
    CONSTANTS(:,37) = CONSTANTS(:,36);
    CONSTANTS(:,38) =   - CONSTANTS(:,36).*CONSTANTS(:,26).*CONSTANTS(:,27);
    CONSTANTS(:,39) =   - CONSTANTS(:,37).*CONSTANTS(:,26).*CONSTANTS(:,27);
    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
    RATES(:,5) = 0;%CONSTANTS(:,39);
    RATES(:,6) = CONSTANTS(:,26);
    ALGEBRAIC(:,2) =  CONSTANTS(:,34).*STATES(:,7).*CONSTANTS(:,27);
    ALGEBRAIC(:,6) =  - CONSTANTS(:,38) - ALGEBRAIC(:,2);
    ALGEBRAIC(:,10) = ALGEBRAIC(:,6)./CONSTANTS(:,27);
    RATES(:,7) = ALGEBRAIC(:,10);
    ALGEBRAIC(:,3) =  CONSTANTS(:,35).*STATES(:,8).*CONSTANTS(:,27);
    ALGEBRAIC(:,7) =  - CONSTANTS(:,39) - ALGEBRAIC(:,3);
    ALGEBRAIC(:,11) = ALGEBRAIC(:,7)./CONSTANTS(:,27);
    RATES(:,8) = ALGEBRAIC(:,11);
    [CONSTANTS, STATES, ALGEBRAIC] = rootfind_0(VOI, CONSTANTS, STATES, ALGEBRAIC);
    ALGEBRAIC(:,21) = ALGEBRAIC(:,17)./CONSTANTS(:,27);
    RATES(:,9) = ALGEBRAIC(:,21);
    ALGEBRAIC(:,1) = STATES(:,1)+CONSTANTS(:,1);
    ALGEBRAIC(:,20) =  CONSTANTS(:,15).*CONSTANTS(:,16).*log( CONSTANTS(:,10).*ALGEBRAIC(:,1));
    ALGEBRAIC(:,5) = STATES(:,2)+CONSTANTS(:,2);
    ALGEBRAIC(:,22) =  CONSTANTS(:,15).*CONSTANTS(:,16).*log( CONSTANTS(:,11).*ALGEBRAIC(:,5));
    ALGEBRAIC(:,15) = STATES(:,5)+CONSTANTS(:,5);
    ALGEBRAIC(:,28) =  CONSTANTS(:,15).*CONSTANTS(:,16).*log( CONSTANTS(:,14).*ALGEBRAIC(:,15));
    ALGEBRAIC(:,29) =  CONSTANTS(:,6).*(exp((ALGEBRAIC(:,20)+ CONSTANTS(:,17).*ALGEBRAIC(:,28))./( CONSTANTS(:,15).*CONSTANTS(:,16))) - exp((ALGEBRAIC(:,22)+ CONSTANTS(:,17).*ALGEBRAIC(:,28))./( CONSTANTS(:,15).*CONSTANTS(:,16))));
    RATES(:,1) =  - ALGEBRAIC(:,29);
    ALGEBRAIC(:,9) = STATES(:,3)+CONSTANTS(:,3);
    ALGEBRAIC(:,24) =  CONSTANTS(:,15).*CONSTANTS(:,16).*log( CONSTANTS(:,12).*ALGEBRAIC(:,9));
    ALGEBRAIC(:,30) =  CONSTANTS(:,7).*(exp(ALGEBRAIC(:,22)./( CONSTANTS(:,15).*CONSTANTS(:,16))) - exp(ALGEBRAIC(:,24)./( CONSTANTS(:,15).*CONSTANTS(:,16))));
    ALGEBRAIC(:,13) = STATES(:,4)+CONSTANTS(:,4);
    ALGEBRAIC(:,26) =  CONSTANTS(:,15).*CONSTANTS(:,16).*log( CONSTANTS(:,13).*ALGEBRAIC(:,13));
    ALGEBRAIC(:,31) =  CONSTANTS(:,8).*(exp(ALGEBRAIC(:,24)./( CONSTANTS(:,15).*CONSTANTS(:,16))) - exp(ALGEBRAIC(:,26)./( CONSTANTS(:,15).*CONSTANTS(:,16))));
    RATES(:,3) = ALGEBRAIC(:,30) - ALGEBRAIC(:,31);
    ALGEBRAIC(:,32) =  CONSTANTS(:,9).*(exp(ALGEBRAIC(:,26)./( CONSTANTS(:,15).*CONSTANTS(:,16))) - exp(ALGEBRAIC(:,22)./( CONSTANTS(:,15).*CONSTANTS(:,16))));
    RATES(:,2) = (ALGEBRAIC(:,29) - ALGEBRAIC(:,30))+ALGEBRAIC(:,32);
    RATES(:,4) = ALGEBRAIC(:,31) - ALGEBRAIC(:,32);
   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) =  CONSTANTS(:,34).*STATES(:,7).*CONSTANTS(:,27);
    ALGEBRAIC(:,6) =  - CONSTANTS(:,38) - ALGEBRAIC(:,2);
    ALGEBRAIC(:,10) = ALGEBRAIC(:,6)./CONSTANTS(:,27);
    ALGEBRAIC(:,3) =  CONSTANTS(:,35).*STATES(:,8).*CONSTANTS(:,27);
    ALGEBRAIC(:,7) =  - CONSTANTS(:,39) - ALGEBRAIC(:,3);
    ALGEBRAIC(:,11) = ALGEBRAIC(:,7)./CONSTANTS(:,27);
    ALGEBRAIC(:,21) = ALGEBRAIC(:,17)./CONSTANTS(:,27);
    ALGEBRAIC(:,1) = STATES(:,1)+CONSTANTS(:,1);
    ALGEBRAIC(:,20) =  CONSTANTS(:,15).*CONSTANTS(:,16).*log( CONSTANTS(:,10).*ALGEBRAIC(:,1));
    ALGEBRAIC(:,5) = STATES(:,2)+CONSTANTS(:,2);
    ALGEBRAIC(:,22) =  CONSTANTS(:,15).*CONSTANTS(:,16).*log( CONSTANTS(:,11).*ALGEBRAIC(:,5));
    ALGEBRAIC(:,15) = STATES(:,5)+CONSTANTS(:,5);
    ALGEBRAIC(:,28) =  CONSTANTS(:,15).*CONSTANTS(:,16).*log( CONSTANTS(:,14).*ALGEBRAIC(:,15));
    ALGEBRAIC(:,29) =  CONSTANTS(:,6).*(exp((ALGEBRAIC(:,20)+ CONSTANTS(:,17).*ALGEBRAIC(:,28))./( CONSTANTS(:,15).*CONSTANTS(:,16))) - exp((ALGEBRAIC(:,22)+ CONSTANTS(:,17).*ALGEBRAIC(:,28))./( CONSTANTS(:,15).*CONSTANTS(:,16))));
    ALGEBRAIC(:,9) = STATES(:,3)+CONSTANTS(:,3);
    ALGEBRAIC(:,24) =  CONSTANTS(:,15).*CONSTANTS(:,16).*log( CONSTANTS(:,12).*ALGEBRAIC(:,9));
    ALGEBRAIC(:,30) =  CONSTANTS(:,7).*(exp(ALGEBRAIC(:,22)./( CONSTANTS(:,15).*CONSTANTS(:,16))) - exp(ALGEBRAIC(:,24)./( CONSTANTS(:,15).*CONSTANTS(:,16))));
    ALGEBRAIC(:,13) = STATES(:,4)+CONSTANTS(:,4);
    ALGEBRAIC(:,26) =  CONSTANTS(:,15).*CONSTANTS(:,16).*log( CONSTANTS(:,13).*ALGEBRAIC(:,13));
    ALGEBRAIC(:,31) =  CONSTANTS(:,8).*(exp(ALGEBRAIC(:,24)./( CONSTANTS(:,15).*CONSTANTS(:,16))) - exp(ALGEBRAIC(:,26)./( CONSTANTS(:,15).*CONSTANTS(:,16))));
    ALGEBRAIC(:,32) =  CONSTANTS(:,9).*(exp(ALGEBRAIC(:,26)./( CONSTANTS(:,15).*CONSTANTS(:,16))) - exp(ALGEBRAIC(:,22)./( CONSTANTS(:,15).*CONSTANTS(:,16))));
    ALGEBRAIC(:,4) =  (CONSTANTS(:,28)./( CONSTANTS(:,18).*CONSTANTS(:,19).*CONSTANTS(:,20))).*STATES(:,4).*(STATES(:,8)+CONSTANTS(:,18));
    ALGEBRAIC(:,8) =  (CONSTANTS(:,28)./( CONSTANTS(:,18).*CONSTANTS(:,19).*CONSTANTS(:,20))).*STATES(:,3).*STATES(:,7);
    ALGEBRAIC(:,12) = ALGEBRAIC(:,4)+ALGEBRAIC(:,8);
    ALGEBRAIC(:,14) = ALGEBRAIC(:,12);
    ALGEBRAIC(:,23) =  (( CONSTANTS(:,32).*ALGEBRAIC(:,16))./CONSTANTS(:,18)).*ALGEBRAIC(:,21);
    ALGEBRAIC(:,25) = ALGEBRAIC(:,23);
    ALGEBRAIC(:,27) = ALGEBRAIC(:,14)+ALGEBRAIC(:,25);
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) ~= 4), initialGuess_0 = [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(:,16) = soln(1);
        ALGEBRAIC(:,17) = soln(2);
        ALGEBRAIC(:,18) = soln(3);
        ALGEBRAIC(:,19) = soln(4);
    else
        SET_ALGEBRAIC(:,16) = logical(1);
        SET_ALGEBRAIC(:,17) = logical(1);
        SET_ALGEBRAIC(:,18) = logical(1);
        SET_ALGEBRAIC(:,19) = 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(:,16) = soln(1);
            TEMP_ALGEBRAIC(:,17) = soln(2);
            TEMP_ALGEBRAIC(:,18) = soln(3);
            TEMP_ALGEBRAIC(:,19) = soln(4);
            ALGEBRAIC(i,SET_ALGEBRAIC) = TEMP_ALGEBRAIC(SET_ALGEBRAIC);
        end
    end
end

function resid = residualSN_0(algebraicCandidate, ALGEBRAIC, VOI, CONSTANTS, STATES)
    ALGEBRAIC(:,16) = algebraicCandidate(1);
    ALGEBRAIC(:,17) = algebraicCandidate(2);
    ALGEBRAIC(:,18) = algebraicCandidate(3);
    ALGEBRAIC(:,19) = algebraicCandidate(4);
    resid(1) = ALGEBRAIC(:,16) - piecewise({ALGEBRAIC(:,17)>0.000000, CONSTANTS(:,29) }, CONSTANTS(:,30));
    resid(2) = ALGEBRAIC(:,18) -  (CONSTANTS(:,31)./ALGEBRAIC(:,16)).*STATES(:,9).*CONSTANTS(:,27);
    resid(3) = ALGEBRAIC(:,19) -  (CONSTANTS(:,31)./ALGEBRAIC(:,16)).*(STATES(:,6) - CONSTANTS(:,18)).*CONSTANTS(:,27);
    resid(4) = ALGEBRAIC(:,17) - ( - ALGEBRAIC(:,18)+ALGEBRAIC(:,19));
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

