function [clean] = method1(corrupt, noise)
% Fighting Corrupt Speech: method1
% <cleaned-data> = method1( <corrupt-data>, <noise-data> )
%
% Attempts to clean up the corrupt voice data by subtracting
% the noise signal frequency magnitude in the Fourier domain
% and then recreates the phase information to regenerate the
% hopefully cleaner signal.
%
% This function takes the corrupt and noise signals, as read
% by the wavread function.  The function assumes 11.025 kHz 
% recording.  Example usage:
%
% >> corrupt = wavread('corrupt');
% >> noise = wavread('noise');
% >> data = method1(corrupt, noise);
% >> soundsc(data, 11025);
%

[N, trash]=size(noise);

% subtract the dc offset from the inputs
noise = losedcoff(noise);
corrupt = losedcoff(corrupt);

noiseFFT = fft(noise);
corruptFFT = fft(corrupt);

%plot(abs(noiseFFT))
%pause
%plot(abs(corruptFFT))
%pause

FS = 11025;
Ts = 1/FS;
DELTAF = 1 / ( N * Ts );
FREQ = 0:DELTAF:FS/2;
FREQ = FREQ';
plot(FREQ(1:N/2), abs(noiseFFT(1:N/2)));
title('Noise Data Magnitude Plot (Fourier Domain)');
pause;
plot(FREQ(1:N/2), abs(corruptFFT(1:N/2)));
title('Corrupt Speech Data Magnitude Plot (Fourier Domain)');
pause;

npc = abs(noiseFFT) .* abs(noiseFFT);
cpc = abs(corruptFFT) .* abs(corruptFFT);

cleansnd = cpc - npc;

for I=1:N,
    if cleansnd(I) < 0
        cleansnd(I) = 0;
    end
end

cleansnd = sqrt ( cleansnd );
phasevalues = angle(corruptFFT);
rebuilt = cleansnd .* cos(phasevalues) + i * cleansnd .* sin(phasevalues);

plot(FREQ(1:N/2), abs(rebuilt(1:N/2)));
title('Rebuilt Speech Data After method1 Processing');
pause;

clean = real( ifft(rebuilt) );
