function plotDecodePerformance(type,decode,subjectData)

header = decode.header;
timeline = header.timeline;
frameshift = header.frameShift;

psthStart         = timeline.psthStart;
psthEnd           = timeline.psthEnd;
frameStart        = frameshift.frameShiftStart;
frameEnd          = frameshift.frameShiftEnd;

nClasses          = numel(header.classDef.labelCells);
decodePerformance = decode.decodePerformance;
psth              = decode.rawTimeCourse;
ert               = psth; % Rename to EventRelatedTimeline
SubjectID         = subjectData;

nSubjects         = size(SubjectID,2);

nTrials           = getNTrials(psth);

    f = figure;
  
    hold on;
    chanceLevel = 100/nClasses;

    axis([psthStart psthEnd 0 100])
    xlabel('time [sec]');
    ylabel('decode performance [%]');
    
    
plottime= tic;
    switch type
        case 'psth'
            plotPSTH(ert,psthStart,psthEnd);  
            
        case 'trajectory'
            plotTrajectory(ert,psthStart,psthEnd);

        case 'trajectory3'
            plotTrajectory3(ert);

        case 'simple'
            plotDecodePerformanceWithSE(frameStart,frameEnd,decodePerformance)

            plot([psthStart psthEnd],[chanceLevel chanceLevel],'k:');
            plotBinConfidenceIntervall(psthStart,psthEnd,nTrials,0.05,chanceLevel/100,'--');
            plotBinConfidenceIntervall(psthStart,psthEnd,nTrials,0.01,chanceLevel/100,'-.');
            plotBinConfidenceIntervall(psthStart,psthEnd,nTrials,0.001,chanceLevel/100,':');

        case 'class performance'
            plotClassPerformance(frameStart,frameEnd,decodePerformance,nClasses)

            plot([psthStart psthEnd],[chanceLevel chanceLevel],'k:');
            plotBinConfidenceIntervall(psthStart,psthEnd,nTrials,0.05,chanceLevel/100,'--');
            plotBinConfidenceIntervall(psthStart,psthEnd,nTrials,0.01,chanceLevel/100,'-.');
            plotBinConfidenceIntervall(psthStart,psthEnd,nTrials,0.001,chanceLevel/100,':');
        case 'x-subject-val'
            for c = 1:nSubjects
                plot(frameStart:frameEnd, decodePerformance(:,c) ,[colorChooser(mod(c,nSubjects)+3) '-']);
            end
            plotDecodePerformanceWithSE(frameStart,frameEnd,decodePerformance)
            
            plot([psthStart psthEnd],[chanceLevel chanceLevel],'k:');
            plotBinConfidenceIntervall(psthStart,psthEnd,nTrials,0.05,chanceLevel/100,'--');
            plotBinConfidenceIntervall(psthStart,psthEnd,nTrials,0.01,chanceLevel/100,'-.');
            plotBinConfidenceIntervall(psthStart,psthEnd,nTrials,0.001,chanceLevel/100,':');

    end
toc(plottime);    
    hold off;
    
end

function plotBinConfidenceIntervall(pStart,pEnd,nTrials,alpha,limit,color)
    [pLevel Z] = rev_ki_bin(nTrials,alpha,limit);
    [lower upper proz] = ki_bin(Z,nTrials,alpha);

    plot([pStart pEnd],[pLevel*100 pLevel*100],[color 'k']);
%     plot([pStart pEnd],[lower*100 lower*100],[color 'k']);
%     plot([pStart pEnd],[upper*100 upper*100],[color 'k']);
end

function n = getNTrials(psth)
nOverallConditions = size(psth,2);

n = 0;
for ns = 1:nOverallConditions
    nClasses = size(psth{ns},2);
    for nc = 1:nClasses
        n = n + size(psth{ns}{nc},1);
    end
end
n=n/(nOverallConditions/nClasses);

end

function plotClassPerformance(frameStart,frameEnd,decodePerformance,nClasses)
for c = 1:size(decodePerformance,2)
    plot(frameStart:frameEnd, decodePerformance(:,c) ,[colorChooser(mod(c,nClasses)+3) '-']);
end
plot(frameStart:frameEnd, mean(decodePerformance,2) ,'b','LineWidth',2);
end

function plotDecodePerformanceWithSE(frameStart,frameEnd,decodePerformance)
plot(frameStart:frameEnd, mean(decodePerformance,2) ,'b','LineWidth',2);

se = myStdErr(decodePerformance,2);
plot(frameStart:frameEnd, mean(decodePerformance,2)+se ,'b:');
plot(frameStart:frameEnd, mean(decodePerformance,2)-se ,'b:');
end


function plotPSTH(psth,psthStart,psthEnd)

PSTH_AXIS_MIN = -2;
PSTH_AXIS_MAX = 2;

    hold on;
    if (size(psth) > 0)
      for voxel = 1:size(psth,2)
          for label = 1:size(psth{voxel},2)
              psthData = [];
              for timepoint = 1:size(psth{voxel}{label},2)
                  psthData = nanmean(psth{voxel}{label});
              end
              PSTH_AXIS_MAX = max(PSTH_AXIS_MAX,nanmax(psthData));
              PSTH_AXIS_MIN = min(PSTH_AXIS_MIN,nanmin(psthData));
              plot(psthStart:psthEnd,psthData,[colorChooser(voxel), lineStyleChooser(label)]);
