clear all;
load ('R_W.mat');
load ('RAW.mat');

%get parameters
BinBase=R_W.Param.BinBase;
BinDura=R_W.Param.BinDura;
bins=R_W.Param.bins;
binint=R_W.Param.binint;
binstart=R_W.Param.binstart;
PStatBins=0.01; %using more stringent cutoff to reduce pre-delivery noise

%which bins bound the area examined for reward-selectivity? (in seconds)
Time1=0.4; %seconds
Time2=3; %seconds
Bin1=(((Time1-BinDura(2)/2)-binstart)/binint); %convert to bin name
Bin2=(((Time2-BinDura(2)/2)-binstart)/binint); %convert to bin name

%sorting bin -- which bin the neurons' activity is sorted on for heatmap(in seconds)
SortBinTime=1; %seconds
SortBin=round((((SortBinTime-BinDura(2)/2)-binstart)/binint)); %convert to bin name

sucrose=[1  0.6  0.1];
maltodextrin=[.9  0.3  .9];
water=[0.00  0.75  0.75];
total=[0.3  0.1  0.8];
exc=[0 113/255 188/255];
inh=[240/255 0 50/255];

%% bins analysis

%first and last bin aren't included because you can't compare to the previous/subsequent bin
%this axis plots the bins on their centers
xaxis=linspace(binstart+binint+BinDura(2)/2,binstart+(bins-2)*binint+BinDura(2)/2,bins-2);

for i=2:(bins-1) %no including first or last bin because can't compare to previous/subsequent bin
    
    %finds out whether firing is stronger (high excitation or lower inhibition) for 1 or 2
    for k=1:length(R_W.Ninfo) %runs through neurons
        if R_W.BinStatRwrd{i,1}(k).IntSig < PStatBins %if neuron is significant for this bin
            if R_W.BinStatRwrd{i-1,1}(k).IntSig < PStatBins || R_W.BinStatRwrd{i+1,1}(k).IntSig < PStatBins %either previous or subsequent bin must be significant
                if R_W.BinStatRwrd{i,1}(k).R1Mean > R_W.BinStatRwrd{i,1}(k).R2Mean %if firing is greater on sucrose trials than maltodextrin
                    R_W.BinRewPref{i,1}(k,1)=1;
                else
                    R_W.BinRewPref{i,1}(k,1)=2; %otherwise maltodextrin must be greater than sucrose
                end
            else
                R_W.BinRewPref{i,1}(k,1)=0; %if not significant in 2 consecutive bins
            end
        else
            R_W.BinRewPref{i,1}(k,1)=0; %if no sig reward modulation
        end
        
    end
    %find how many NAc neurons have significant reward modulation in each bin
    NN1perBin(i,1)=sum(R_W.BinRewPref{i,1}(:,1)==1); %sucrose pref
    NN2perBin(i,1)=sum(R_W.BinRewPref{i,1}(:,1)==2); %malto pref
    NNperBin(i,1)=sum(R_W.BinRewPref{i,1}(:,1)>0); %either
    %normalize to number of neurons in population
    NN1norm=NN1perBin./sum(length(R_W.Ninfo));
    NN2norm=NN2perBin./sum(length(R_W.Ninfo));
    NNnorm=NNperBin./sum(length(R_W.Ninfo));
   

end

%Cumulative reward selectivity
cumsel=zeros(length(R_W.Ninfo),bins); %set up result matrix
cumsel1=zeros(length(R_W.Ninfo),bins); %set up result matrix for sucrose
cumsel2=zeros(length(R_W.Ninfo),bins); %set up result matrix for maltodextrin
%note, this has to be corrected to +1 because of the way the bin matrix is
%layed out (bin 0 is the first column, not the 0th column)
for i=1:length(R_W.Ninfo) %go through each neuron
    for j=2:bins-1 %look in each bin we did analysis on
        if R_W.BinRewPref{j,1}(i,1)>0 || cumsel(i,j-1)==1
            cumsel(i,j) = 1;
        end
        if R_W.BinRewPref{j,1}(i,1)==1 || cumsel1(i,j-1)==1
            cumsel1(i,j) = 1;
        end
        if R_W.BinRewPref{j,1}(i,1)==2 || cumsel2(i,j-1)==1
            cumsel2(i,j) = 1;
        end        
    end
