function PalaPetersen_Plot(figname)

%
% LSENS, Aurelie Pala, July 2018
%
% Change the path to the data structure for the code to run
%
% figname: 'figure1'
% figname: 'figure2'
% figname: 'figure3' 
% figname: 'figure4'
% figname: 'figure2suppfig1'
% figname: 'figure2suppfig2'
% figname: 'figure2suppfig3'
% figname: 'figure3suppfig1'
% figname: 'figure4suppfig1'
%

%% General parameters
srate = 20000; %Hz, acquisition rate of electrophysiology
srate_mov = 200; %Hz, acquisition rate of whisker movies

%% Ploting parameters
close all
set(0,'DefaultFigureWindowStyle','docked');
colpvsst = {[255 0 0;255 153 153]/255,[200 140 0;250 200 90]/255};
colchronos = [0 0 0 ;0.5 0.5 0.5];

%% Input data file name and location
inputdatastruct_path = pwd; %location of the data structure is assumed to be in current folder
datastruct_name = 'data.mat'; %name of the data structure
cd(inputdatastruct_path)

%% Figure 1: spontaneous activity single PV and Sst examples
if(strcmp(figname,'figure1'))
    exampledata = {'AP060','PV',1,1,5,15;'AP056','Sst',1,3,7,17}; % Mouse_Name, Cell_Type, Cell_Counter, trial number, trial start (sec), trial end (sec)  
    
    tempstr = load(datastruct_name,'data');
    tempstr = tempstr.data;
    
    idexpt = tempstr.Mouse_Name;   
    idcelltype = tempstr.Cell_Type;
    idccount = tempstr.Cell_Counter;
    idttype = tempstr.Trial_Type;
    idttype= strcmp(idttype,'Spont');
    
    lfplh = tempstr.Trial_LFPLowHigh;
    wq = tempstr.Trial_WhiskNoWhisk;
    vm = tempstr.Trial_MembranePotential;
    lfp = tempstr.Trial_LFP;    
    whipos = tempstr.Trial_WhiskerAngleC2Right;
    
    clearvars tempstr
    
    for i =1 : size(exampledata,1)
        idexptsc= strcmp(idexpt,exampledata{i,1});
        idcelltypec= strcmp(idcelltype,exampledata{i,2});
        idccountc= idccount == exampledata{i,3};
        idtrials = idexptsc & idcelltypec & idccountc & idttype;
        
        lfplhc = lfplh(idtrials,:);
        wqc = wq(idtrials,:);
        vmc = cell2mat(vm(idtrials,:));
        lfpc = cell2mat(lfp(idtrials,:));
        whiposc = cell2mat(whipos(idtrials,:));
        
        %compute LFP power spectrum
        templfp = 1000000*lowpassfilt(lfpc(exampledata{i,4},:),200,srate); %uV
        F=0:1:15;
        shift=0.01*srate;
        N = 2*srate;
        w = hamming(N);
        ovlp = N-shift;
        
        [~,~,times,Pow] = spectrogram(templfp,w,ovlp,F,srate); % units uV^2/Hz
        Pow_norm = Pow./(max(max(Pow)));
        Pow_int = interp1(1:size(Pow_norm,1),Pow_norm,1:0.5:size(Pow_norm,1),'linear');
        
        %plot
        t = 0:1/srate:18-(1/srate);
        tmov = 0:1/srate_mov:18-(1/srate_mov); 
        xpl = 1*srate+1:19*srate;
        xplmov = 1*srate_mov+1:19*srate_mov;
        lw = 5;

        fig = figure;
        
        ax1 = subplot(5,1,1);
        plot(t,1000*vmc(exampledata{i,4},xpl),'Color',colpvsst{i}(1,:))
        axis tight
        title('Vm')
        ylabel('mV')
        ax1.Box = 'off';
        xlim([exampledata{i,5} exampledata{i,6}])
        
        ax2 = subplot(5,1,2);
        plot(tmov,whiposc(exampledata{i,4},xplmov)-mean(whiposc(exampledata{i,4},xplmov)),'g')
        axis tight
        ylabel('deg')
        title('Whisker angle')
        ax2.Box = 'off';
        xlim([exampledata{i,5} exampledata{i,6}])
        
        ax3 = subplot(5,1,3);
        plot(t,templfp(xpl)-mean(templfp(xpl)),'Color',[0.6 0.6 0.6])
        axis tight
        ylabel('uV')
        title('LFP')
        ax3.Box = 'off';
        xlim([exampledata{i,5} exampledata{i,6}])
        
        ax4 = subplot(5,1,4);
        imagesc(Pow_int)
        colorbar('Position',[0.93 0.28 0.019 0.09]);
        axis xy;
        axis tight;
        v = caxis;
        caxis ([v(1) v(2)/25])
        set(gca,'yTick',[1 31])
        set(gca,'yTickLabel',{'0','15'})
        set(gca,'xTick',[])
        ylabel('Hz')
        xlim([find(times==exampledata{i,5}+1) find(times==exampledata{i,6}+1)])
        title('LFP power spectrum')
        
        ax5 = subplot(5,1,5);
        temp = double(wqc{exampledata{i,4},1}(xpl));
        temp(temp==0)=NaN;
        plot(t,2*temp,'Color',[0 0.8 0],'LineWidth',lw)
        hold on
        temp = double(wqc{exampledata{i,4},2}(xpl));
        temp(temp==0)=NaN;
        plot(t,2*temp,'Color',[0.6 0.6 0.6],'LineWidth',lw)
        temp = double(lfplhc{exampledata{i,4},1});
        temp(temp==0)=NaN;
        plot(t,3*temp,'Color',[1 0.4 0.7],'LineWidth',lw)
        temp = double(lfplhc{exampledata{i,4},2});
        temp(temp==0)=NaN;
        plot(t,3*temp,'Color',[0.6 0.6 0.6],'LineWidth',lw)
        temp = double(lfplhc{exampledata{i,4},1} & wqc{exampledata{i,4},1}(xpl));
        temp(temp==0)=NaN;
        plot(t,temp,'Color',[0.4 0.4 1],'LineWidth',lw)
        temp = double(lfplhc{exampledata{i,4},2} & wqc{exampledata{i,4},2}(xpl));
        temp(temp==0)=NaN;
        plot(t,temp,'Color',[0.6 0.6 0.6],'LineWidth',lw)
        set(gca,'yTick',[])
        ylim([0.5 3.5])
        lgd = legend('W','NW','L','H','Active','Quiet','Location','none');
        lgd.Position=[0.92 0.09 0.06 0.14];
        xlabel('sec')
        title('States')
        ax5.Box = 'off';
        xlim([exampledata{i,5} exampledata{i,6}])
        linkaxes([ax1,ax2,ax3,ax5],'x')
        suptitleAP([exampledata{i,1} ' ' exampledata{i,2} '_' num2str(exampledata{i,3}) ' sweep no: ' num2str(exampledata{i,4})])
        
        %save
        cd(inputdatastruct_path)
        if(exist(fullfile(inputdatastruct_path,'Figures'),'dir')~=7)
            mkdir('Figures')
        end
        cd('Figures')
        fig.PaperUnits = 'centimeters';
        fig.PaperPosition = [0 0 27 15];
        fig.Renderer = 'Painters';
        savefig(fig,['Figure1_' exampledata{i,2}])
        %print(fig,['Figure1_' exampledata{i,2}],'-depsc') 
        cd(inputdatastruct_path)
    end
end

