%  Purpose: Take home exam EE289
%  Inputs:  noisy sequence yn
%           Fs sampling frequency
%           n length of sequence
%  Outputs: filtered sequence
%  Written by: HE
%  Date: Feb. 2012

clear all;
close all;
ans=input('Generate noisy squence: 1-yes,2-no ');

if(ans==1)
  % If Yes then generate noisy sequence
  
  % Load Handel and play it
  load handel;
  %sound(y,Fs);
  
  % n is the length of sequence
  n=length(y);
  for i=1:n
      
      % Generate normal random number
      rnd(i)=randn;
      
      % If magnitude of random number > threshold
      % add an impulse to the data otherwise just
      % copy the sample
      if(abs(rnd(i)) > 2)
          yn(i)=y(i)+rnd(i);
      else
          yn(i)=y(i);
      end
  end
  
  %  Save noisy file, sampling frequency and length
  save('Noisyfile.mat','yn','Fs','n'); 

else
    
  %  Do not generate file, load it  
  load Noisyfile.mat;
  
end
  
% Plot noisy sequence
figure;
plot(yn);
title('Noisy sequence');
xlabel('Sequence #');
ylabel('Magnitude');

% Play noisy file
%sound(yc,Fs);

% Initialize filtered sequences for
% median and mean filters
yemed=yn*0.0;
yemea=yn*0.0;

% Run for ever
while(1)
    
  % Input 1/2 filter length
  % if negative then exit the while loop
  N=input('Input positive 1/2 filter length ');
  if(N<0)
      break;
  end
  
  % Generate filtered sequences using mean
  % and median filters
  yemed=Filter_median(yn,n,N);
  yemea=Filter_mean(yn,n,N);
    
  % Play filtered sequences
  sound(yemed,Fs);
  sound(yemea,Fs);
  
  % Plot filtered sequence using the meadian filter
  figure;
  Ns=int2str(N);
  subplot(211);
  plot(yemed);
  title(['Filtered sequence (median filter N=',Ns,')']);
  xlabel('Sequence #');
  ylabel('Magnitude');
  
  % Plot filtered sequence using the mean filter
  subplot(212);
  plot(yemea);
  title(['Filtered sequence (mean filter N=',Ns,')']);
  xlabel('Sequence #');
  ylabel('Magnitude');

end