%function [dico, yord] = GAD(y, ntime, length, overlap_P)
function [dico] = GAD(y, ntime, length)
% This function finds an orthogonal dictionary using a greedy adaptive  
% algorithm.
% Inputs: 
% y         -   matrix of frames taken from observed signal(s). When performing
%               source separation, this contains interleaved signal samples.
% ntime     -   size of dictionary.
% length    -   length of the data frame.
% overlap_P -   size of overlap between frames.
% 
% Outputs:
% dico      -  learned dictionary, with atoms in the columns of dico.
% yord      -  matrix of frames ordered according to how GAD extracts the frames.
%

residual = y;
dico = zeros(length,ntime);
%yord=zeros(512);

for k = 1 : ntime
    
    % Find frame with minimum sparsity index
    minFrame = sum(abs(residual))./sqrt(sum(abs(residual).^2));
    [a, i] = min(minFrame);
    b(k)=a;
    %yord(:,k) = y(:,i);
    y(:,i)=[];
   
    % Normalise residual and subtract atom's contribution from residual
    % matrix
    dico(:,k)=residual(:,i)./sqrt(sum(residual(:,i)'*residual(:,i)));
    residual = residual - dico(:,k)*dico(:,k)'*residual;
    residual(:,i)=[];    
end