%% Figure 2: spontaneous activity across Quiet and Active states, PV and Sst population
if(strcmp(figname,'figure2'))
    
    [outputdata]=PalaPetersen_Analysis('spontaneous','save_n','ActiveQuiet');
    
    fig = figure;
    for i=1:size(outputdata,2)
        subplot(2,3,i)
        outputdataplot = outputdata{2,i};
        if(i~=4)
            temppv = ~isnan(outputdataplot{2,1}(:,[1 2]));
            idkeeppv = temppv(:,1)&temppv(:,2);
            tempsst = ~isnan(outputdataplot{2,2}(:,[1 2]));
            idkeepsst = tempsst(:,1)&tempsst(:,2);
            datpvkeep = outputdataplot{2,1}(idkeeppv,[1 2]);
            datsstkeep = outputdataplot{2,2}(idkeepsst,[1 2]);
            boxplot(datpvkeep,'Widths',0.5,'Colors',colpvsst{1}(1,:),'Symbol','','Positions',[2.4 0.6])
            hold on
            boxplot(datsstkeep,'Widths',0.5,'Colors',colpvsst{2}(1,:),'Symbol','','Positions',[5.4 3.6])
            for k=1:size(datpvkeep,1)
                plot([1 2], [datpvkeep(k,2) datpvkeep(k,1)],'Color',colpvsst{1}(1,:))
            end
            for k=1:size(datsstkeep,1)
                plot([4 5], [datsstkeep(k,2) datsstkeep(k,1)],'Color',colpvsst{2}(1,:))
            end
            plot([0.6 2.4], [mean(datpvkeep(:,2)) mean(datpvkeep(:,1))],'o','Color',colpvsst{1}(1,:),'MarkerFaceColor',colpvsst{1}(1,:),'MarkerSize',8)
            plot([3.6 5.4], [mean(datsstkeep(:,2)) mean(datsstkeep(:,1))],'o','Color',colpvsst{2}(1,:),'MarkerFaceColor',colpvsst{2}(1,:),'Markersize',8)
            xlim([0 6])
            text(0.18,0.95,[ 'p=' num2str(signrank(datpvkeep(:,1),datpvkeep(:,2)))],'Units','normalized')
            text(0.68,0.95,['p=' num2str(signrank(datsstkeep(:,1),datsstkeep(:,2)))],'Units','normalized')
            ttpv = datpvkeep(:,2);
            ttsst = datsstkeep(:,2);
            text(0.22,0.9,['n=' num2str(numel(ttpv(~isnan(ttpv))))],'Units','normalized')
            text(0.72,0.9,['n=' num2str(numel(ttsst(~isnan(ttsst))))],'Units','normalized')
            if(i==1)
                ylim([-66 -45])
                title('Mean Vm')
            end
            if(i==2)
                ylim([2 10])
                title('SD Vm')
            end
            if(i==3)
                ylim([0 60])
                title('AP rate')
            end
            if(i==5)
                ylim([0 20])
                title('Vm FFT 1-5 Hz amplitude')
            end
            if(i==6)
                ylim([-0.5 1])
                title('Vm vs LFP cross-correlation')
            end
            if(i==1 || i==2 || i==5)
                ylabel('mV')
            end
            if(i==3)
                ylabel('Hz')
            end
            if(i==6)
                ylabel(' ')
            end
            set(gca,'XTick',[0.6 2.4 3.6 5.4])
            set(gca,'XTickLabel',{'Quiet','Active','Quiet','Active'})     
        else
            temppv = cell2mat(cellfun(@(x) sum(isnan(x)),outputdataplot{2,1}(:,[2 1]),'UniformOutput',0));
            idkeeppv = ~(temppv(:,2)-temppv(:,1)~=0);
            tempsst = cell2mat(cellfun(@(x) sum(isnan(x)),outputdataplot{2,2}(:,[2 1]),'UniformOutput',0));
            idkeepsst = ~(tempsst(:,2)-tempsst(:,1)~=0);
            plot(nanmean(cell2mat(outputdataplot{2,1}(idkeeppv,2))),'Color',colpvsst{1}(2,:))
            hold on
            plot(nanmean(cell2mat(outputdataplot{2,1}(idkeeppv,1))),'Color',colpvsst{1}(1,:))
            plot(nanmean(cell2mat(outputdataplot{2,2}(idkeepsst,2))),'Color',colpvsst{2}(2,:))
            plot(nanmean(cell2mat(outputdataplot{2,2}(idkeepsst,1))),'Color',colpvsst{2}(1,:))
            legend('Quiet','Active','Quiet','Active')
            xlim([1 40])
            ylim([0 4])
            ylabel('mV/Hz')
            xlabel('Hz')
            set(gca,'XTick',0:10:40)
            set(gca,'XTickLabel',{'0','5','10','15','20'})
            title('Vm FFT amplitude')
        end   
    end
    
    %save
    cd(inputdatastruct_path)
    if(exist(fullfile(inputdatastruct_path,'Figures'),'dir')~=7)
        mkdir('Figures')
    end
    cd('Figures')
    fig.PaperUnits = 'centimeters';
    fig.PaperPosition = [0 0 27 15];
    fig.Renderer = 'Painters';
    savefig(fig,'Figure2')
    %print(fig,'Figure2','-depsc')
end

