%% project the input and template on another space that maximizies the correlation
%input: data (time*ch)
%frequency: data fundamental frequency (in vector)
%harmonics: number of harmonics
%output: myU (component*time*frequency); 
function [corrVector, powerVector, myU] = my_FFT_or_CCA(input, resolution, frequency, harmonics,algorithm)
%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));
powerVector = zeros(1,length(frequency));
myU = [];
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
    
    if(algorithm == 'CCA')
        [A,B,r,U,V] = canoncorr(input,template);
        tempPower = (abs(fft(U)/size(input,1)));
        corrVector(f) = r(1);
        powerVector(f) = (tempPower(round(resolution*frequency(f)+1),1));
        myU(:,:,f) = U';
    elseif(algorithm == 'FFT')
        %mean first and then calculate the power
        tempPower = (abs(fft(mean(input,2))/size(input,1)));
        powerVector(f) = (tempPower(round(resolution*frequency(f)+1),1));
%         %fft first and then mean the power
%         tempPower = 10*log(abs(fft(input)));
%         powerVector(f) = mean(tempPower(round(resolution*frequency(f)+1),:),2);
    end
    
    
    index=1;
    template=[];
end
end