function dum = wcintron(k)

% The example of the introduction
% elementary Haar wavelet analysis

% the signal has n = 2^k samples

if nargin == 0
  disp('please give an integer k > 3 as argument\n')
  disp('the signal contains 2^k samples\n')
  return
end

if ( k < 4 )
   disp('k should be at least 4\n')
   k = 4;
end

n = 2^k;
as = [0 n+1 -2*n 2*n];
%x0 = fix(n*(rand(n,1)-0.5));
%x0 = (n*(sin((1:n)'*2*pi/n))/2);
a = [2 10 6]; b = [3 7 1];
x0 = n/8 * (a * cos(b' * (1:n) * 2 * pi / n))';
figure(1), xst = (1 : n + 1) - 0.5;
subplot(4, 2, 1), stairs(xst, exex(x0)), axis(as)
hold on, plot(xst, zeros(size(xst)), 'r'), hold off
title(['the originl signal: ' int2str(n) '  samples'])

% first transform step

H1 = eye(n) + diag(ones(n - 1, 1), 1);
H1 = H1(1 : 2 : n, : ) / sqrt(2);
G1 = eye(n) - diag(ones(n - 1, 1), 1);
G1 = G1(1 : 2 : n, : ) / sqrt(2);
X1 = H1 * x0; x1 = H1' * X1; Y1 = G1 * x0; y1 = G1' * Y1;
subplot(4, 2, 3); stairs(xst, exex(x1)), axis(as)
hold on, plot(xst, zeros(size(xst)), 'r')
plot(1.5 : 2 : n - 0.4, X1, 'r.'), hold off
subplot(4, 2, 4); stairs(xst, exex(y1)), axis(as)
hold on, plot(xst, zeros(size(xst)), 'r')
plot(1.5 : 2 : n - 0.4, Y1, 'r.'), hold off


H2 = H1(1 : n / 4, 1 : n / 2);
G2 = G1(1 : n / 4, 1 : n / 2);
X2 = H2 * X1; Y2 = G2 * X1;
x2 = H1' * H2' * X2; y2 = H1' * G2' * Y2;
subplot(4, 2, 5); stairs(xst, exex(x2)), axis(as)
hold on, plot(xst, zeros(size(xst)), 'r'),
plot(2.5 : 4 : n - 1.5, X2, 'r.'), hold off
subplot(4, 2, 6); stairs(xst, exex(y2)), axis(as)
hold on, plot(xst, zeros(size(xst)), 'r')
plot(2.5 : 4 : n - 1.5, Y2, 'r.'), hold off

% third transform step

H3 = H2(1 : n / 8, 1 : n / 4);
G3 = G2(1 : n / 8, 1 : n / 4);
X3 = H3 * X2; Y3 = G3 * X2;
x3 = H1' * H2' * H3' * X3; y3 = H1' * H2' * G3' * Y3;
subplot(4, 2, 7); stairs(xst, exex(x3)), axis(as)
hold on, plot(xst, zeros(size(xst)), 'r')
plot(4.5 : 8 : n - 5 / 2, X3, 'r.'), hold off
subplot(4, 2, 8); stairs(xst, exex(y3)), axis(as)
hold on, plot(xst, zeros(size(xst)), 'r')
plot(4.5 : 8 : n - 5 / 2, Y3, 'r.'), hold off

% the wavelet transform 

HH0 = H3 * H2 * H1; XP = [Y3' Y2' Y1'];
X = x0;
for j = 4 : k
mj = 2^j; mj1 = mj / 2;

H = H1(1 : n / mj, 1 : n / mj1); HH = H * HH0;
G = G1(1 : n / mj, 1 : n / mj1); HG = G * HH0; HH0 = HH;
XX = HH * X; YY = HG * X; xx = HH' * XX; yy = HG' * YY;
XP = [YY' XP];
end
XP = [XX' XP];

subplot(4, 2, 2), plot(1 : n, XP, 'r.'), axis(as)
hold on, plot(0.5 : n + 0.5, zeros(1, n + 1), 'r'), vert = [-n; n];
np = n;
for j = 1 : k
    np = np / 2;
    plot([np + 0.5 np + 0.5], vert, 'b-');
end
hold off;

function xex = exex(x)
l = length(x);
xex(1 : l, : ) = x;
xex(l + 1, : ) = x(l, :);