%% Figure 3: LED-evoked APs and uEPSPs single Chronos, PV and Sst examples
if(strcmp(figname,'figure3'))
    
    exampledata = {'AP061','Chronos',0,2,5,7;'AP069','PV',1,8,9,11;'AP040','Sst',2,16,10,12}; % Mouse_Name, Cell_Type, Cell_Counter, trial number, trial start (sec), trial end (sec)  
      
    tempstr = load(datastruct_name,'data');
    tempstr = tempstr.data;
    
    idexpts = tempstr.Mouse_Name;   
    idcelltype = tempstr.Cell_Type;
    idccount = tempstr.Cell_Counter;
    idttype = tempstr.Trial_Type;
    idttype= strcmp(idttype,'LED');
    
    lfplh = tempstr.Trial_LFPLowHigh;
    wq = tempstr.Trial_WhiskNoWhisk;
    vm = tempstr.Trial_MembranePotential;
    lfp = tempstr.Trial_LFP;    
    whipos = tempstr.Trial_WhiskerAngleC2Right;
    
    clearvars tempstr
        
    for i=1:size(exampledata,1)
        cd(inputdatastruct_path)
        idexptsc= strcmp(idexpts,exampledata{i,1});
        idcelltypec= strcmp(idcelltype,exampledata{i,2});
        if(strcmp(exampledata{i,2},'Chronos'))
            idtrials = idexptsc & idcelltypec & idttype;
        else
            idccountc= idccount==exampledata{i,3};
            idtrials = idexptsc & idcelltypec & idccountc & idttype;
        end
        lfplhc = lfplh(idtrials,:);
        wqc = wq(idtrials,:);
        vmc = cell2mat(vm(idtrials,:));
        lfpc = cell2mat(lfp(idtrials,:));
        whiposc = cell2mat(whipos(idtrials,:));
      
        if(i==1) % Chronos presynaptic cell           
            [outputdata]=PalaPetersen_Analysis('chronos','save_n','ActiveQuiet');   
            exptsid = outputdata{2,6};
            exptsid = strcmp(exptsid,exampledata{i,1});
            indtrials = outputdata{2,7};
            indtrialsc = indtrials(exptsid,:);
        else % Postsynaptic cells   
            if(i==2)
                [outputdata]=PalaPetersen_Analysis('uEPSP','save_n','ActiveQuiet');
            end
            exptsid = outputdata{2,2};
            exptsid = strcmp(exptsid{2,i-1},[exampledata{i,1} '_' exampledata{i,3}]);
            indtrials = outputdata{2,3};
            indtrialsc = indtrials{2,i-1}(exptsid,[1 2]);
        end
        
                
        %plot      
        t = 0:1/srate:18-(1/srate);
        tmov = 0:1/srate_mov:18-(1/srate_mov); 
        xpl = 1*srate+1:19*srate;
        xplmov = 1*srate_mov+1:19*srate_mov;
        lw =5;
        led1st = zeros(1*srate,1);
        led1st(0.5*srate+1:0.501*srate)=1;
        led=repmat(led1st,18,1);
        nsp = 1;
        colfig = [colchronos(1,:);colpvsst{1}(1,:);colpvsst{2}(1,:)];
        
        fig1 = figure;
        ax1 = subplot(5,nsp,1);
        plot(t,1000*vmc(exampledata{i,4},xpl),'Color',colfig(i,:))
        title('Vm')
        ylabel('mV')
        set(ax1,'XTick',[])
        ax1.Box = 'off';
        xlim(ax1,[exampledata{i,5} exampledata{i,6}])
        if(i==1)
            ylim(ax1,[-2 2])
        end
        if(i==2)
            ylim(ax1,[min(1000*vmc(exampledata{i,4},xpl)) -30])
        end
        if(i==3)
            ylim(ax1,[min(1000*vmc(exampledata{i,4},xpl)) -40])
        end
        
        ax2 = subplot(5,nsp,nsp+1);
        plot(tmov,whiposc(exampledata{i,4},xplmov)-mean(whiposc(exampledata{i,4},xplmov)),'g')
        axis tight
        title('Whisker position')
        ylabel('deg')
        set(ax2,'XTick',[])
        ax2.Box = 'off';
        xlim(ax2,[exampledata{i,5} exampledata{i,6}])
        
        ax3 = subplot(5,nsp,2*nsp+1);
        temp = 1000000*lowpassfilt(lfpc(exampledata{i,4},xpl),200,srate);
        plot(t,temp-mean(temp),'Color',[0.6 0.6 0.6])
        axis tight
        title('LFP')
        ylabel('uV')
        set(ax3,'XTick',[])
        ax3.Box = 'off';
        xlim(ax3,[exampledata{i,5} exampledata{i,6}])
        
        ax4 = subplot(5,nsp,3*nsp+1);
        temp = double(lfplhc{exampledata{i,4},1});
        temp(temp==0)=NaN;
        plot(t,3*temp,'Color',[1 0.4 0.7],'LineWidth',lw)
        hold on
        temp = double(lfplhc{exampledata{i,4},2});
        temp(temp==0)=NaN;
        plot(t,3*temp,'Color',[0.6 0.6 0.6],'LineWidth',lw)
        temp = double(wqc{exampledata{i,4},1}(xpl));
        temp(temp==0)=NaN;
        plot(t,2*temp,'Color',[0 0.8 0],'LineWidth',lw)
        temp = double(wqc{exampledata{i,4},2}(xpl));
        temp(temp==0)=NaN;
        plot(t,2*temp,'Color',[0.6 0.6 0.6],'LineWidth',lw)
        temp = double(lfplhc{exampledata{i,4},1} & wqc{exampledata{i,4},1}(xpl));
        temp(temp==0)=NaN;
        plot(t,temp,'Color',[0.4 0.4 1],'LineWidth',lw)
        temp = double(lfplhc{exampledata{i,4},2} & wqc{exampledata{i,4},2}(xpl));
        temp(temp==0)=NaN;
        plot(t,temp,'Color',[0.6 0.6 0.6],'LineWidth',lw)
        set(ax4,'YTick',[])
        set(ax4,'XTick',[])
        ylim([0.5 3.5])
        lgd = legend('L','H','W','NW','Active','Quiet','Location','none');
        lgd.Position=[0.91 0.24 0.08 0.21];
        title('States')
        ax4.Box = 'off';
        xlim(ax4,[exampledata{i,5} exampledata{i,6}])
            
        ax5 = subplot(5,nsp,4*nsp+1);
        plot(t,led,'Color',[0.4 0.7 1],'LineWidth',1)
        ax5.Box = 'off';
        axis tight
        set(ax5,'YTick',[])
        xlabel('sec')
        title('LED')
        xlim(ax5,[exampledata{i,5} exampledata{i,6}])
        linkaxes([ax1,ax2,ax3,ax4,ax5],'x')
        if(i==1)
            suptitleAP([exampledata{i,1} ' ' exampledata{i,2} ' sweep no ' num2str(exampledata{i,4})])
            
        else
            suptitleAP([exampledata{i,1} ' ' exampledata{i,2} '_' num2str(exampledata{i,3}) ' sweep no ' num2str(exampledata{i,4})])
        end
                   
        fig2 = figure;
        tsh = 1000*(-0.005:1/srate:0.01-(1/srate));
        if(i==1)
            sp = 1;
        else
            sp = 3;
        end
        if(i==1)
            colfig2 = colchronos;
        else
            colfig2 = [colpvsst{i-1}];
        end

        titlab = {'Active','Quiet'};      

        for s=1:size(indtrialsc,2)
            ax1(s) = subplot(1,2,size(indtrialsc,2)-(s-1));
            if(i==1)
                indtrialsc{s}= cell2mat(indtrialsc{s});
                indtrialsc{s}=indtrialsc{s}./1000;
            end
            for k=1:size(indtrialsc{s},1)
                tempo = 1000*indtrialsc{s}(k,0.495*srate+1:0.510*srate);
                plot(tsh,tempo-mean(tempo)-(k-1)*sp,'Color',colfig2(s,:))
                hold on
            end
            if(i==1)
                fill([0 1 1 0],[-k*sp -k*sp 3*sp 3*sp],[0.4 0.7 1],'Linestyle','none','FaceAlpha',0.5)
            else
                fill([0 1 1 0],[-k*sp -k*sp 2*sp 2*sp],[0.4 0.7 1],'Linestyle','none','FaceAlpha',0.5)
            end
            axis tight
            set(ax1(s),'XTick',[-5 0 5 10])
            ylabel('mV')
            xlabel('ms')
            ax1(s).Box = 'off';
            title(titlab{s})
        end       
        if(i==1)
            suptitleAP([exampledata{i,1} ' ' exampledata{i,2}])
        else
            suptitleAP([exampledata{i,1} ' ' exampledata{i,2} '_' exampledata{i,3}])
        end
        
        %save
        cd(inputdatastruct_path)
        if(exist(fullfile(inputdatastruct_path,'Figures'),'dir')~=7)
            mkdir('Figures')
        end
        cd('Figures')
        fig1.PaperUnits = 'centimeters';
        fig1.PaperPosition = [0 0 27 15];
        fig1.Renderer = 'Painters';
        savefig(fig1,['Figure3_' exampledata{i,2} '_part1'])
        %print(fig1,['Figure3_' exampledata{i,2} '_part1'],'-depsc')
        fig2.PaperUnits = 'centimeters';
        fig2.PaperPosition = [0 0 27 15];
        fig2.Renderer = 'Painters';
        savefig(fig2,['Figure3_' exampledata{i,2} '_part2'])
        %print(fig2,['Figure3_' exampledata{i,2} '_part2'],'-depsc')
    end
end

