%% subject loop
function decode = xsvm_subject_loop(header,subjectdata,svmopts)

addpath(fullfile(getTbxPath,'libsvm-mat-2.88-1'));

nSubjects = numel(subjectdata);
if(nSubjects < 2) 
    error('SVMCrossVal:xsvmSubjectLoop:tooFewSubjects','You need at least 2 Subjects in this Across-Subject analysis!');
end

RANDOMIZE_DATAPOINTS = header.svmrnd;
NAN_AS_ZERO = header.nantozero;

decode = struct;
decode.decodePerformance = [];
decode.rawTimeCourse     = [];

disp(sprintf('computinig additional datastructs for %u subjects',nSubjects));

timeline = header.timeline;
timeline.frameShiftStart = header.frameShift.frameShiftStart;
timeline.frameShiftEnd   = header.frameShift.frameShiftEnd;
timeline.decodeDuration  = header.frameShift.decodeDuration;

% TimePointMatrix
for subjectDataID = 1:nSubjects
    currentSubject = subjectdata{subjectDataID};
    timePointArgs.pst           = currentSubject.pst;
    timePointArgs.labelMap      = LabelMap(header.classDef.labelCells,header.classDef.conditionCells);
    timePointArgs.eventList     = header.classDef.eventMatrix;

    timePointMatrix{subjectDataID} = buildTimePointMatrix(timeline,timePointArgs);
    
    decode.rawTimeCourse = [decode.rawTimeCourse currentSubject.pst];
end

% timeframe x-subject validation
timeLineStart   = timeline.frameShiftStart;
timeLineEnd     = timeline.frameShiftEnd;

display(sprintf('%u -fold cross validation for %u timeslices.\n',nSubjects,size(1:timeLineEnd-timeLineStart+1,2)));
% disp(sprintf('Press ANY-Key to continue.\n Use Retrun if your Keyboard lacks the ANY-Key.'));
% pause

for timeIndex = 1:timeLineEnd-timeLineStart+1
    cross_value = [];
    for validationSubjectID = 1:nSubjects
        svm_train_label = [];
        svm_train_data  = [];
        svm_validation_label = [];
        svm_validation_data  = [];
        for subjectDataID = 1:nSubjects
            svmstruct = calculateSVMTables(timePointMatrix{subjectDataID},timeIndex);
            if subjectDataID == validationSubjectID
                svm_validation_label = svmstruct.svmlabel;
                svm_validation_data  = svmstruct.svmdata;
            else
                svm_train_label = [svm_train_label; svmstruct.svmlabel];
                svm_train_data  = [svm_train_data;  svmstruct.svmdata];
            end
        end
        
        if RANDOMIZE_DATAPOINTS
            rndindex  = randperm(length(svm_train_label));
            svm_train_data   = svm_train_data(rndindex,:);
            svm_train_label  = svm_train_label(rndindex);
        end
        
        if NAN_AS_ZERO
            svm_train_data(isnan(svm_train_data))=0;
        end
        

        svmmodel = svmtrain(svm_train_label,svm_train_data,svmopts);
        
        [plabel accuracy dvalue] = svmpredict(svm_validation_label,svm_validation_data,svmmodel,'');
        cross_value = [cross_value accuracy(1)];
        
    end
    decode.decodePerformance = [decode.decodePerformance; cross_value];
    
end

disp('decode done');
end