function [model,maxC] = kfoldCV(classification,trainingData,k,cExpMax,maxDataPerClass)
    noClasses=size(unique(classification),1);
    cvAccurancy=zeros(2*cExpMax+1,1);
    parfor cExp=1:2*cExpMax+1
        c=2^(cExp-cExpMax-1);

        randomMapping=transpose(randperm(size(trainingData,1)));
        accurancy=zeros(k,3);

        for i=1:k
            trainData=trainingData(mod(randomMapping,k)+1~=i,:,:);
            testData=trainingData(mod(randomMapping,k)+1==i,:,:);
            trainClasses=classification(mod(randomMapping,k)+1~=i);
            testClasses=classification(mod(randomMapping,k)+1==i);
            %fprintf('i=%i, k=%i, c=%i\n',i,k,c)
            [trainClasses,trainData]=balanceClasses(trainClasses,trainData,maxDataPerClass,noClasses);
            model=svmtrain(trainClasses,trainData(:,:),sprintf('-t 0 -c %f -q',c));
            [~, accurancy(i,:), ~]=svmpredict(testClasses, testData(:,:), model,'-q');
        end

        cvAccurancy(cExp)=mean(accurancy(:,1));
    end
    [~,maxC]=max(cvAccurancy);
    bestC=2^(maxC-cExpMax-1);
    [balancedClasses, balanceData]=balanceClasses(classification,trainingData,maxDataPerClass,noClasses);
    model=svmtrain(balancedClasses, balanceData(:,:),sprintf('-t 0 -c %f -q',bestC));

end