end

%plotting number of significantly modulated neurons across time
subplot(3,2,2);
hold on;
plot(xaxis,NNnorm(2:bins-1),'Color', total,'linewidth',1.5);
plot(xaxis,NN1norm(2:bins-1),'Color',water,'linewidth',1.5);
plot(xaxis,NN2norm(2:bins-1),'Color',maltodextrin,'linewidth',1.5);
plot([Time1 Time1],[-1 1],':','color','k','linewidth',0.75);
plot([Time2 Time2],[-1 1],':','color','k','linewidth',0.75);
axis([xaxis(1) xaxis(end) 0 0.7]);
legend('Total','Wat > mal','Mal > wat','Location','northeast')
ylabel('Fraction of population');
title('Reward-selective neurons');
xlabel('Seconds from RD');



%% plotting maltodextrin-selective neurons

%color map
[magma,inferno,plasma,viridis]=colormaps;
colormap(plasma);
c=[-100 2000];ClimE=sign(c).*abs(c).^(1/4);%colormap

%events we're looking at
ev1=strcmp('RD1', R_W.Erefnames);
ev2=strcmp('RD2', R_W.Erefnames);

%setting up parameters
Xaxis=[-2 5];
inttime=find(R_W.Param.Tm>=Xaxis(1) & R_W.Param.Tm<=Xaxis(2));
paramtime=R_W.Param.Tm(inttime);

%find all neurons with greater firing for maltodextrin
for i = 1:(Bin2-Bin1+1)
    %the added +1 is necessary because bin 20 is the 21st entry in the matrix
    Pref1(:,i)=R_W.BinRewPref{Bin1+i}==2; %get neurons that have greater firing for water in any of the bins bounded above
    Resp11(:,i)=Pref1(:,i)&cat(1,R_W.BinStatRwrd{Bin1+i,1}.WatRespDir)==-1; %get neurons with inhibition to water
    Resp12(:,i)=Pref1(:,i)&cat(1,R_W.BinStatRwrd{Bin1+i,1}.MalRespDir)==1;%get neurons with excitation to maltodextrin
end

Mel=sum(Pref1,2)>0;  %all neurons selective for mal in any bin
Mel2=sum(Resp11,2)>0; %all selective neurons water inhibited in any bin
Mel3=sum(Resp12,2)>0; %all selective neurons malto excited in any bin

subplot(9,40,[(15:23)+120 (15:23)+160]); %heatmap of maltodextrin preferring neurons' response to water
Neurons=R_W.Ev(ev1).PSTHz(Mel,inttime); %get the firing rates of neurons of interest
MalResp=cat(1,R_W.BinStatRwrd{SortBin+1,1}.R2Mean); %water responses
TMP=MalResp(Mel); %find the magnitude of the excitations for water for this bin
TMP(isnan(TMP))=0; %To place the neurons with no onset/duration/peak at the top of the color-coded map
[~,SORTimg]=sort(TMP);
Neurons=Neurons(SORTimg,:); %sort the neurons by magnitude
imagesc(paramtime,[1,sum(Mel,1)],Neurons,ClimE);
title(['Water trials']);
ylabel('Individual neurons');
hold on;
plot([0 0],[0 sum(Mel)],':','color','k','linewidth',0.75);

subplot(9,40,[(27:35)+120 (27:35)+160]); %heatmap of maltodextrin preferring neurons' response to maltodextrin
Neurons=R_W.Ev(ev2).PSTHz(Mel,inttime); %get the firing rates of neurons of interest
Neurons=Neurons(SORTimg,:); %sort the neurons same as before
imagesc(paramtime,[1,sum(Mel,1)],Neurons,ClimE);
title(['Maltodextrin trials']);
xlabel('Seconds from RD');
hold on;
plot([0 0],[0 sum(Mel)],':','color','k','linewidth',0.75);