%               plot(psthStart:psthEnd,psthData,[lineStyleChooser(voxel), colorChooser(label)]);
          end
      end
    end
    axis([psthStart psthEnd PSTH_AXIS_MIN PSTH_AXIS_MAX])
    xlabel('time [sec]');
    ylabel('fMRI-signal change [%]');
    hold off
end


function plotTrajectory(psth,psthStart,psthEnd)
% ERTA_AXIS_MAX = 2;
% ERTA_AXIS_MIN = 2;
% ERTB_AXIS_MAX = 2;
% ERTB_AXIS_MIN = 2;

    if (mod(size(psth,2),2)==0) %% TODO insufficient test!!!
    hold on;
%     grid on;
    for voxel = 1:2:size(psth,2)
        for label = 1:size(psth{voxel},2)
            ertDataA = [];
            for timepoint = 1:size(psth{voxel}{label},2)
                ertDataA = nanmean(psth{voxel}{label}); % mean ueber die trials
            end
%               ERTA_AXIS_MAX = max(ERTA_AXIS_MAX,nanmax(ertDataA));
%               ERTA_AXIS_MIN = min(ERTA_AXIS_MIN,nanmin(ertDataA));

            voxel2 = voxel+1;
            ertDataB = [];
            for timepoint = 1:size(psth{voxel2}{label},2)
                ertDataB = nanmean(psth{voxel2}{label}); % mean ueber die trials
            end
%               ERTB_AXIS_MAX = max(ERTB_AXIS_MAX,nanmax(ertDataB));
%               ERTB_AXIS_MIN = min(ERTB_AXIS_MIN,nanmin(ertDataB));
              
            plot3(psthStart:psthEnd,ertDataA,ertDataB,['.', colorChooser(label),'-']);
        end
    end
%     axis([psthStart psthEnd ERTA_AXIS_MIN ERTA_AXIS_MAX ERTB_AXIS_MIN ERTB_AXIS_MAX])
    axis tight;
    view(90,0);
    xlabel('time [sec]');
    ylabel('fMRI-signal change [%] A');
    zlabel('fMRI-signal change [%] B');
    
    hold off
    
    
    else 
        display('unsuitable # of voxel/roi!');
    end

end

function plotTrajectory3(ert)
    
    if (mod(size(ert,2),3)~=0)
        display('unsuitable # of voxel/roi!');
        return
    end
        
    nSubjects = size(ert,2)/3;
    
%     nLabel = size(ert{1},2);  % this is sane, because the program produces only such things.
    subplot(2,1,1);
    hold on;
%     for label = 1:nLabel 
        ertDataA = ertDataMatrix(ert,1,1,nSubjects);
        ertDataB = ertDataMatrix(ert,1,2,nSubjects);
        ertDataC = ertDataMatrix(ert,1,3,nSubjects);

        plot3(ertDataA,ertDataB,ertDataC,['.', colorChooser(1),'-']);

        ertDataA2 = ertDataMatrix(ert,2,1,nSubjects);
        ertDataB2 = ertDataMatrix(ert,2,2,nSubjects);
        ertDataC2 = ertDataMatrix(ert,2,3,nSubjects);

        plot3(ertDataA2,ertDataB2,ertDataC2,['.', colorChooser(2),'-']);

        %     end
        
        for a = 1:length(ertDataA)
            line([ertDataA(a) ertDataA2(a)],...
                [ertDataB(a) ertDataB2(a)],...
                [ertDataC(a) ertDataC2(a)],...
                'color',[.8/a 0 1-.8/a]);
            
            d(a) = sqrt( (ertDataA(a)-ertDataA2(a))^2 +...
            (ertDataB(a)-ertDataB2(a))^2 + ...
            (ertDataC(a)-ertDataC2(a))^2);
        end

    axis tight;
%     view(90,0);
    xlabel('fMRI-signal change [%] A');
    ylabel('fMRI-signal change [%] B');
    zlabel('fMRI-signal change [%] C');
    
    hold off

    subplot(2,1,2);
        
    plot(d);
    
end

function ertDataMatrix = ertDataMatrix(ert,label,roiID,nSubjects)
    ertDataMatrix = [];
    for subject = 1:nSubjects
        voxel = roiID*subject;
        for timepoint = 1:size(ert{voxel}{label},2)
            ertDataMatrix = [ertDataMatrix ; nanmean(ert{voxel}{label})]; % mean ueber die trials
        end
    end
    ertDataMatrix = nanmean(ertDataMatrix,1);
end


function color = colorChooser(n)
    switch (mod(n,8))
    case 0
        color = 'r';
    case 1
        color = 'g';
    case 2
        color = 'b';
    case 3
        color = 'c';
    case 4
        color = 'm';
    case 5
        color = 'y';
    otherwise
        color = 'k';
    end
end

function style = lineStyleChooser(n)
switch(mod(n,4))
    case 0
      style = '--';
    case 1
        style = '-';
    case 2 
        style = ':';
    case 3
        style = '-.';
end
end