function [Q,cnt] = quad8stp(FunFcn,a,b,tol,lev,w,x0,f0,Q0,trace)
%QUAD8STP Recursive function used by QUAD8.
%	[Q,cnt] = quad8stp(F,a,b,tol,lev,w,f,Q0) tries to approximate
%	the integral of f(x) from a to b to within a relative error of tol.  
%	F is a string containing the name of f.  The remaining arguments are 
%	generated by quad8 or by the recursion.  lev is the recursion level.
%	w is the weights in the 8 panel Newton Cotes formula.
%	x0 is a vector of 9 equally spaced abscissa is the interval.
%	f0 is a vector of the 9 function values at x.
%	Q0 is an approximate value of the integral.
%	See also QUAD8 and QUAD.

%	Cleve Moler, 5-08-88.
%	Copyright (c) 1984-93 by The MathWorks, Inc.

LEVMAX = 10;

% Evaluate function at midpoints of left and right half intervals.
x = zeros(1,17);
f = zeros(1,17);
x(1:2:17) = x0;
f(1:2:17) = f0;
x(2:2:16) = (x0(1:8) + x0(2:9))/2;
f(2:2:16) = feval(FunFcn,x(2:2:16));
if trace
    plot(x(2:2:16),f(2:2:16),'.');
    if any(imag(f))
        plot(x(2:2:16),imag(f(2:2:16)),'+');
    end
end
cnt = 8;

% Integrate over half intervals.
h = (b-a)/16;
Q1 = h*w*f(1:9).';
Q2 = h*w*f(9:17).';
Q = Q1 + Q2;

% Recursively refine approximations.
if abs(Q - Q0) > tol*abs(Q) & lev <= LEVMAX
   c = (a+b)/2;
   [Q1,cnt1] = quad8stp(FunFcn,a,c,tol/2,lev+1,w,x(1:9),f(1:9),Q1,trace);
   [Q2,cnt2] = quad8stp(FunFcn,c,b,tol/2,lev+1,w,x(9:17),f(9:17),Q2,trace);
   Q = Q1 + Q2;
   cnt = cnt + cnt1 + cnt2;
end
