%% leave-one-trial-out

%data: (ch*time*trial)
%excludeTrials: the trials index of input data i.e. template should not include these
%        trials

% output: correlation of each frequency

function [ out ] = myCCA4( data , excludeTrials, harmonics)

numTrials = (1:size(data,3));
newData = squeeze(mean(data(:,:,excludeTrials),3))';
template = squeeze(mean(data(:,:,numTrials(~ismember(numTrials,numTrials(excludeTrials)))),3))';
if(isempty(numTrials(~ismember(numTrials,numTrials(excludeTrials)))))
    template = newData;
end
[c, wx, wy] = myCCA2__(template,5,8:0.2:11.8,harmonics);
freq = (8:0.2:11.8);
for i=1:20
    pNewData{i} = newData*wx{i};
    pTemplateData{i} = template*wx{i};
    %[A,B,r,U,V]  = canoncorr(pNewData{i}(:,1),pTemplateData{i}(:,1));
    [A,B,r,U,V]  = canoncorr(pNewData{i},pTemplateData{i});
    %r = corr2(pNewData{i}(:,1),pTemplateData{i}(:,1));
    
    out(i) = r(1);
end
end

function [corrVector, Wx, Wy] = myCCA2__(input, resolution, frequency, harmonics)
%column major
template = zeros(size(input,1),harmonics*2);
time = size(input,1);
T = 1/time * resolution;                     % Sample time
L = size(input,1);                     % Length of signal
t = (0:L-1)*T;                % Time vector
index=1;
corrVector = zeros(1,length(frequency));

for f = 1:length(frequency)
    for harm=1:(harmonics)
        template(:,index) = sin(2*harm*pi*frequency(f)*t);
        template(:,index+1) = cos(2*harm*pi*frequency(f)*t);
        index= index+2;
    end
    [A,B,r,U,V] = canoncorr(input,template);
    corrVector(f) = r(1);
    Wx{f} = A;
    Wy{f} = B;
    index=1;
    template=[];
end
end