%plot water preferring neurons to water
psth1=nanmean(R_W.Ev(ev1).PSTHz(Mel,inttime),1); 
sem1=nanste(R_W.Ev(ev1).PSTHz(Mel,inttime),1); %calculate standard error of the mean
up1=psth1+sem1;
down1=psth1-sem1;

%plot water preferring neurons to malt
psth2=nanmean(R_W.Ev(ev2).PSTHz(Mel,inttime),1); 
sem2=nanste(R_W.Ev(ev2).PSTHz(Mel,inttime),1); %calculate standard error of the mean
up2=psth2+sem2;
down2=psth2-sem2;

%plotting
subplot(9,3,[10 13]);
title(['Mal>wat (n=' num2str(sum(Mel)) ' of ' num2str(length(Mel)) ')'])
hold on;
plot(paramtime,psth1,'Color',water,'linewidth',1);
plot(paramtime,psth2,'Color',maltodextrin,'linewidth',1);
patch([paramtime,paramtime(end:-1:1)],[up1,down1(end:-1:1)],water,'EdgeColor','none');alpha(0.5);
patch([paramtime,paramtime(end:-1:1)],[up2,down2(end:-1:1)],maltodextrin,'EdgeColor','none');alpha(0.5);
plot([-2 5],[0 0],':','color','k','linewidth',0.75);
plot([0 0],[-2 10],':','color','k','linewidth',0.75);
axis([-2 5 -1.5 3.5]);
ylabel('Mean firing (z-score)');
legend('Wat trials','Mal trials');
xlabel('Seconds from RD');


%display inhibitions and excitations
both = sum(Mel2&Mel3);
excite = sum(Mel3)-both;
inhib = sum(Mel2)-both;

subplot(9,40,[160 200]);
b = bar([inhib both excite; 0 0 0],'stacked');
b(1,1).FaceColor=water;
b(1,2).FaceColor=total;
b(1,3).FaceColor=maltodextrin;
axis([1 1.2 0 both+excite+inhib]);
ylabel('Inh / Both / Excited');
set(gca,'xtick',[])


%% emergence of maltodextrin and water responses

%select which time point we're examining
Window=[0.8 1.8]; %For looking at emergence of excitation
NN=0; %neuron counter
Sess=0; %session counter

%plotting
sucrose=[1  0.6  0.1];
maltodextrin=[.9  0.3  .9];
water=[0.00  0.75  0.75];
total=[0.3  0.1  0.8];
exc=[0 113/255 188/255];
inh=[240/255 0 50/255];

