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

nSubjects = numel(subjectdata);

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

disp(sprintf('we have %g subjects. Press ANY-Key to continue.\n Use Retrun if your Keyboard lacks the ANY-Key.',nSubjects));
pause


timeline = header.timeline;

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);
end

timeLineStart   = timeline.frameShiftStart;
timeLineEnd     = timeline.frameShiftEnd;

addpath 'libsvm-mat-2.88-1';

for timeIndex = 1:timeLineEnd-timeLineStart+1
    svm_train_label = [];
    svm_train_data  = [];
    svm_validation_label = [];
    svm_validation_data  = [];

    for validationSubjectID = 1:nSubjects
        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
        
        svmmodel = svmtrain(svm_train_label,svm_train_data,svmopts);
        
        [plabel accuracy dvalue] = svmpredict(svm_validation_label,svm_validation_data,svmmodel,'');
        
        accuracy(1)

%         decode.(namehelper)         = calculateDecodePerformance(header,currentSubject,svmopts);
% 
%         display('... done');
%         display('restoring warnings');
%         warning(warning_state);
% 
%         decode.decodePerformance    = [decode.decodePerformance decode.(namehelper).decodePerformance];
%         decode.rawTimeCourse        = [decode.rawTimeCourse decode.(namehelper).rawTimeCourse];

%         assignin('base','decode',decode);

        %         if RANDOMIZE_DATAPOINTS
        %         rndindex  = randperm(length(svmlabel));
        %         svmdata   = svmdata(rndindex,:);
        %         svmlabel  = svmlabel(rndindex);
        %         end

    end
end
end