%
% Adaptive CSR
%
% This is the main "meat" of the recursive scheme,
% there should be no reason to edit this
% (except to get rid of excessive output -- both
% text and graphics...
%

function [val,err] = ACSR(f,a,b,tol,level,h)

h1 = (b-a)/2;  x1 = (a:h1:b);  w1 = [1 4 1];
h2 = h1/2;     x2 = (a:h2:b);  w2 = [1 4 2 4 1];

S1 = h1/3*sum(f(x1).*w1);
S2 = h2/3*sum(f(x2).*w2);

err = abs(S1-S2)/15;

if( err < tol )
  fprintf('CSR succeeded at level %d on interval [%f,%f]\n',...
	  level,a,b);
  val = S2;
  figure(h); hold on
  plot([a b],[level level],'o-','linewidth',3)
  hold off
else
  [lt, err_lt] = ACSR(f,a,(a+b)/2,tol/2,level+1,h);
  [rt, err_rt] = ACSR(f,(a+b)/2,b,tol/2,level+1,h);
  val = lt+rt;
  err = err_lt+err_rt;
end



