%% subject loop
function decode = som_combined_subject_batch(header,subjectdata,somOpts)

addpath 'somtoolbox2';

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

RANDOMIZE_DATAPOINTS = 1;

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
        svm_train_label = [];
        svm_train_data  = [];
        svm_validation_label = [];
        svm_validation_data  = [];
        for subjectDataID = 1:nSubjects
            svmstruct = calculateSVMTables(timePointMatrix{subjectDataID},timeIndex);
            svm_validation_label = svmstruct.svmlabel;
            svm_validation_data  = svmstruct.svmdata;
            svm_train_label = [svm_train_label; svmstruct.svmlabel];
            svm_train_data  = [svm_train_data;  svmstruct.svmdata];
        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

        [sD sM] = train_som(svmlabel, svmdata, somOpts)
        
%         [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