function [bestc,bestg] = GetcgCrossvalidate(trainsample,trainlabels,Nsets,crossvalindd,cgtable)
% Get parameters c and g of SVM classifier by using N-folds crossvalidate
% function [bestc,bestg] = GetcgCrossvalidate(trainsample,trainlabels,Nsets,cgtable)
% input:
%   trainsample,trainlabels: corrsponding training samples and labels;
%   Nsets:      using 1/Nsets of training samples as validing samples and others as training samples
%   crossvalindd: crossvalidate group indices,produced by crossvalind;
%   cgtable:    c and g lists

if ~exist('Nsets','var')
    Nsets = 2;
end
if ~exist('crossvalindd','var')
    crossvalindd = crossvalind('Kfold',size(trainsample,1),Nsets);
end
for j=1:Nsets
    indValid{j} = find(crossvalindd==j);
    indTrain{j} = find(crossvalindd~=j);
end
if ~exist('cgtable','var')
    cgtable.c1 = [10^2,10^3,10^4,10^5];
    cgtable.g1 = [ 0.1,   1,  10, 100];
end
acc=zeros(length(cgtable.c1),length(cgtable.g1));
for k1 = 1:length(cgtable.c1)
    for k2 = 1:length(cgtable.g1)
        cmd = ['-c ',num2str(cgtable.c1(k1)),' -g ',num2str(cgtable.g1(k2)),' -b 1 -q'];
        for j = 1:Nsets
            model = svmtrain(trainlabels(indTrain{j}),trainsample(indTrain{j},:),cmd);
            [~,accu,~] = svmpredict(trainlabels(indValid{j}),trainsample(indValid{j},:),model,'-b 1');
            acc(k1,k2)=acc(k1,k2)+accu(1);
        end
    end
end
[k1,k2]=find(acc==max(acc(:)));
bestc=cgtable.c1(k1);
bestg=cgtable.g1(k2);
bestc=bestc(1);
bestg=bestg(1);
