%% leave-one-trial-out

%data(normal): (ch*time*trial)
%excludeTrials: template should not include these trials
%data2(sick): (ch*time*trial)
%excludeTrials2: template should not include these trials

% output: out-> PSD of data,
%         out2-> PSD of data2

function [ out,outPower ,out2, out2Power] = myCCA4_twoDataSet_predict( data ,index1, excludeTrials, data2, index2, excludeTrials2, harmonics, freq, resolution)
if(isempty(index1))
    numTrials = (1:min(size(data2,3),size(data,3)));
else
    numTrials = index1;
end
newData = squeeze(mean(data(:,:,excludeTrials),3))';
template = squeeze(mean(data(:,:,setdiff(numTrials,excludeTrials)),3))';

if(isempty(index2))
    numTrials2 = (1:min(size(data2,3),size(data,3)));
else
    numTrials2 = index2;
end
newData2 = squeeze(mean(data2(:,:,excludeTrials2),3))';
template2 = squeeze(mean(data2(:,:,setdiff(numTrials2,excludeTrials2)),3))';

% Note: if running out of trials for template, just randomly pick one
if(isempty(setdiff(numTrials2,excludeTrials2)) || isempty(setdiff(numTrials,excludeTrials)) )
    excludeTrials = index1(1);
    excludeTrials2 = index2(1);
    newData = squeeze(mean(data(:,:,excludeTrials),3))';
    template = squeeze(mean(data(:,:,setdiff(numTrials,excludeTrials)),3))';
    newData2 = squeeze(mean(data2(:,:,excludeTrials2),3))';
    template2 = squeeze(mean(data2(:,:,setdiff(numTrials2,excludeTrials2)),3))';
end
[c, wx, wy] = myCCA2__(template,resolution,freq,harmonics);
[c2, wx2, wy2] = myCCA2__(template2,resolution,freq,harmonics);
%freq = (8:0.2:11.8);
debug = zeros(length(freq),harmonics*2,2);
for i=1:length(freq)
    pNewData{i} = newData*wx{i};
    pTemplateData{i} = template*wx{i};
    %fft
    powerPnewdata = abs(fft(pNewData{i}(:,1:size(pNewData{i},2)))/size(data2,2));
    newR = powerPnewdata(round(freq(i)*resolution+1),:);
    outPower(i) = (newR(1));
    %cca
    %for rr = 1:size(pNewData{i},2)
    [A,B,r,U,V]  = canoncorr(pNewData{i}(:,1),pTemplateData{i}(:,1));
    %     [A,B,r,U,V]  = canoncorr(pNewData{i},pTemplateData{i});
    out(i) = r(1);
    %end
    %
    %debug(i,:,1) = newR;
    
    pNewData2{i} = newData2*wx2{i};
    pTemplateData2{i} = template2*wx2{i};
    %fft
    powerPnewdata2 = abs(fft(pNewData2{i}(:,1:size(pNewData2{i},2)))/size(data,2));
    newR2 = powerPnewdata2(round(freq(i)*resolution+1),:);
    out2Power(i) = (newR2(1));
    %cca
    %     for rr = 1:size(pNewData2{i},2)
    [A,B,r,U,V]  = canoncorr(pNewData2{i}(:,1),pTemplateData2{i}(:,1));
    %     [A,B,r,U,V]  = canoncorr(pNewData2{i},pTemplateData2{i});
    out2(i) = r(1);
    %         newR2(rr) = r(1);
    %     end
    %debug(i,:,2) = newR2;
    
end
end
%figure;plot(freq,out,'b',freq,out2,'r');


