function [correlation,maxRidgeParamIndex]=ridgeCV(savePath,data,goal,k,ridgeParams,eegOffset)
% ridgeCV runs a ridge regression to predict 'goal' from 'data'
    load(savePath);
    clear classification; %classification is not need
    eeg=false;
    if strcmp(data,'EEG')
        eeg=true;
        trainingData=trainingDataEEG(eegOffset+1:end,:);
    elseif strcmp(data,'EMG')
        trainingData=trainingDataEMG;
    elseif strcmp(data,'LF')
        eeg=true;
        trainingData=trainingDataEEGlf(eegOffset+1:end,:);
    elseif strcmp(data,'Autoenc')
        trainingData=synergiesAutoenc;
    elseif strcmp(data,'PCA')
        trainingData=synergiesPCA;
    elseif strcmp(data,'NNMF')
        trainingData=synergiesNNMF;
    else
        error('only EEG, EMG, LF, Autoenc, PCA and NNMF are valid inputs for data');
    end
    % if data is smaller then goal, goal is scaled down
    factor=size(trainingDataEMG,1)/(size(trainingData,1)+eegOffset);


    if strcmp(goal,'Autoenc')
        predicted=shiftingMean(synergiesAutoenc,factor);
    elseif strcmp(goal,'PCA')
        predicted=shiftingMean(synergiesPCA,factor);
    elseif strcmp(goal,'NNMF')
        predicted=shiftingMean(synergiesNNMF,factor);
    elseif strcmp(goal,'kin')
        predicted=shiftingMean(kinematics,factor);
    elseif strcmp(goal,'EMG')
        predicted=shiftingSum(trainingDataEMG,factor);
    else
        error('only kin, Autoenc, PCA, NNMF and EMG are valid inputs for goal');
    end

    clear trainingDataEEG;
    clear trainingDataEEGlf;
    clear trainingDataEMG;
    clear synergies*;
    clear kinematics;
    
    % is eeg Offset applied?
    if eeg
        predicted=predicted(1:end-eegOffset,:);
    end
    
    %disp([size(trainingData),size(predicted)])
    %adjust small errors when unsung down scaling
    minSize=min([size(trainingData,1),size(predicted,1)]);
    if minSize+5<max([size(trainingData,1),size(predicted,1)])
        error('data dimensions not matching');
    end
    while minSize<size(trainingData,1)
        trainingData=trainingData(2:end,:);
    end
    while minSize<size(predicted,1)
        predicted=predicted(2:end,:);
    end
    %disp([size(trainingData),size(predicted)])
    

    correlation=zeros(size(predicted,2),1);
    maxRidgeParamIndex=zeros(size(predicted,2),k);

    for j=1:size(predicted,2)
        randMap=randperm(size(trainingData,1));
        pred=predicted(:,j);
        correlations=zeros([k,1]);

        for i=1:k %k-fold CV
            leaveData=trainingData(mod(randMap,k)==i-1,:);
            leavePerd=pred(mod(randMap,k)==i-1);
            remainingData=trainingData(mod(randMap,k)~=i-1,:);
            remainingPred=pred(mod(randMap,k)~=i-1);

            [coeffs,maxRidgeParamIndex(j,i)]=kFoldRidge(remainingData,remainingPred,k,ridgeParams);

            correlations(i)=ridgeCorrelation(leaveData,leavePerd,coeffs);
        end

        correlation(j)=mean(correlations); % correlation is mean of all correlations
    end
end
