function showconv
% showconv Illustration of simple smoothing as convolution operation
% showconv: Version 21.11.2011
%
%   Description
%       Illustrates how a simple sinusoidal movement (blue line; intended to
%       represent something like a very simple lip movemement) that has been
%       corrupted by noise (noisy signal = green line/dots) can be smoothed
%       by moving a 5-point window over the signal.
%       The output of each window is computed as the average of the points
%       within the window. The window is moved sample by sample from left
%       to right over the signal, and the new smoothed signal is displayed
%       in red.
%       This moving average operation can be thought of as a primitive
%       filter where all 5 coefficients are equal to 0.2 (= 1/5).
%       The effect of this filter in the frequency domain is shown in a new
%       figure when the complete new signal has been generated.
%       Not surprisingly, the higher frequencies are suppressed, especially
%       above sample_frequency / 5 (i.e 200/5 in this case)

fs=200;
tv=((1:(fs*2))/fs)';

sampinc=1/fs;

truedata=sin(2*pi*1.5*tv);

noiseamp=0.1;
nd=length(tv);

noise=randn(nd,1)*noiseamp;

noisedata=truedata+noise;

filtdata=ones(nd,1)*NaN;

hld=plot([tv tv tv],[truedata noisedata filtdata],'linewidth',2);
hlw1=line([0;0],[min(noisedata);max(noisedata)],'linestyle','--');
hlw2=line([tv(end);tv(end)],[min(noisedata);max(noisedata)],'linestyle','--');

hlc=line(tv(1),noisedata(1),'linestyle','none','marker','x','color','m','linewidth',2,'markersize',14);

b=[0.2 0.2 0.2 0.2 0.2]';
nb=length(b);
nb2=floor(nb/2);

ncontext=3;
tcontext=sampinc*ncontext;

set(gcf,'doublebuffer','on');

set(gca,'fontsize',14,'fontweight','bold');
xlabel('Time (s)');
ylabel('Signal amplitude');
disp('hit any key to continue');
pause;


dozoom=1;
if dozoom
set(hld(2),'linestyle','none','marker','o');
disp('hit any key to continue');
pause;
end;
for ipi=(nb2+1):(nd-nb2)
    tmpd=noisedata((ipi-nb2):(ipi+nb2));
    
    ic1=ipi-nb2-ncontext;
    if ic1<1 ic1=1; end;
    ic2=ipi+nb2+ncontext;
    if ic2>nd ic2=nd; end;
    tmpdc=noisedata(ic1:ic2);
    y=sum(tmpd.*b);
    filtdata(ipi)=y;
    tw1=tv(ipi-nb2)-sampinc/2;
    tw2=tv(ipi+nb2)+sampinc/2;
    
    set(hlw1,'xdata',[tw1;tw1]);
    set(hlw2,'xdata',[tw2;tw2]);
    
    set(hld(3),'ydata',filtdata);
    set(hlc,'xdata',tv(ipi),'ydata',y);
if dozoom
    xlim([tw1-tcontext tw2+tcontext]);
    ylim([min(tmpdc) max(tmpdc)]);
end;

    drawnow;
    pause;
end;

xlim([0 tv(end)]);
ylim([min(noisedata) max(noisedata)]);

disp('hit any key to see frequency response');
pause

[h,f]=freqz(b,1,1024,200);
figure;
hfr=plot(f,abs(h),'linewidth',2);
set(gca,'fontsize',14,'fontweight','bold');
xlabel('Frequency (Hz)');
ylabel('Frequency Response');
grid on;
