function downsample_example()

NFFT = 2^16;
freq = [0:NFFT-1]/NFFT;
freq = [freq-1,freq];
D = 2; % Downsample factor
L = 2e4;
n = [-L:L];
f0 = 0.05;
f1 = 0.245;

clf;

make_plot(f0,f1);

hui = uicontrol('style','slider','value',f0,'min',0,'max',0.5,...
                'position',[10 10 300 20],'callback',{@nestfunc});

huj = uicontrol('style','slider','value',f1,'min',0,'max',0.5,...
                'position',[400 10 300 20],'callback',{@nestfunc});


function make_plot(f0,f1)
fprintf('Sinc width = %f, cos freq = %f\n',f0,f1);
x = 2*f0*sinc(2*f0*n);
y1 = exp(1j*2*pi*f1*n)/(NFFT);
y2 = exp(-1j*2*pi*f1*n)/(NFFT);
xd = x(1:D:end);
y1d = y1(1:D:end);
y2d = y2(1:D:end);

X = fft(x,NFFT); X = [X,X];
Y1 = fft(y1,NFFT); Y1 = [Y1,Y1];
Y2 = fft(y2,NFFT); Y2 = [Y2,Y2];
Xd = fft(xd,NFFT); Xd = [Xd,Xd];
Y1d = fft(y1d,NFFT); Y1d = [Y1d,Y1d];
Y2d = fft(y2d,NFFT); Y2d = [Y2d,Y2d];

subplot(211);
plot(freq,abs(X),'Color',[0.8 0 0.3],'LineWidth',4); hold on;
plot(freq,abs(Y1),'Color',[0 0.3 0.8],'LineWidth',4); hold on;
plot(freq,abs(Y2),'Color',[0 0.8 0.3],'LineWidth',4); hold on;
ax = axis;
plot(0*[1 1],ax(3:4),':k'); hold on;
plot(0.5*[1 1],ax(3:4),':k'); hold on;
plot(-0.5*[1 1],ax(3:4),':k'); hold on;
plot(f0*[1 1],ax(3:4),'--k'); hold on;
plot(-f0*[1 1],ax(3:4),'--k'); hold on;
plot(((1/D)-f0)*[1 1],ax(3:4),'--k'); hold on;
plot(-((1/D)-f0)*[1 1],ax(3:4),'--k'); hold on;
plot(((1/D)+f0)*[1 1],ax(3:4),'--k'); hold on;
plot(-((1/D)+f0)*[1 1],ax(3:4),'--k'); hold off;
title('Before Decimation by 2');
xlabel('Normalized Frequency [cycles/sample]');
subplot(212);
plot(freq,abs(Xd),'Color',[0.8 0 0.3],'LineWidth',4); hold on;
plot(freq,abs(Y1d),'Color',[0 0.3 0.8],'LineWidth',4); hold on;
plot(freq,abs(Y2d),'Color',[0 0.8 0.3],'LineWidth',4); hold on;
ax = axis;
plot(0*[1 1],ax(3:4),':k'); hold on;
plot(0.5*[1 1],ax(3:4),':k'); hold on;
plot(-0.5*[1 1],ax(3:4),':k'); hold on;
plot(2*f0*[1 1],ax(3:4),'--k'); hold on;
plot(-2*f0*[1 1],ax(3:4),'--k'); hold off;
title('After Decimation by 2');
xlabel('Normalized Frequency [cycles/sample]');
end

function nestfunc(src,evd)
f0 = get(hui,'Value');
f1 = get(huj,'Value');
make_plot(f0,f1);
end

end