% usage: y = psi_it(c,d,nn,M)
% given filters c,d, find the scaling and wavelet function by iteration.
% M is the number of iterations
% nn is the number of points in between integers where psi is evaluated.

figure(1), clf

% generate filters
h = ortfilt('Daubechies',2);
[h, g, ht, gt, sh, sg, sht, sgt] = qmf2hgs(h);
c=h; d=g;
nn=20;M=100;

d = 2*d/sum(d.*(-1).^(0:length(d)-1));
c = 2*c/sum(c);
nc = length(c);
nd = length(d);
n = max(nc,nd);
N = nn*n;
x = (-N:2*N)*n/N;
y = zeros(size(x));
z = zeros(size(x));

% starting value 1:
  y(N/2:N+N/2) = ones(size(y(N/2:N+N/2)));
% starting value 2:
%  y(N+1+N/2) = 1;
%  y(N+1) = 1;
% starting value 3:
%  y(N+1:2*N+1) = ones(size(y(N+1:2*N+1)));
% starting value 4:
%  y(N+1:N+N/2) = x(N+1:N+N/2);
%  y(N+N/2+1:2*N+1) = n - x(N+N/2+1:2*N+1);
% starting value 5:
%  y(N+1) = 0;
%  y(N+1+nn) = c(1);
%  y(N+1+2*nn) = c(4);

y(1:N) = 0; y(2*N+1:end) = 0;

figure(1),plot(x,y),
title('Starting function'),
disp('... hit any key to continue'),pause
for j = 1:M
  y0 = y;

  for k = 0:N-1
    y(N+1+k) = sum(y0(N+1+2*k:-nn:N+1+2*k-nn*(nc-1)).*c); 
    z(N+1+k) = sum(y0(N+1+2*k:-nn:N+1+2*k-nn*(nd-1)).*d); 
  end

  subplot(2,1,1),  plot(x(N+1-nn:2*N+1+nn),y(N+1-nn:2*N+1+nn)),
  title(['phi, iteration # ',int2str(j)])
  subplot(2,1,2),  plot(x(N+1-nn:2*N+1+nn),z(N+1-nn:2*N+1+nn)),
  title(['psi, iteration # ',int2str(j)])
  pause(0.1)
end