%get firing rates on each trial
for i=1:length(RAW) %loops through sessions
    if strcmp('WA',RAW(i).Type(1:2))
        Sess=Sess+1; %session counter
        SN{Sess}=0; %selective neuron counter
        ev1=strmatch('RD1',RAW(i).Einfo(:,2),'exact');
        ev2=strmatch('RD2',RAW(i).Einfo(:,2),'exact');
        for j= 1:size(RAW(i).Nrast,1) %Number of neurons within sessions
            NN=NN+1;
            if Mel(NN)==1
                
                SN{Sess}=SN{Sess}+1;
                Bcell1=0;
                Bcell2=0;
                Bcell=0;
                ev1spk=0;
                Ev2spk=0;

                %get mean baseline firing for all reward trials
                [Bcell1,B1n]=MakePSR04(RAW(i).Nrast(j),RAW(i).Erast{ev1},BinBase,{2});% makes trial by trial rasters for baseline
                for y= 1:B1n
                    Bcell(1,y)=sum(Bcell1{1,y}>BinBase(1));
                end
                [Bcell2,B2n]=MakePSR04(RAW(i).Nrast(j),RAW(i).Erast{ev2},BinBase,{2});% makes trial by trial rasters for baseline
                for z= 1:B2n
                    Bcell(1,z+B1n)=sum(Bcell2{1,z}>BinBase(1));
                end
                Bhz=Bcell/(BinBase(1,2)-BinBase(1,1));
                Bmean=nanmean(Bhz);
                Bstd=nanstd(Bhz);

                %get trial by trial firing rate for water trials
                [ev1cell,ev1n]=MakePSR04(RAW(i).Nrast(j),RAW(i).Erast{ev1},Window,{2});% makes trial by trial rasters for event
                for y= 1:ev1n
                    ev1spk(SN{Sess},y)=sum(ev1cell{1,y}>Window(1));
                end       
                ev1hz=ev1spk(SN{Sess},:)/(Window(1,2)-Window(1,1));
                for x= 1:ev1n
                    ev1norm{Sess}(SN{Sess},x)=((ev1hz(1,x)-Bmean)/Bstd);
                end

                %get trial by trial firing rate for maltodextrin trials
                [ev2cell,ev2n]=MakePSR04(RAW(i).Nrast(j),RAW(i).Erast{ev2},Window,{2});% makes trial by trial rasters for event
                for y= 1:ev2n
                    ev2spk(1,y)=sum(ev2cell{1,y}>Window(1));
                end       
                ev2hz=ev2spk/(Window(1,2)-Window(1,1));
                for x= 1:ev2n
                    ev2norm{Sess}(SN{Sess},x)=((ev2hz(1,x)-Bmean)/Bstd);
                end
            end
        end %neurons in each session
        
        trialmeanz1{Sess}=NaN(2,1);
        trialmeanz2{Sess}=NaN(2,1);
        ind=0;
        order=0;

        [~,ind]=sort(cat(1,RAW(i).Erast{ev1},RAW(i).Erast{ev2}));
        for j=1:length(ind)
            order(j,1)=find(ind==j);
        end
        xaxis1{Sess}=order(1:length(ev1norm{Sess}(1,:)));
        xaxis2{Sess}=order(1+length(ev1norm{Sess}(1,:)):end);

        for k=1:length(ev1norm{Sess}(1,:))
            trialmeanz1{Sess}(1,k)=nanmean(ev1norm{Sess}(:,k));
            trialmeanz1{Sess}(2,k)=nanste(ev1norm{Sess}(:,k),1);
        end

        for k=1:length(ev2norm{Sess}(1,:))
            trialmeanz2{Sess}(1,k)=nanmean(ev2norm{Sess}(:,k));
            trialmeanz2{Sess}(2,k)=nanste(ev2norm{Sess}(:,k),1);
        end
        
        %stats checking for interaction between # of reward presentations
        %and reward on firing rate
        numtrials=min([length(xaxis1{Sess}) length(xaxis2{Sess})]); %number of trials for stats (fewest number of trials for the 2 outcomes)
        trials1=repmat(1:numtrials,length(ev1norm{Sess}(:,1)),1);
        trials2=repmat(1:numtrials,length(ev2norm{Sess}(:,1)),1);
        reward1=zeros(size(trials1));
        reward2=ones(size(trials2));
        data1=ev1norm{Sess}(:,1:numtrials);
        data2=ev2norm{Sess}(:,1:numtrials);

        [~,R_W.EmergenceStats{Sess,1},R_W.EmergenceStats{Sess,2}]=anovan(cat(1,data1(:),data2(:)),{cat(1,trials1(:),trials2(:)),cat(1,reward1(:),reward2(:))},'varnames',{'trials','reward'},'display','off','model','full');

     end %checking if a water session
     
     
    
end %session

