function L = Example_38_2a(given)
%Example_38_2a Solve AFCoKaRE Example 38.2 using an average effectiveness

    % Structure array given contains known quantities and constants

    % Average the effectiveness factors at the inlet and outlet
    CAin = given.CA0;
    [flux, eta_in] = Example_38_2_cat_bal(given,CAin);
    CAout = (1-given.fA)*CAin;
    [flux, eta_out] = Example_38_2_cat_bal(given,CAout);
    eta_avg = (eta_in + eta_out)/2.;
    %eta_avg = 1.0
    
    % Solve the PFR design equation using the average effectiveness factor
    
    % Initial values
    t0 = 0.0;
    z0 = [
        CAin*given.VFR
    ]; % solution, equation 2

    tf = 960.;
    %tf = 96.6;
    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;
        
        stop_when = z(1) - (1-given.fA)*CAin*given.VFR; % solution, equation 23
    end % of internal function stop

    % Extract the final values of the independent and dependent variables
	last_value = length(t);
	t_f = t(last_value); % final value of the independent variable
	z = zz(last_value,:); % final values of the dependent variables
    
    % Warn if the independent variable reached tf above
    if (t_f >= tf)
        display('WARNING: the final value of the independent variable was')
        display('    reached, instead of the final value of the dependent')
        display('    variable. Set tf to a larger value and re-execute');
        display('    the function')
    end % if (t_f >= tf)
	
    %conv_check = (CA0*VFR - z(1))/CA0/VFR
    L = t_f;

	% Function that evaluates the ODEs
    function dzdt = odeqns(t,z)
        rate = given.k*z(1)^2/given.VFR^2;
        if (z(1) < 0)
            rate = 0.0;
        end % if (z(1) < 0)
        dzdt = [
            -pi()*given.D^2/4*eta_avg*(1-given.eps)*rate;
        ]; % solution, equation 1
    end % of internal function odeqns

end % of Example_38_2a