%% Figure 4: uEPSPs analysis, across Quiet and Active states, PV and Sst population
if(strcmp(figname,'figure4'))   
    
    [outputdata]=PalaPetersen_Analysis('uEPSP','save_n','ActiveQuiet');
    
    x = -500:1000/srate:500;
    x = x(1:end-1);
    labtitle = {'PV','Sst'};
    
    fig = figure;
    
    ax(1) = subplot(3,3,1); % All trials PV, SST, NC
    tp1 = mean(cell2mat(outputdata{2,4}{2,1}(:,3)'),2);%PV
    p1 = plot(x,tp1-tp1(10032),'Color',colpvsst{1}(1,:));
    hold on
    tp2 = mean(cell2mat(outputdata{2,4}{2,2}(:,3)'),2);%Sst
    p2 = plot(x,tp2-tp2(10032),'Color',colpvsst{2}(1,:));
    tp3 = mean(cell2mat(outputdata{2,1}{2,1}'),2);%NC
    p3 = plot(x,tp3 - tp3(10032),'Color',[0.5 0.5 0.5]);
    fill([0 1 1 0],[-0.4 -0.4 1.2 1.2],[0.4 0.7 1],'Linestyle','none','FaceAlpha',0.5)
    legend([p1 p2 p3],{['PV (n=' num2str(size(outputdata{2,4}{2,1},1)) ')'],['SST (n=' num2str(size(outputdata{2,4}{2,2},1)) ')'],['NC (n=' num2str(size(outputdata{2,1}{2,1},1)) ')']},'Location','Northwest')
    xlim([-5 10])
    ylim([-0.4 1.2])
    xlabel('ms')
    ylabel('mV')
    ax(1).Box = 'off';   
    for k=1:2 % PV and SST
            ax(k+1)=subplot(3,3,k+1);
            tp1 = mean(cell2mat(outputdata{2,4}{2,k}(:,1)'),2);
            tp2 = mean(cell2mat(outputdata{2,4}{2,k}(:,2)'),2);
            p1 = plot(x,tp1-tp1(10032),'Color',colpvsst{k}(1,:));
            hold on
            p2 = plot(x,tp2-tp2(10032),'Color',colpvsst{k}(2,:));     
            fill([0 1 1 0],[-0.4 -0.4 1.2 1.2],[0.4 0.7 1],'Linestyle','none','FaceAlpha',0.5)
            legend([p1 p2],{'Active','Quiet'},'Location','Northwest')
            ylim([-0.4 1.2])
            xlim([-5 10])
            xlabel('ms')
            ylabel('mV')
            ax(k+1).Box = 'off';
            title([labtitle{k} '  (n=' num2str(size(cell2mat(outputdata{2,4}{2,k}(:,1)'),2)) ' cells)'])
    end
    
    for i=1:2 % uEPSP amplitude, uEPSP baseline Vm
        for j = 1:3 %states
            ax(i,1)=subplot(3,3,i*3+1); % no state sorting, compare PV vs Sst
            for k=1:2 % PV, Sst
                outputdataplot = outputdata{2,5+i}{2,k}(:,3);
                boxplot(outputdataplot,'Widths',0.5,'Colors',colpvsst{k}(1,:),'Symbol','','Positions',k)
                hold on
                plot(k,mean(outputdataplot),'o','Color',colpvsst{k}(1,:),'MarkerFaceColor',colpvsst{k}(1,:),'MarkerSize',8)
                for l=1:length(outputdataplot)
                    plot(k+0.4,outputdataplot(l),'o','Color',colpvsst{k}(1,:),'MarkerSize',8)
                end                             
            end
            xlim([0 3])
            set(gca,'XTick',[1 2])
            set(gca,'XTickLabel',{'PV','Sst'})
            if(i==1)
                ylim([-0.5 4])
                ylabel('uEPSP amplitude (mV)')
            end
            if(i==2)
                ylim([-68 -45])
                ylabel('Baseline Vm (mV)')
            end
            text(0.4,0.95,[ 'p=' num2str(ranksum(outputdata{2,5+i}{2,1}(:,3),outputdata{2,5+i}{2,2}(:,3)))],'Units','normalized')
            ax(i,2)=subplot(3,3,[i*3+2 i*3+3]);
            for k=1:2 % PV, Sst
                outputdataplot = outputdata{2,5+i}{2,k}(:,[1 2]);
                tempdat = ~isnan(outputdataplot);
                idkeep = tempdat(:,1)&tempdat(:,2);
                outputdataplot = fliplr(outputdataplot(idkeep,:));
                datstat{k}=outputdataplot;
                boxplot(outputdataplot,'Widths',0.5,'Colors',colpvsst{k}(1,:),'Symbol','','Positions',[k^2 3*k])
                hold on
                plot([k^2 3*k],mean(outputdataplot),'o','Color',colpvsst{k}(1,:),'MarkerFaceColor',colpvsst{k}(1,:),'MarkerSize',8)
                for l=1:size(outputdataplot,1)
                    plot([k^2+0.5 3*k-0.5],outputdataplot(l,:),'Color',colpvsst{k}(1,:))
                end

            end
            xlim([0 7])
            set(gca,'XTick',[1 3 4 6])
            set(gca,'XTickLabel',{'Quiet','Active','Quiet','Active'})
            if(i==1)
                ylim([-0.5 4])
                ylabel('uEPSP amplitude (mV)')
                text(0.2,0.95,[ 'p=' num2str(signrank(datstat{1}(:,1),datstat{1}(:,2),'tail','left'))],'Units','normalized')
                text(0.7,0.95,[ 'p=' num2str(signrank(datstat{2}(:,1),datstat{2}(:,2),'tail','left'))],'Units','normalized')
            end
            if(i==2)
                ylim([-68 -45])
                ylabel('Baseline Vm (mV)')            
                text(0.2,0.95,[ 'p=' num2str(signrank(datstat{1}(:,1),datstat{1}(:,2),'tail','left'))],'Units','normalized')
                text(0.7,0.95,[ 'p=' num2str(signrank(datstat{2}(:,1),datstat{2}(:,2),'tail','right'))],'Units','normalized')
            end
        end
    end
    suptitleAP('uEPSP analysis')
    
    %save
    cd(inputdatastruct_path)
    if(exist(fullfile(inputdatastruct_path,'Figures'),'dir')~=7)
        mkdir('Figures')
    end
    cd('Figures')
    fig.PaperUnits = 'centimeters';
    fig.PaperPosition = [0 0 27 15];
    fig.Renderer = 'Painters';
    savefig(fig,'Figure4')
    %print(fig,'Figure4','-depsc')     
end

%% Figure 2 Supp Figure 1: LFP FFT amplitude and Whisking/Non-Whisking epochs across mouse genotypes
if(strcmp(figname,'figure2suppfig1'))
    outputdata = PalaPetersen_Analysis('LFPFFTamplitude','save_n');
    idpv = strcmp(outputdata(:,2),'PV');
    datpv = outputdata(idpv,:);
    datsst = outputdata(~idpv,:);
    
    outputdatawnw = PalaPetersen_Analysis('whisking','save_n');
    idpvwnw = strcmp(outputdatawnw(:,2),'PV');
    idsstwnw = strcmp(outputdatawnw(:,2),'Sst');
    datpvwnw = outputdatawnw(idpvwnw,:);
    datsstwnw = outputdatawnw(idsstwnw,:);
    datwnw = {datpvwnw,datsstwnw};
    
    fig= figure; 
    subplot(2,4,[1 2])%FFT amplitude spectrum
    plot(0:0.5:10000,mean(cell2mat(datpv(:,3))),'Color',colpvsst{1}(1,:));
    hold on
    plot(0:0.5:10000,mean(cell2mat(datsst(:,3))),'Color',colpvsst{2}(1,:));
    legend(['PV (n=' num2str(length(datpv)) ' mice)'],['Sst (n=' num2str(length(datsst)) ' mice)'])
    xlim([0 20])
    ylim([0 0.05])
    xlabel('Hz')
    ylabel('mV/Hz')
    title('LFP FFT amplitude')
    
    subplot(2,4,3)%FFT amplitude 1-5Hz
    boxplot(cell2mat(datpv(:,4)),'Widths',0.5,'Colors',colpvsst{1}(1,:),'Symbol','','Positions',1)
    hold on
    boxplot(cell2mat(datsst(:,4)),'Widths',0.5,'Colors',colpvsst{2}(1,:),'Symbol','','Positions',2)
    for k=1:size(datpv,1)
        plot(0.6,datpv{k,4},'o','Color',colpvsst{1}(1,:),'MarkerSize',8)
    end
    for k=1:size(datsst,1)
        plot(1.6,datsst{k,4},'o','Color',colpvsst{2}(1,:),'MarkerSize',8)
    end
    plot(1,mean(cell2mat(datpv(:,4))),'o','Color',colpvsst{1}(1,:),'MarkerFaceColor',colpvsst{1}(1,:),'MarkerSize',8)
    plot(2,mean(cell2mat(datsst(:,4))),'o','Color',colpvsst{2}(1,:),'MarkerFaceColor',colpvsst{2}(1,:),'MarkerSize',8)
    set(gca,'XTick',[1 2])
    set(gca,'XTickLabel',{'PV','Sst'})
    xlim([0 2.8])
    ylim([0.09 0.15])
    ylabel('mV')
    text(0.4,0.95,['p=' num2str(ranksum(cell2mat(datpv(:,4)),cell2mat(datsst(:,4))))],'Units','normalized')
    title('LFP FFT amplitude 1-5Hz')
    
    subplot(2,4,4)%FFT amplitude 1-80Hz
    boxplot(cell2mat(datpv(:,5)),'Widths',0.5,'Colors',colpvsst{1}(1,:),'Symbol','','Positions',1)
    hold on
    boxplot(cell2mat(datsst(:,5)),'Widths',0.5,'Colors',colpvsst{2}(1,:),'Symbol','','Positions',2)
    for k=1:size(datpv,1)
        plot(0.6,datpv{k,5},'o','Color',colpvsst{1}(1,:),'MarkerSize',8)
    end
    for k=1:size(datsst,1)
        plot(1.6,datsst{k,5},'o','Color',colpvsst{2}(1,:),'MarkerSize',8)
    end
    plot(1,mean(cell2mat(datpv(:,5))),'o','Color',colpvsst{1}(1,:),'MarkerFaceColor',colpvsst{1}(1,:),'MarkerSize',8)
    plot(2,mean(cell2mat(datsst(:,5))),'o','Color',colpvsst{2}(1,:),'MarkerFaceColor',colpvsst{2}(1,:),'MarkerSize',8)
    set(gca,'XTick',[1 2])
    set(gca,'XTickLabel',{'PV','Sst'})
    xlim([0 2.8])
    ylim([0.38 0.63])
    ylabel('mV')
    text(0.4,0.95,['p=' num2str(ranksum(cell2mat(datpv(:,5)),cell2mat(datsst(:,5))))],'Units','normalized')
    title('LFP FFT amplitude 1-80Hz')
    
    subplot(2,4,[5 6])%Fraction of time Whisking/Non-Whisking
    for i=1:2%PV, Sst
        boxplot(100*cell2mat(datwnw{i}(:,4)),'Widths',0.5,'Colors',colpvsst{i}(1,:),'Symbol','','Positions',i)
        if(i==1)
            hold on
        end
        boxplot(100*cell2mat(datwnw{i}(:,3)),'Widths',0.5,'Colors',colpvsst{i}(1,:),'Symbol','','Positions',i+3)
        plot([i,i+3],[mean(100*cell2mat(datwnw{i}(:,4))) mean(100*cell2mat(datwnw{i}(:,3)))],'o','Color',colpvsst{i}(1,:),'MarkerFaceColor',colpvsst{i}(1,:),'MarkerSize',8)
        for j = 1:size(datwnw{i},1)
            plot([i-0.4,i+3-0.4],[100*cell2mat(datwnw{i}(j,4)) 100*cell2mat(datwnw{i}(j,3))],'o','Color',colpvsst{i}(1,:),'MarkerSize',8)
        end
    
    end
    xlim([0 6])
    ylim([0 100])
    set(gca,'XTick',[1 2 4 5])
    set(gca,'XTickLabel',{'PV','Sst','PV','Sst'})
    ylabel('Percentage(%)')
    title('Fraction of time')
    text(0.18,0.95,'Not Whisking','Units','normalized','FontWeight','bold')
    text(0.7,0.95,'Whisking','Units','normalized','FontWeight','bold')
    text(0.25,0.85,['p=' num2str(ranksum(cell2mat(datwnw{1}(:,4)),cell2mat(datwnw{2}(:,4))))],'Units','normalized')
    text(0.7,0.85,['p=' num2str(ranksum(cell2mat(datwnw{1}(:,3)),cell2mat(datwnw{2}(:,3))))],'Units','normalized')

    subplot(2,4,[7 8])%Epoch duration Whisking/Non-Whisking
    for i=1:2%PV, Sst
        boxplot(cell2mat(datwnw{i}(:,6)),'Widths',0.5,'Colors',colpvsst{i}(1,:),'Symbol','','Positions',i)
        if(i==1)
            hold on
        end
        boxplot(cell2mat(datwnw{i}(:,5)),'Widths',0.5,'Colors',colpvsst{i}(1,:),'Symbol','','Positions',i+3)
        plot([i,i+3],[mean(cell2mat(datwnw{i}(:,6))) mean(cell2mat(datwnw{i}(:,5)))],'o','Color',colpvsst{i}(1,:),'MarkerFaceColor',colpvsst{i}(1,:),'MarkerSize',8)
        for j = 1:size(datwnw{i},1)
            plot([i-0.4,i+3-0.4],[cell2mat(datwnw{i}(j,6)) cell2mat(datwnw{i}(j,5))],'o','Color',colpvsst{i}(1,:),'MarkerSize',8)
        end
    
    end
    xlim([0 6])
    ylim([0 3])
    set(gca,'XTick',[1 2 4 5])
    set(gca,'XTickLabel',{'PV','Sst','PV','Sst'})
    ylabel('Time(s)')
    title('Mean epoch duration')
    text(0.18,0.95,'Not Whisking','Units','normalized','FontWeight','bold')
    text(0.7,0.95,'Whisking','Units','normalized','FontWeight','bold')
    text(0.25,0.85,['p=' num2str(ranksum(cell2mat(datwnw{1}(:,6)),cell2mat(datwnw{2}(:,6))))],'Units','normalized')
    text(0.7,0.85,['p=' num2str(ranksum(cell2mat(datwnw{1}(:,5)),cell2mat(datwnw{2}(:,5))))],'Units','normalized')


    
    %save
    cd(inputdatastruct_path)
    if(exist(fullfile(inputdatastruct_path,'Figures'),'dir')~=7)
        mkdir('Figures')
    end
    cd('Figures')
    fig.PaperUnits = 'centimeters';
    fig.PaperPosition = [0 0 27 15];
    fig.Renderer = 'Painters';
    savefig(fig,'Figure2_SuppFigure1')
    %print(fig,'Figure2_SuppFigure1','-depsc') 
  
end

%% Figure 2 Supp Figure 2: spontaneous activity across High and Low LFP Power, and NW and W
if(strcmp(figname,'figure2suppfig2'))

    outputdatastov = PalaPetersen_Analysis('stateoverlap','save_n');

    
    outputdata = PalaPetersen_Analysis('spontaneous','save_n','LFPPowHLandNWW');
    outputdata = outputdata(:,[1 2 4 5 3 6]);

    meandatastov = 100*mean(outputdatastov,1);
    stddatastov = 100*std(outputdatastov);
    
    fig1 = figure;
    titles = {'High 1-5Hz LFP Power','Low 1-5Hz LFP Power','Not-Whisking','Whisking'};
    colbar = [0 0.8 0 ;0 0.8 0; 1 0.4 0.7;1 0.4 0.7];
    for i=1:4
        subplot(2,4,i)
        bar(1,meandatastov(3*i-2),0.8,'FaceColor',[0.6 0.6 0.6],'EdgeColor',[0.6 0.6 0.6]);
        hold on
        errorbar(1,meandatastov(3*i-2),stddatastov(3*i-2),'.','Color',[0.6 0.6 0.6],'LineWidth',2)
        bar(2,meandatastov(3*i-1),0.8,'FaceColor',colbar(i,:),'EdgeColor',colbar(i,:));
        errorbar(2,meandatastov(3*i-1),stddatastov(3*i-1),'.','Color',colbar(i,:),'LineWidth',2)
        text(0.35,0.95,[ 'p=' num2str(signrank(outputdatastov(:,3*i-2),outputdatastov(:,3*i-1)))],'Units','normalized')
        ylim([0 100])
        xlim([0 3]) 
        ylabel('Fraction of time (%)')
        set(gca,'XTick',[1 2])
        if(i<3)
            set(gca,'XTickLabel',{'NW','W'})
        else
            set(gca,'XTickLabel',{'H','L'})
        end
        title(titles{i})
        if(i==1)
            text(0.35,0.85,['n=' num2str(size(outputdatastov,1)) ' mice'],'Units','normalized')
        end
    end
    
    fig2 =figure;
    for i=1:6
        outputdataplot = outputdata{2,i};
        if(i~=3)
            subplot(3,4,[2*i-1 2*i])
            for j=1:2
                temppv = ~isnan(outputdataplot{2,1}(:,[2*j-1 2*j]));
                idkeeppv = temppv(:,1)&temppv(:,2);
                tempsst = ~isnan(outputdataplot{2,2}(:,[2*j-1 2*j]));
                idkeepsst = tempsst(:,1)&tempsst(:,2);
                datpvkeep = outputdataplot{2,1}(idkeeppv,[2*j-1 2*j]);
                datsstkeep = outputdataplot{2,2}(idkeepsst,[2*j-1 2*j]);
                boxplot(datpvkeep,'Widths',0.5,'Colors',colpvsst{1}(1,:),'Symbol','','Positions',[6*(j-1)+0.6 6*(j-1)+2.4])
                hold on
                boxplot(datsstkeep,'Widths',0.5,'Colors',colpvsst{2}(1,:),'Symbol','','Positions',[6*(j-1)+3.6 6*(j-1)+5.4])
                for k=1:size(datpvkeep,1)
                    plot([6*(j-1)+2 6*(j-1)+1], [datpvkeep(k,2) datpvkeep(k,1)],'Color',colpvsst{1}(1,:))
                end
                for k=1:size(datsstkeep,1)
                    plot([6*(j-1)+5 6*(j-1)+4], [datsstkeep(k,2) datsstkeep(k,1)],'Color',colpvsst{2}(1,:))
                end
                plot([6*(j-1)+2.4 6*(j-1)+0.6], [mean(datpvkeep(:,2)) mean(datpvkeep(:,1))],'o','Color',colpvsst{1}(1,:),'MarkerFaceColor',colpvsst{1}(1,:),'MarkerSize',8)
                plot([6*(j-1)+5.4 6*(j-1)+3.6], [mean(datsstkeep(:,2)) mean(datsstkeep(:,1))],'o','Color',colpvsst{2}(1,:),'MarkerFaceColor',colpvsst{2}(1,:),'Markersize',8)
                xlim([0 12])
                text((j-1)*0.5+0.08,0.95,[ 'p=' num2str(signrank(datpvkeep(:,1),datpvkeep(:,2)))],'Units','normalized')
                text((j-1)*0.5+0.3,0.95,['p=' num2str(signrank(datsstkeep(:,1),datsstkeep(:,2)))],'Units','normalized')
                ttpv = datpvkeep(:,2);
                ttsst = datsstkeep(:,2);
                text((j-1)*0.5+0.08,0.85,['n=' num2str(numel(ttpv(~isnan(ttpv))))],'Units','normalized')
                text((j-1)*0.5+0.3,0.85,['n=' num2str(numel(ttsst(~isnan(ttsst))))],'Units','normalized')
            end
            if(i==1)
                ylim([-65 -40])
                title('Mean Vm')
            end
            if(i==2)
                ylim([2 12])
                title('SD Vm')
            end
            if(i==4)
                ylim([2 22])
                title('Vm FFT 1-5 Hz amplitude')
            end
            if(i==5)
                ylim([0 70])
                title('AP rate')
            end
            if(i==6)
                ylim([-0.5 1.25])
                title('Vm vs LFP cross-correlation')
            end
            if(i==1 || i==2 || i==4)
                ylabel('mV')
            end
            if(i==5)
                ylabel('Hz')
            end
            if(i==6)
                ylabel(' ')
            end
            set(gca,'XTick',[0.6 2.4 3.6 5.4 6.6 8.4 9.6 11.4])
            set(gca,'XTickLabel',{'H','L','H','L','NW','W','NW','W'})      
        else
            subplot(3,4,2*i-1)
            temppv = cell2mat(cellfun(@(x) sum(isnan(x)),outputdataplot{2,1}(:,[2 1]),'UniformOutput',0));
            idkeeppv = ~(temppv(:,2)-temppv(:,1)~=0);
            tempsst = cell2mat(cellfun(@(x) sum(isnan(x)),outputdataplot{2,2}(:,[2 1]),'UniformOutput',0));
            idkeepsst = ~(tempsst(:,2)-tempsst(:,1)~=0);
            plot(nanmean(cell2mat(outputdataplot{2,1}(idkeeppv,2))),'Color',colpvsst{1}(1,:))
            hold on
            plot(nanmean(cell2mat(outputdataplot{2,1}(idkeeppv,1))),'Color',colpvsst{1}(2,:))
            plot(nanmean(cell2mat(outputdataplot{2,2}(idkeepsst,2))),'Color',colpvsst{2}(1,:))
            plot(nanmean(cell2mat(outputdataplot{2,2}(idkeepsst,1))),'Color',colpvsst{2}(2,:))
            legend('L','H','L','H')
            xlim([1 40])
            ylim([0 4])
            ylabel('mV/Hz')
            xlabel('Hz')
            set(gca,'XTick',0:10:40)
            set(gca,'XTickLabel',{'0','5','10','15','20'})
            title('Vm FFT amplitude')
            
            subplot(3,4,2*i)
            temppv = cell2mat(cellfun(@(x) sum(isnan(x)),outputdataplot{2,1}(:,[4 3]),'UniformOutput',0));
            idkeeppv = ~(temppv(:,2)-temppv(:,1)~=0);
            tempsst = cell2mat(cellfun(@(x) sum(isnan(x)),outputdataplot{2,2}(:,[4 3]),'UniformOutput',0));
            idkeepsst = ~(tempsst(:,2)-tempsst(:,1)~=0);
            plot(nanmean(cell2mat(outputdataplot{2,1}(idkeeppv,4))),'Color',colpvsst{1}(1,:))
            hold on
            plot(nanmean(cell2mat(outputdataplot{2,1}(idkeeppv,3))),'Color',colpvsst{1}(2,:))
            plot(nanmean(cell2mat(outputdataplot{2,2}(idkeepsst,4))),'Color',colpvsst{2}(1,:))
            plot(nanmean(cell2mat(outputdataplot{2,2}(idkeepsst,3))),'Color',colpvsst{2}(2,:))
            legend('W','NW','W','NW')
            xlim([1 40])
            ylim([0 4])
            ylabel('mV/Hz')
            xlabel('Hz')
            set(gca,'XTick',0:10:40)
            set(gca,'XTickLabel',{'0','5','10','15','20'})
            title('Vm FFT amplitude')
        end
        
    end
    
    %save
    cd(inputdatastruct_path)
    if(exist(fullfile(inputdatastruct_path,'Figures'),'dir')~=7)
        mkdir('Figures')
    end
    cd('Figures')
    fig1.PaperUnits = 'centimeters';
    fig1.PaperPosition = [0 0 27 15];
    fig1.Renderer = 'Painters';
    savefig(fig1,'Figure2_SuppFigure2_part1')
    %print(fig1,'Figure2_SuppFigure2_part1','-depsc')
    fig2.PaperUnits = 'centimeters';
    fig2.PaperPosition = [0 0 27 15];
    fig2.Renderer = 'Painters';
    savefig(fig2,'Figure2_SuppFigure2_part2')
    %print(fig2,'Figure2_SuppFigure2_part2','-depsc')
end

%% Figure 2 Supp Figure 3: spontaneous activity Low LFP Power NW W, and Not-Whisking L H
if(strcmp(figname,'figure2suppfig3'))
    
    anatp = {'LFPPowL_WNW','NW_LFPPowLH'};
    suptitles = {'Low 1-5 Hz LFP Power','Not-Whisking'};
    
    for l=1:2
        cd(inputdatastruct_path)
        outputdata = PalaPetersen_Analysis('spontaneous','save_n',anatp{l});
        outputdata = outputdata(:,[1 2 4 5 3 6]);
        
        fig =figure;
        for i=1:6
            outputdataplot = outputdata{2,i};
            outputdataplot{2,1}=fliplr(outputdataplot{2,1});
            outputdataplot{2,2}=fliplr(outputdataplot{2,2});
            if(i~=3)
                subplot(3,2,i)
                temppv = ~isnan(outputdataplot{2,1}(:,[1 2]));
                idkeeppv = temppv(:,1)&temppv(:,2);
                tempsst = ~isnan(outputdataplot{2,2}(:,[1 2]));
                idkeepsst = tempsst(:,1)&tempsst(:,2);
                datpvkeep = outputdataplot{2,1}(idkeeppv,[1 2]);
                datsstkeep = outputdataplot{2,2}(idkeepsst,[1 2]);
                boxplot(datpvkeep,'Widths',0.5,'Colors',colpvsst{1}(1,:),'Symbol','','Positions',[0.6 2.4])
                hold on
                boxplot(datsstkeep,'Widths',0.5,'Colors',colpvsst{2}(1,:),'Symbol','','Positions',[3.6 5.4])
                for k=1:size(datpvkeep,1)
                    plot([2 1], [datpvkeep(k,2) datpvkeep(k,1)],'Color',colpvsst{1}(1,:))
                end
                for k=1:size(datsstkeep,1)
                    plot([5 4], [datsstkeep(k,2) datsstkeep(k,1)],'Color',colpvsst{2}(1,:))
                end
                plot([2.4 0.6], [mean(datpvkeep(:,2)) mean(datpvkeep(:,1))],'o','Color',colpvsst{1}(1,:),'MarkerFaceColor',colpvsst{1}(1,:),'MarkerSize',8)
                plot([5.4 3.6], [mean(datsstkeep(:,2)) mean(datsstkeep(:,1))],'o','Color',colpvsst{2}(1,:),'MarkerFaceColor',colpvsst{2}(1,:),'Markersize',8)
                xlim([0 6])
                text(0.18,0.93,[ 'p=' num2str(signrank(datpvkeep(:,1),datpvkeep(:,2)))],'Units','normalized')
                text(0.68,0.93,['p=' num2str(signrank(datsstkeep(:,1),datsstkeep(:,2)))],'Units','normalized')
                ttpv = datpvkeep(:,2);
                ttsst = datsstkeep(:,2);
                text(0.22,0.85,['n=' num2str(numel(ttpv(~isnan(ttpv))))],'Units','normalized')
                text(0.72,0.85,['n=' num2str(numel(ttsst(~isnan(ttsst))))],'Units','normalized')
                if(i==1)
                    ylim([-68 -43])
                    title('Mean Vm')
                end
                if(i==2)
                    ylim([2 8])
                    title('SD Vm')
                end
                if(i==4)
                    ylim([0 16])
                    title('Vm FFT 1-5 Hz amplitude')
                end
                if(i==5)
                    ylim([0 65])
                    title('AP rate')
                end
                if(i==6)
                    ylim([-0.5 1])
                    title('Vm vs LFP cross-correlation')
                end
                if(i==1 || i==2 || i==4)
                    ylabel('mV')
                end
                if(i==5)
                    ylabel('Hz')
                end
                if(i==6)
                    ylabel(' ')
                end
                set(gca,'XTick',[0.6 2.4 3.6 5.4])
                if(l==1)
                    set(gca,'XTickLabel',{'NW','W','NW','W'})
                else
                    set(gca,'XTickLabel',{'H','L','H','L'})
                end
            else
                subplot(3,2,i)
                temppv = cell2mat(cellfun(@(x) sum(isnan(x)),outputdataplot{2,1}(:,[2 1]),'UniformOutput',0));
                idkeeppv = ~(temppv(:,2)-temppv(:,1)~=0);
                tempsst = cell2mat(cellfun(@(x) sum(isnan(x)),outputdataplot{2,2}(:,[2 1]),'UniformOutput',0));
                idkeepsst = ~(tempsst(:,2)-tempsst(:,1)~=0);
                plot(nanmean(cell2mat(outputdataplot{2,1}(idkeeppv,2))),'Color',colpvsst{1}(1,:))
                hold on
                plot(nanmean(cell2mat(outputdataplot{2,1}(idkeeppv,1))),'Color',colpvsst{1}(2,:))
                plot(nanmean(cell2mat(outputdataplot{2,2}(idkeepsst,2))),'Color',colpvsst{2}(1,:))
                plot(nanmean(cell2mat(outputdataplot{2,2}(idkeepsst,1))),'Color',colpvsst{2}(2,:))
                if(l==1)
                    legend('W','NW','W','NW')
                else
                    legend('L','H','L','H')
                end
                xlim([1 40])
                ylim([0 4])
                ylabel('mV/Hz')
                xlabel('Hz')
                set(gca,'XTick',0:10:40)
                set(gca,'XTickLabel',{'0','5','10','15','20'})
                title('Vm FFT amplitude')
            end
            
        end
        suptitleAP(suptitles{l})
        
        %save
        cd(inputdatastruct_path)
        if(exist(fullfile(inputdatastruct_path,'Figures'),'dir')~=7)
            mkdir('Figures')
        end
        cd('Figures')
        fig.PaperUnits = 'centimeters';
        fig.PaperPosition = [0 0 27 15];
        fig.Renderer = 'Painters';
        savefig(fig,['Figure2_SuppFigure3_part' num2str(l)])
        %print(fig,['Figure2_SuppFigure3_part' num2str(l)],'-depsc')
    end
end

%% Figure 3 Supp Figure 1: presynaptic Chronos-expressing cell analysis
if(strcmp(figname,'figure3suppfig1'))
    
    outputdata = PalaPetersen_Analysis('chronos','save_n','ActiveQuiet');
    
    psths = outputdata{2,1};
    ntrials = outputdata{2,3};
    ntrials = num2cell(ntrials);
    psthscounts = cellfun(@(x,y) x*y,psths,ntrials,'UniformOutput',0);
    psthall = mat2cell(nansum(cell2mat(psthscounts),1),1,50*ones(1,size(psths,2)));
    ntrialsall = num2cell(sum(cell2mat(ntrials),1));
    grandpsth = cellfun(@(x,y) x./y,psthall,ntrialsall,'UniformOutput',0);
    
    approb = outputdata{2,2}; % >=1 APs
    approbmin1 = cell2mat(cellfun(@(x) nansum(cell2mat(x(2:3))),approb,'UniformOutput',0));
    
    
    aplat = outputdata{2,4};
    apjitter = outputdata{2,5};
    
    fig = figure;
    
    for i=1:floor(size(grandpsth,2)/2)
        
        subplot(2,6,[6*(i-1)+1 6*(i-1)+2])
        bar(-49:2:49,grandpsth{2*i},1,'EdgeColor',colchronos(2,:),'FaceColor',colchronos(2,:))
        hold on
        bar(-49:2:49,grandpsth{2*i-1},1,'EdgeColor',colchronos(1,:),'FaceColor','none')
        xlim([-5 10])
        set(gca,'ytick',[0 0.5 1])
        ylabel('AP/trial/2 ms bin')
        xlabel('ms')
        legend('Quiet','Active')
        legend('boxoff')
        title('Grand PSTH')
        
        subplot(2,6,6*(i-1)+4)
        bar(2,nanmean(approbmin1(:,2*i-1)),0.6,'EdgeColor',colchronos(1,:),'FaceColor',colchronos(1,:))
        hold on
        errorbar(2,nanmean(approbmin1(:,2*i-1)),nanstd(approbmin1(:,2*i-1)),'.','Color',colchronos(1,:),'LineWidth',2)
        bar(1,nanmean(approbmin1(:,2*i)),0.6,'EdgeColor',colchronos(2,:),'FaceColor',colchronos(2,:))
        errorbar(1,nanmean(approbmin1(:,2*i)),nanstd(approbmin1(:,2*i)),'.','Color',colchronos(2,:),'LineWidth',2)
        idnan = isnan(approbmin1(:,2*i-1)) | isnan(approbmin1(:,2*i));
        pval = signrank(approbmin1(~idnan,2*i),approbmin1(~idnan,2*i-1));
        text(0.4,0.9,[ 'p=' num2str(pval)],'Units','normalized')
        xlim([0 3])
        ylim([0 1.5])
        set(gca,'ytick',[0 0.5 1])
        set(gca,'xtick',[1 2])
        set(gca,'xticklabel',{'Quiet','Active'})
        title('AP Prob')
        
        subplot(2,6,[6*(i-1)+5 6*(i-1)+6])
        bar(2,nanmean(aplat(:,2*i-1)),0.6,'EdgeColor',colchronos(1,:),'FaceColor',colchronos(1,:))
        hold on
        errorbar(2,nanmean(aplat(:,2*i-1)),nanstd(aplat(:,2*i-1)),'.','Color',colchronos(1,:),'LineWidth',2)
        bar(1,nanmean(aplat(:,2*i)),0.6,'EdgeColor',colchronos(2,:),'FaceColor',colchronos(2,:))
        errorbar(1,nanmean(aplat(:,2*i)),nanstd(aplat(:,2*i)),'.','Color',colchronos(2,:),'LineWidth',2)
        idnan = isnan(aplat(:,2*i-1)) | isnan(aplat(:,2*i));
        pval = signrank(aplat(~idnan,2*i),aplat(~idnan,2*i-1));
        text(0.2,0.9,[ 'p=' num2str(pval)],'Units','normalized')
        bar(5,nanmean(apjitter(:,2*i-1)),0.6,'EdgeColor',colchronos(1,:),'FaceColor',colchronos(1,:))
        errorbar(5,nanmean(apjitter(:,2*i-1)),nanstd(apjitter(:,2*i-1)),'.','Color',colchronos(1,:),'LineWidth',2)
        bar(4,nanmean(apjitter(:,2*i)),0.6,'EdgeColor',colchronos(2,:),'FaceColor',colchronos(2,:))
        errorbar(4,nanmean(apjitter(:,2*i)),nanstd(apjitter(:,2*i)),'.','Color',colchronos(2,:),'LineWidth',2)
        idnan = isnan(apjitter(:,2*i-1)) | isnan(apjitter(:,2*i));
        pval = signrank(apjitter(~idnan,2*i),apjitter(~idnan,2*i-1));
        text(0.7,0.9,[ 'p=' num2str(pval)],'Units','normalized')
        xlim([0 6])
        ylim([0 2])
        ylabel('ms')
        title('Latency                    Jitter')
        set(gca,'xtick',[1 2 4 5])
        set(gca,'xticklabel',{'Quiet','Active','Quiet','Active'})
    end    
    suptitleAP(['Chronos (n=' num2str(size(psths,1)) ' cells)'])
    
    %save
    cd(inputdatastruct_path)
    if(exist(fullfile(inputdatastruct_path,'Figures'),'dir')~=7)
        mkdir('Figures')
    end
    cd('Figures')
    fig.PaperUnits = 'centimeters';
    fig.PaperPosition = [0 0 27 15];
    fig.Renderer = 'Painters';
    savefig(fig,'Figure3_SuppFigure1')
    %print(fig,'Figure3_SuppFigure1','-depsc')
        
end

%% Figure 4 Supp Figure 1: uEPSP kinetics, PV and Sst cells
if(strcmp(figname,'figure4suppfig1'))

    [outputdata]=PalaPetersen_Analysis('uEPSP','save_n','ActiveQuiet');
    
    fig = figure;
    for i=1:2 % uEPSP rise-time, uEPSP latency
            subplot(2,2,3-i); % no state sorting, compare PV vs Sst
            for k=1:2 % PV, Sst
                outputdataplot = outputdata{2,7+i}{2,k}(:,3);
                boxplot(outputdataplot,'Widths',0.5,'Colors',colpvsst{k}(1,:),'Symbol','','Positions',k)
                hold on
                plot(k,mean(outputdataplot),'o','Color',colpvsst{k}(1,:),'MarkerFaceColor',colpvsst{k}(1,:),'MarkerSize',8)
                for l=1:length(outputdataplot)
                    plot(k+0.4,outputdataplot(l),'o','Color',colpvsst{k}(1,:),'MarkerSize',8)
                end                             
            end
            xlim([0 3])
            set(gca,'XTick',[1 2])
            set(gca,'XTickLabel',{'PV','Sst'})
            if(i==1)
                ylim([1 3.5])
                ylabel('ms')
                title('uEPSP latency')
            end
            if(i==2)
                ylim([0 2])
                ylabel('ms')
                title('uEPSP rise-time')
            end
            text(0.4,0.95,[ 'p=' num2str(ranksum(outputdata{2,7+i}{2,1}(:,3),outputdata{2,7+i}{2,2}(:,3)))],'Units','normalized')
    end
    
    %save
    cd(inputdatastruct_path)
    if(exist(fullfile(inputdatastruct_path,'Figures'),'dir')~=7)
        mkdir('Figures')
    end
    cd('Figures')
    fig.PaperUnits = 'centimeters';
    fig.PaperPosition = [0 0 27 15];
    fig.Renderer = 'Painters';
    savefig(fig,'Figure4_SuppFigure1')
    %print(fig,'Figure4_SuppFigure1','-depsc')
end

end