%plotting
for i=1:Sess
    subplot(3,2,4+i);
    hold on;
    errorbar(xaxis1{i},trialmeanz1{i}(1,:),trialmeanz1{i}(2,:),'*','Color',water,'linewidth',1.5);
    errorbar(xaxis2{i},trialmeanz2{i}(1,:),trialmeanz2{i}(2,:),'*','Color',maltodextrin,'linewidth',1.5);
    %plot(xaxis1,(cell2mat(ev1stat{i}(1,:))*13-16.9),'*','Color',water); %(12.5-trialmeanz242(1,1:trials1)-trialmeanz242(2,1:trials1))
    %plot(xaxis2,(cell2mat(ev2stat{i}(1,:))*13-16.7),'*','Color',maltodextrin); %(12.5-trialmeanz242(1,1:trials1)-trialmeanz242(2,1:trials1))
    %plot(xaxis1,(cell2mat(trialstat42(1,1:trials1))*13-17.1),'*','Color','k'); %(12.5-trialmeanz242(1,1:trials1)-trialmeanz242(2,1:trials1))
    plot([0 60],[0 0],':','color','k','linewidth',0.75);
    ylabel(['Mean firing ' num2str(Window(1,1)) '-' num2str(Window(1,2)) 's (z-score)']);
    title(['Rat ' num2str(i) ' (n=' num2str(SN{i}) ')']);
    axis([1 max([xaxis1{i};xaxis2{i}]) min(trialmeanz1{i}(1,:))*1.3 max(trialmeanz2{i}(1,:))*1.3]);
    xlabel('Trial #');
    legend('Wat','Mal','location','northwest');

end


%% conduct lick analysis
global Dura Tm BSIZE Tbin
path='C:\Users\dottenh2\Documents\MATLAB\David\2Rewards Nex Files\2RLick_paper.xls';

%Main settings
BSIZE=0.01; %Do not change
Dura=[-22 20]; Tm=Dura(1):BSIZE:Dura(2);
Tbin=-0.5:0.005:0.5; %window used to determine the optimal binsize
MinNumTrials=5;
Lick=[];Lick.Ninfo={};LL=0;Nlick=0;

%Smoothing
Smoothing=1; %0 for raw and 1 for smoothing
SmoothTYPE='lowess'; %can change this between lowess and rlowess (more robust, ignores outliers more)
SmoothSPAN=50; %percentage of total data points
if Smoothing~=1, SmoothTYPE='NoSmoothing';SmoothSPAN=NaN; end

% List of events to analyze and analysis windows EXTRACTED from excel file
[~,Erefnames]=xlsread(path,'Windows','a3:a10'); % cell that contains the event names

%Finds the total number of sessions
for i=1:length(RAW)
    if strcmp('WA',RAW(i).Type(1:2))
        Nlick=Nlick+1;
        Lick.Linfo(i,1)=RAW(i).Ninfo(1,1);
    end
end
Lick.Erefnames= Erefnames;

%preallocating the result matrix
for k=1:length(Erefnames)
    Lick.Ev(k).PSTHraw(1:Nlick,1:length(Tm))=NaN(Nlick,length(Tm));
    Lick.Ev(k).BW(1:Nlick,1)=NaN;
    Lick.Ev(k).NumberTrials(1:Nlick,1)=NaN;
end

for i=1:length(RAW) %loops through sessions
    if strcmp('WA',RAW(i).Type(1:2))
        LL=LL+1; %lick session counter
        for k=1:length(Erefnames) %loops thorough the events
            EvInd=strcmp(Erefnames(k),RAW(i).Einfo(:,2)); %find the event id number from RAW
            LickInd=strcmp('Licks',RAW(i).Einfo(:,2)); %find the event id number from RAW
            if sum(EvInd)==0
                fprintf('HOWDY, CANT FIND EVENTS FOR ''%s''\n',Erefnames{k});
            end

            Lick.Ev(k).NumberTrials(LL,1)=length(RAW(i).Erast{EvInd});
            if  ~isempty(EvInd) && Lick.Ev(k).NumberTrials(LL,1)>MinNumTrials %avoid analyzing sessions where that do not have enough trials
                [PSR1,N1]=MakePSR04(RAW(i).Erast(LickInd),RAW(i).Erast{EvInd},Dura,{1});% makes collpased rasters. PSR1 is a cell(neurons)
                if ~isempty(PSR1{1}) %to avoid errors, added on 12/28 2011
                    %forcing 100ms bin size to keep it consistent across
                    %sessions (no reason is should be different for licks)
                    [PTH1,BW1,~]=MakePTH07(PSR1,repmat(N1, size(RAW(i).Erast{LickInd},1),1),{2,0,0.1});%these values force bin size to be 100ms
                    PTH1=smooth(PTH1,SmoothSPAN,SmoothTYPE)';

                    %------------- Fills the R.Ev(k) fields --------------
                    Lick.Ev(k).BW(LL,1)=BW1;
                    Lick.Ev(k).PSTHraw(LL,1:length(Tm))=PTH1;
                end
            end
        end
    end
