%
%  fit a wavenet to a vector of data
%
%   [ y, cc ] = fitwavnt( x, w, l, pflag )
%
%  y     = fitted data (2^l+1 points)
%  cc    = wavenet coefficients (2^l+1, l+2)
%  x     = original data (2^l+1 points)
%  w     = wavelet type (see function wavefunc)
%  l     = resolution
%  pflag = plots progress by level if nonzero
%
function [ y, cc ] = fitwavnt( x, w, l, pflag )
%
x = x(:);
cc = [];
%
% fit scaling function nodes
[ y, c ] = levelfit( x, w, l, l );
cc = [ cc [ c; zeros( 2^l+1-length(c) ,1 ) ] ];
if pflag,
  v = (x-y)' * (x-y);
  sd = sqrt( v / ( 2^l + 1 ) );
  disp( [ 'Scaling function' ...
        ' standard deviation = ' num2str(sd) ] );
  t = [0:2^l]';
  plot( t, x, 'o', t, y, '-' );
  title( 'SCALING FUNCTION NODES' );
  pause
end;
%
% fit wavelet detail nodes
for m = l:-1:0,
  [ dy, c ] = levelfit( x-y, w, l, m );
  cc = [ cc [ c; zeros( 2^l+1-length(c) ,1 ) ] ];
  y = y + dy;
  if pflag,
    v = (x-y)' * (x-y);
    sd = sqrt( v / ( 2^6 + 1 ) );
    disp( [ 'Level ' num2str(m) ...
        ' standard deviation = ' num2str(sd) ] );
    plot( t, x, 'o', t, y, '-' );
    title( [ 'LEVEL ' num2str(m) ' APPROXIMATION' ] );
    pause
  end;
end;
%