function [fig,storeData,timesSec,legends]= PlotPPI(dat,plotl,settings)
% Plots PPIs stored in data
% plotl: store colors of lines

if ~isfield(plotl,'designList')
    ndes = length(dat.design);
    deslist=1:ndes;
else
    deslist=plotl.designList;
    ndes= length(deslist);
end
% plot settings
if ~isfield(plotl,'Colors') || isempty(plotl.Colors)
    colours= repmat([0 255 255],ndes,1); % colors in case we have more lines on the same plot
else
    colours = plotl.Colors;
end
colours= colours./255;
Liwi=2;
lineform={'-';':';'--';':'};


% Now plot the actual data
pcount=0;
for cp = deslist%1:ndes
    pcount=pcount+1;
    fig(pcount)=figure('color','w')
    
    if settings.split
    subplot(1,2,1)
    else
     subplot(1,1,1)   
    end
    
    % get the correct data + labels
    % physiological regressor when psychological is high, mid or low
    physXpsyInd = [find(~cellfun(@isempty,strfind(dat.design(cp).out.labels,'xHigh'))) ...
                  find(~cellfun(@isempty,strfind(dat.design(cp).out.labels,'xMid'))) ...
                  find(~cellfun(@isempty,strfind(dat.design(cp).out.labels,'xLow')))];
    
      %physXpsyInd=dat.physXpsyInd;
               
               if settings.split
                   pdata= squeeze(dat.design(cp).out.betas(:,:,:,physXpsyInd));
               else
                   physXpsyInd=  length(dat.design(cp).out.labels2);
                   pdata= squeeze(dat.design(cp).out.betas2(:,:,:,physXpsyInd));  
                   %keyboard;
               end
    %pdata2= squeeze(dat.design(cp).out.betas2([1:18 20:25],:,:,physXpsyInd));

    
    pdataDiff = squeeze(pdata(:,:,1))- squeeze(pdata(:,:,end)); %comparing high with low
    % Store the data so that we can print .txt files
    storeData{pcount}=pdata;
    %storeData2{pcount}=pdata2;

    
    % Plot the data
    for iline = 1:length(physXpsyInd)
        cpdat =squeeze(pdata(:,:,iline));
        
        h(iline*2-1)=plot(mean(cpdat),'Color',colours(pcount,:),'LineStyle', lineform{iline}, 'Linewidth',Liwi);
        
        hold on
        
        % Add shaded errorbars
        % Compute within subject error bars (from Morey 2008, Tutorias in quantitative methods for psychology)
        % in words: performance of participant minus this participant's
        % mean performance plus the group mean performance
        % accroding to Morey, we're also adjusting by multiplying with
        % sqrt(2)
        sqrTadj = sqrt(size(pdata,3)/(size(pdata,3)-1));
        cpdatDM = pdata(:,:,iline)- mean(pdata(:,:,:),3) +mean(mean(pdata,1),3);
        lst=mean(cpdat(:,1))-sqrTadj*std(cpdatDM(:,1))/sqrt(size(cpdat,1));
        ubou=mean(cpdat(:,:))+sqrTadj*std(cpdatDM(:,:))/sqrt(size(cpdat,1));
        lbou=mean(cpdat(:,:))-sqrTadj*std(cpdatDM(:,:))/sqrt(size(cpdat,1));
        
            if settings.split        
        h(iline*2)=patch([1 1:size(cpdat,2) size(cpdat,2):-1:1],[lst ubou lbou(end:-1:1)],colours(pcount,:),'facealpha',0.25,'edgecolor','k');
            else
            lst=mean(cpdat(:,1))-std(cpdat(:,1))/sqrt(size(cpdat,1));
        ubou=mean(cpdat(:,:))+std(cpdat(:,:))/sqrt(size(cpdat,1));
        lbou=mean(cpdat(:,:))-std(cpdat(:,:))/sqrt(size(cpdat,1));   
                h(iline*2)=patch([1 1:size(cpdat,2) size(cpdat,2):-1:1],[lst ubou lbou(end:-1:1)],colours(pcount,:),'facealpha',0.25,'edgecolor','none');
            end
    end
    
    % do the 0 line
    line([0 size(pdata,2)],[0 0],'Color','k')
    % Add a straight line for where the mean median RT is
    %meanRT=dat.design(1).inp(1).meanMedianDec1RT;
    %meanRT = settings.pseudosamples/settings.window*meanRT;
    %dat.design(plots(cp,1)).inp(1).SeparateMedianDec1RT
    %meanRTSTD=settings.pseudosamples/settings.window*mean(dat.design(1).inp(1).SeparateMedianDec1RTSTD);
    %if ~isfield(plotl,'ylims') 
    %    line([meanRT meanRT],[min(lbou) max(ubou)],'Color','k')
    %else
       % keyboard
    %    line([meanRT meanRT],[plotl.ylims(pcount,1)+0.1*abs(plotl.ylims(pcount,1)) plotl.ylims(pcount,2)-0.1*abs(plotl.ylims(pcount,2))],'Color','k')
    %end
       
    
    % add title and x tick lables
    title(['Seed: ' dat.design(cp).out.ppiInfo.seedRegion ' - Target: ' dat.design(cp).out.ppiInfo.targetRegion]);
    xlabel(['Time in seconds' ],'Fontweight','Bold','FontSize',16);
    set(gca,'XTick',0:(settings.pseudosamples/settings.window*2):(settings.pseudosamples))
    set(gca,'XTickLabel',0:2:settings.window,'FontSize',16)
    
    if settings.split
    legend(h([1:2:length(h)]),dat.design(cp).out.labels{physXpsyInd});% (1)},dat.design(cp).out.labels{physXpsyInd(2)})        
    legends{pcount} = dat.design(cp).out.labels(physXpsyInd);
    else
     legend(h([1:2:length(h)]),dat.design(cp).out.labels2{physXpsyInd});% (1)},dat.design(cp).out.labels{physXpsyInd(2)})        
    legends{pcount} = dat.design(cp).out.labels2(physXpsyInd);   
    end
    
    % Store the time (in sec) related to each pseudosample
    timesSecT=0:(settings.window/settings.pseudosamples):settings.window;
    timesSec=[];
    for it = 1:size(pdata,2)
        timesSec{it}= [num2str(timesSecT(it),'%.2f'), ' sec'];
    end
    
    % Determine how long to make the epoch
    if ~isfield(plotl,'TimeLimit')
        xlim([0 settings.pseudosamples])
    else
        
        xlim([0 floor(settings.pseudosamples/settings.window*plotl.TimeLimit(cp))])
    end
    if ~isfield(plotl,'ylims')
        ylim([min(lbou)-0.1*abs(min(lbou)) max(ubou)+0.1*abs(max(ubou))])
    else
        ylim([plotl.ylims(pcount,1) plotl.ylims(pcount,2)])
    end
    
    % make the second subplot - difference between the conditions
    if settings.split
    subplot(1,2,2)
    
    cpdat = pdataDiff;
    plot(mean(cpdat),'Color','k','LineStyle', lineform{1}, 'Linewidth',Liwi);
    hold on
    
    lst=mean(cpdat(:,1))-std(cpdat(:,1))/sqrt(size(cpdat,1));
    ubou=mean(cpdat(:,:))+std(cpdat(:,:))/sqrt(size(cpdat,1));
    lbou=mean(cpdat(:,:))-std(cpdat(:,:))/sqrt(size(cpdat,1));
    patch([1 1:size(cpdat,2) size(cpdat,2):-1:1],[lst ubou lbou(end:-1:1)],'k','facealpha',0.25,'edgecolor','none')
    
    % add RT and zero lines
    %line([meanRT meanRT],[min(lbou) max(ubou)],'Color','k')
    line([1 size(cpdat,2)],[0 0],'Color','k')
    %h=errorbar(meanRT,0,meanRTSTD,'k','horizontal','Linewidth',3,'Markersize',10);
    %        h.CapSize = 24;  
    % title and labels
    title(['Difference of PPIs']);
    xlabel(['Time in seconds' ],'Fontweight','Bold','FontSize',16);
    set(gca,'XTick',0:(settings.pseudosamples/settings.window*2):(settings.pseudosamples))
    set(gca,'XTickLabel',0:2:settings.window,'FontSize',16)
    else
        
    end
end