end

Xaxis=[-2 12];
Ishow=find(Tm>=Xaxis(1) & Tm<=Xaxis(2));
time1=Tm(Ishow);
c=[-1000 7500];ClimE=sign(c).*abs(c).^(1/4);%ColorMapExc
colormap(jet);
sucrose=[1  0.6  0.1];
maltodextrin=[.9  0.3  .9];
water=[0.00  0.75  0.75];
total=[0.3  0.1  0.8];
exc=[0 113/255 188/255];
inh=[240/255 0 50/255];

Ev1=strcmp('RD1', Lick.Erefnames);
Ev2=strcmp('RD2', Lick.Erefnames);

psth1=nanmean(Lick.Ev(Ev1).PSTHraw(:,Ishow),1);
sem1=nanste(Lick.Ev(Ev1).PSTHraw(:,Ishow),1); %calculate standard error of the mean
up1=psth1+sem1;
down1=psth1-sem1;

psthE=nanmean(Lick.Ev(Ev2).PSTHraw(:,Ishow),1);
semE=nanste(Lick.Ev(Ev2).PSTHraw(:,Ishow),1); %calculate standard error of the mean
upE=psthE+semE;
downE=psthE-semE;

%plotting
subplot(3,2,1);
hold on;
plot(time1,psth1,'Color',water,'linewidth',1);
plot(time1,psthE,'Color',maltodextrin,'linewidth',1);
patch([time1,time1(end:-1:1)],[up1,down1(end:-1:1)],water,'EdgeColor','none');alpha(0.5);
patch([time1,time1(end:-1:1)],[upE,downE(end:-1:1)],maltodextrin,'EdgeColor','none');alpha(0.5);
title('Mean lick rate');
%plot([-2 10],[0 0],':','color','k');
plot([0 0],[-2 8],':','color','k','linewidth',0.75);
axis([-2 12 0 7.5]);
xlabel('Seconds from reward delivery');
ylabel('Licks/s');
legend('Water trials','Maltodextrin trials');
%color map
[magma,inferno,plasma,viridis]=colormaps;
colormap(plasma);
c=[-100 2000];ClimE=sign(c).*abs(c).^(1/4);%colormap

%% creating and saving new variables
R_W.MalN=Mel;

% proportion summary and chi squared test for reward selective neurons in
% sucrose and water sessions in VP

%find all reward-selective neurons
for i = 1:(Bin2-Bin1+1)
    %the added +1 is necessary because bin 20 is the 21st entry in the matrix
    Selective(:,i)=R_W.BinRewPref{Bin1+i}>0; %get neurons that have greater firing for water in any of the bins bounded above
end
WSel=sum(Pref1,2)>0;  %all neurons selective for mal in any bin

%get reward selective neurons from these two rats
load ('R_2R.mat');
selection=(R_2R.SucN | R_2R.MalN); %selective neurons in suc vs mal sessions
SSel=selection(strcmp('VP2',R_2R.Ninfo(:,4)) | strcmp('VP5',R_2R.Ninfo(:,4)),1);

%get proportion and stats
R_W.SucvsWatX2(1,1)=sum(SSel)/length(SSel); %selective neurons in maltodextrin sessions
R_W.SucvsWatX2(1,2)=sum(WSel)/length(WSel); %how many selective neurons in water sessions
[~,R_W.SucvsWatX2(2,1),R_W.SucvsWatX2(2,2)]=crosstab(cat(1,SSel,WSel),cat(1,ones(length(SSel),1),zeros(length(WSel),1))); %find chi squared value for this distribution

save('R_W.mat','R_W');