

set(0, 'DefaultLineLineWidth', 2);
set(0,'defaultTextFontSize', 12);
set(0,'defaultAxesFontSize',12);
set(0,'DefaultFigureColormap',jet)
set(0,'defaultfigurecolor',[1 1 1])
set(0,'DefaultAxesTitleFontWeight', 'normal')
set(0, 'DefaultAxesFontName', 'Arial');
%%
%SleepState_aligned = Sleep_Align('Ach_popRate','LIMP019_004_220303_115500');

%%
clear all;
foldername = 'Dual_recording';
fieldname = 'ACh_OXT004_011_230325';
% Load animal state
sleepfile = dir(sprintf('%s*SleepState*.mat',strcat(foldername,'/',fieldname)));
load(strcat(foldername,'/',sleepfile.name))
% Read OPTOTTL time in sec
popfile = dir(sprintf('%s*popRate*.mat',strcat(foldername,'/',fieldname)));
load(strcat(foldername,'/',popfile.name))

N = round(lfp_fbtime/2e2);

popRate_ = popRate(N(1):N(2));
Ach_dFF = Fluo_dF.Ach(1:size(popRate_));
Oxt_dFF = Fluo_dF.Oxt(1:size(popRate_));

%%
fig1 = figure();
set(gcf,'Position',[100 100 700 500])
fs = 100;
t = (0:1:size(popRate_)-1)/fs;
wbnd = 8e4:10e4;
tl= tiledlayout(2,1);
nexttile(2)
plot(t(wbnd),zscore(Oxt_dFF(wbnd))+2,'Color',[0 120 0]./255)
hold on
plot(t(wbnd),zscore(Ach_dFF(wbnd))-2,'Color',[255 0 0]./255)
xlim([min(wbnd)/fs, max(wbnd)/fs])
ylim([-5,5])
legend('Ach', 'Oxt')
ylabel('zscored')
xlabel('Time (s)')
box off
nexttile(1)
plot(t(wbnd),smoothdata(popRate_(wbnd),'sgolay',5e2),'Color',[0 0 0]./255)
xlim([min(wbnd)/fs, max(wbnd)/fs])
ylabel('Firing rate (Hz)')
box off
tl.TileSpacing = 'compact';
exportgraphics(fig1,'Fig2E_MUA_Ach_Oxt.pdf','BackgroundColor','none','ContentType','vector')


%%
wbnd = 690e2:1390e2;
window_size = 5e3;
[pxx,f] = pwelch(zscore(Oxt_dFF(wbnd)),window_size,window_size/2,5e3,fs);

semilogx(f,pxx)

xlabel('Frequency (Hz)')
ylabel('PSD (dB/Hz)')
hold on
[pxx,f] = pwelch(zscore(Ach_dFF(wbnd)),window_size,window_size/2,5e3,fs);
semilogx(f,pxx)

%%
popRate_smooth = smoothdata(popRate_,'sgolay',5e2);
[pxy,f] = cpsd(zscore(Ach_dFF(wbnd)),zscore(popRate_smooth(wbnd)),window_size,window_size/2,5e3,fs);
plot(f,pxy)
xlim([0 0.5])

%%
[c, lags] = xcorr(zscore(Oxt_dFF(wbnd)),zscore(popRate_smooth(wbnd)),fs*40,'normalized');
figure
set(gcf,'Position',[100 100 400 250])
plot(lags/fs,c,Color=[0 0.5 0])
hold on
[c, lags] = xcorr(zscore(Ach_dFF(wbnd)),zscore(popRate_smooth(wbnd)),fs*40,'normalized');
plot(lags/fs,c,Color=[1 0 0])
xline(0,'--k')
box off
%ylim([-0.4,0])
xlim([-20,20])