% Modified version of the MATLAB template file SolvIVDifD.m used to solve
% Example 2 of Supplemental Unit S5 of "A First Course on Kinetics and
% Reaction Engineering."
%
function [t_f,z] = S5_Example_2
    % Known quantities and constants (in consistent units)
    A = 0.1597;

    % Define the internal functions that will be needed
    
	% Function that evaluates the ODEs
    function dzdt = odeqns(t,z)
        dzdt = [
            -A*z(1)/(z(1) + z(2))
            0.5*A*z(1)/(z(1) + z(2))
        ];
    end % of internal function odeqns
        
    % Initial values
    t0 = 0.0;
    z0 = [
        0.103
        0.0
    ];

    tf = 1000.0;
    options = odeset('Events',@stop);
	[t, zz, te, ze, ie] = ode45(@odeqns,[t0, tf],z0,options);
    
    % Function that provides the integration stopping criterion
    function [stop_when, isterminal, direction] = stop(t,z)
        isterminal = 1;
        direction = 0;
        
        % The variable stop_when should equal zero when the desired
        % stopping criterion is reached
        stop_when = z(1)-z0(1)/2.0;
    end % of internal function stop


    % Return the values of the independent and dependent variables when the
    % integration stopping condition was satisfied
	last_value = length(t);
	t_f = t(last_value);
	z = zz(last_value,:);
	
    % calculate the ratio of z2 to z1
    ratio = z(2)/z(1)
    halfz0 = z0(1)/2.0
    double = 2*halfz0
    
end % of S5_Example_2.m
