%% denoise
%% show a noisy signal and shifted dft magnitude
%% smooth dft and then smooth signal

% define signal, sample rate, sample domain
N = 256;
t = (0:1:(N-1))/N;
eps  = .01;
truesig = 2*cos(5*2*pi*t)+0.5*sin(24*2*pi*t);
unitnoise = rand(size(truesig)) - 0.5*ones(size(truesig)); 
sig  = truesig+eps*unitnoise;

SD = 0:(N-1);

% get dft and frequency domain
fsig = fft(sig); 
FD = 0:(N-1);

% get shifted dft and frequency domain
fsig = fft(sig); 
sfsig = fftshift(fsig);
FD = fftshift(SD);
N1 = FD(1);
FD(1:(N-N1))=  (N1-N):(-1);


% display signal and transform 
figure(1)
subplot(2,1,1)
plot(SD,real(sig),'r',SD,imag(sig),'g')
title('sampled signal');
axis tight
subplot(2,1,2)
plot(FD, abs(sfsig),'r-' )
title('frequency stength')
axis tight

% smooth transform and signal
thresh =0.05;
m = max(abs(fsig)); 
ZI = find(abs(fsig) < thresh*m);
smfsig = fsig;
smfsig(ZI) = 0;
smsig = ifft(smfsig);
ssmfsig = fftshift(smfsig);

disp('press a key');
pause

% display smoothed functions 
figure(2)
subplot(2,1,1)
plot(FD, abs(ssmfsig),'r-' )
title('magnitude of smoothed DFT')
axis tight
subplot(2,1,2)
plot(SD, real(smsig),'g-' )
title('smoothed signal')
axis tight