function plotAverage(eventResponse, time, simplePlot, colors)
% function plotAverage(eventResponse, time, simplePlot)
% This function is to plot the result of cuixuNIRSRetrieve, i.e. it will
% plot the mean and with standard error shaded
%
% simplePlot: 0 or 1. by default 0. If 1, then only plot traces
% colors: if you don't specify, then each event has its own color. If
% specify, all event have the same color you specified. colors is a 1x3
% matrix specified as r-g-b
%
% Xu Cui
% 2009/07/22

if(~exist('simplePlot'))
    simplePlot = 0;
end

if(nargin <4)
    colors = [1 0 0;
        0 0 1;
        0 1 0;
        1 0 1;
        0 0 0;];
end
colors = repmat(colors, 10, 1);

lightColors = colors + 0.5;
lightColors(lightColors>1) = 1;


fs = fieldnames(eventResponse);
lg = {};
for ii=1:length(fs)
    x = getfield(eventResponse, fs{ii});
    m = meannan(x);
    s = stdnan(x)/sqrt(size(x,1));
    upper = m+s;
    lower = m-s;
    xpoints = time;
    
    filled=[upper,fliplr(lower)];
    xpoints=[xpoints,fliplr(xpoints)];
    
    if(simplePlot == 0)
        lg = [lg, ' '];
    
        fillhandle=fill(xpoints,filled,colors(ii,:));%plot the data
        set(fillhandle,'EdgeColor',[1 1 1],'FaceAlpha',0.2,'EdgeAlpha',0);%set edge color    
    
        hold on
    end
    
    plot(time, m, 'color', colors(ii,:), 'linewidth', 2);
    
    hold on
    
    lg = [lg, fs{ii}];
end
legend(lg)

l = line([0 0], [max(m+s), min(m-s)],'color',[0.7 0.7 0.7], 'linewidth',10);
uistack(l, 'bottom')

xlabel('time (s)');
ylabel('activity')
