% Simple script to demonstrate overlap-save algorithm
% Recoded 10/11/00 - Richard Stern

% DFT size 16
% P = 4

% Designing lowpass filter

% n = 4;
% f = [0 .2 .4 1];
% a = [1 1 0 0];
% b = remez(n,f,a);

b= [   0.1723    0.2726    0.2813    0.2726    0.1723];

load welcome16;
x = x16(101:228);
x = x(1:36);

y = conv(x,b);
n = 0:39;

subplot(3,1,1),stem(n,[x 0 0 0 0])
ylabel('x[n]','fontsize',14)
subplot(3,1,2),stem(n,[b zeros(1,35)])
ylabel('h[n]','fontsize',14)
subplot(3,1,3),stem(n,y)
xlabel('n','fontsize',14)
ylabel('y[n]','fontsize',14)

pause

% OLS demo using L = 16

% Show segmentation of x

Hk = fft(b,16);

subplot(4,1,1),stem(n,[x 0 0 0 0]);
ylabel('x[n]','fontsize',14)

subplot(4,1,2),stem([])
axis([0 40 -.01 .02])
subplot(4,1,3),stem([])
axis([0 40 -.01 .02])
subplot(4,1,4),stem([])
axis([0 40 -.01 .02])
xlabel('n','fontsize',14)

pause


x1 = x(1:16);
X1k = fft(x1,16);
Y1k = X1k.*Hk;
y1 = real(ifft(Y1k,16));

subplot(4,1,2),stem((0:15),x1);
axis([0 40 -.01 .02])
ylabel('x1[n]','fontsize',14)

pause

x2 = x(13:28);
X2k = fft([x2 0 0 0 0],16);
Y2k = X2k.*Hk;
y2 = real(ifft(Y2k,16));

subplot(4,1,3),stem((12:27),x2);
axis([0 40 -.01 .02])
ylabel('x2[n]','fontsize',14)

pause
x3 = [x(25:36) 0 0 0 0];
X3k = fft([x3 0 0 0 0],16);
Y3k = X3k.*Hk;
y3 = real(ifft(Y3k,16));

subplot(4,1,4),stem((24:39),x3);
axis([0 40 -.01 .02])
ylabel('x3[n]','fontsize',14)
xlabel('n','fontsize',14)

pause


% Now show segmentation of y

subplot(5,1,1),stem(n,y);
xlabel('n','fontsize',14)
ylabel('y[n]','fontsize',14)

subplot(5,1,2),stem([])
axis([0 40 -.01 .02])
subplot(5,1,3),stem([])
axis([0 40 -.01 .02])
subplot(5,1,4),stem([])
axis([0 40 -.01 .02])
subplot(5,1,5),stem([])
axis([0 40 -.01 .02])

pause

subplot(5,1,2),stem((4:15),y1(4:15));
hold on
subplot(5,1,2),stem((0:3),y1(1:4),'r');
axis([0 40 -.01 .02])
ylabel('y1[n]','fontsize',14)
axis([0 40 -.01 .02])

partial = [0 0 0 0 y1(4:15)];
subplot(5,1,5),stem((0:15),partial)
axis([0 40 -.01 .02])
ylabel('All','fontsize',14)
xlabel('n','fontsize',14)

pause

subplot(5,1,3),stem((12:27),y2);
hold on
subplot(5,1,3),stem((12:15),y2(1:4),'r')
axis([0 40 -.01 .02])
ylabel('y2[n]','fontsize',14)
axis([0 40 -.01 .02])

partial = [0 0 0 0 y1(5:16) y2(5:16)];
subplot(5,1,5),stem((0:27),partial)
axis([0 40 -.01 .02])
ylabel('All','fontsize',14)
xlabel('n','fontsize',14)

pause

subplot(5,1,4),stem((24:39),y3);
hold on
subplot(5,1,4),stem((24:27),y3(1:4),'r')
axis([0 40 -.01 .02])
ylabel('y3[n]','fontsize',14)
axis([0 40 -.01 .02])

partial = [0 0 0 0 y1(5:16) zeros(1,24)] + [zeros(1,16) y2(5:16) zeros(1,12)] + [zeros(1,28) y3(5:16)];
subplot(5,1,5),stem((0:39),partial);
axis([0 40 -.01 .02])
ylabel('All','fontsize',14)
xlabel('n','fontsize',14)

pause
