%implements the entire GSC
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
signal = y;

global mud,global Nd,global mun,global Nn,global calibrated,global adapt

%initialize some blank vectors to store the results
output_delay = [];error_delay = [];output = []; error = [];test = 0;

%run a calibration for the delay line if required
if (calibrated ~= 1)
    display('Starting calibration of the delay filter')
    calibration;
end

%read in the data samples
tic
K = floor((length(signal(:,1))-2*Nd)/Nd);%number of read operations
for k = 0:1:K
    if (k == 0)
        x = [zeros(Nd,1);signal(1:Nd,2)];
        d = signal(1:Nd,1);
    else
        x = signal((k*Nd-Nd)+1:(k*Nd+Nd),2);
        d = signal((k*Nd+1):(k*Nd+Nd),1);
    end
    [out,err,Wd] = fdaf_lms(x,d,Wd,Nd,mud,0);
    output_delay = [output_delay,out'];
    error_delay = [error_delay,err'];
end
t = toc;
display('first stage finished, entering second stage'),display(t)

%perform additions/subtractions to obtain the noise and the desired (with
%noise) signal
desired = signal(1:length(output_delay),1)+output_delay';
noise = signal(1:length(output_delay),1)-output_delay';

%add a delay to the desired signal
desired = [zeros(Nd/2,1);desired];

%use the fdaf algorithm to obtain noise free speech
%construct first filtercoefficient vector
tic
%global Wn
Wn = [zeros(2*Nn,1)];
%Wn = Wn;
K = floor((length(noise(:,1))-2*Nn)/Nn);%number of read operations
for k = 0:1:K
    if (k == 0)
        x = [zeros(Nn,1);noise(1:Nn,1)];
        d = desired(1:Nn,1);
    else
        x = noise((k*Nn-Nn)+1:(k*Nn+Nn),1);
        d = desired((k*Nn+1):(k*Nn+Nn),1);
    end
    
    if (test == 1)
        out1 = IO_test(x,Nn);
        output = [output out1'];
    else
        [out1,err1,Wn] = fdaf_lms(x,d,Wn,Nn,mun,adapt((k+1)*Nn-Nn+1));
        %[out1,err1,Wn] = fdaf_lms(x,d,Wn,Nn,mun,0);
        output = [output,out1'];
        error = [error,err1'];
    end
end
t = toc;
display('calculations are finished'),display(t)
