function [decision] = Decoder(TestResp, Env1, Env2, g, Lag, threshold, index)

% TestResp: EEG data
% Env1: envelope of speaker A
% Env2: envelope of speaker B
% g: the reconstruction filter, basically the weight that is given to each electrode to map it back to the envelope. 
% Lag: is the time window that is being used for the reconstruction
% threshold: correlation threshold used for making the decision on the attended speaker
% index: selection of the EEG measurement points used for the decoding process   

% Nima Mesgarani, nimail@gmail.com
% (Mesgarani et. al. J. Neurophysiology 2009)

% Edited by Ed Lalor.
TestResp = resample(TestResp,1,10);
Env1 = resample(Env1,1,10);
Env2 = resample(Env2,1,10);


TestResp = TestResp(:,index);
TestResp(isnan(TestResp))=0;
TestRespLag  = LagGeneratorNew(TestResp,Lag);
for cnt1 = 1:size(g,3)
    rstim(:,:,cnt1) = g(:,:,cnt1)'*TestRespLag';
end

if (size(rstim,1) == 1)
    rstim = rstim';
end

if (size(Env1,1) == 1)
    Env1 = Env1';
end

if (size(Env2,1) == 1)
    Env2 = Env2';
end

[r1,p1] = corr(rstim,Env1);
[r2,p2] = corr(rstim,Env2);

% **********************************************************
% Check significance and require some difference
% ********************************************************** 
disp([r1 r2]);
if (p1 < 0.05)&&(p2 < 0.05)
    if r1 - r2 > threshold
        decision = 1;
    elseif r2 - r1 > threshold
        decision = 2;
    else
        decision = 0;
    end
elseif (p1 < 0.05)
    decision = 1;
elseif (p2 < 0.05)
    decision = 2;
else
    decision = 0;
end