clear;clc

cd('G:\My Drive\Paper_ACh_OXT\Fig1\Data\Figure1E\ACh_spd\figure 8 maze')
datpath = 'G:\My Drive\Paper_ACh_OXT\Fig1\Data\Figure1E\ACh_spd'
%% get FluoDATA
files = dir('*.mat');
for ii = 1:length(files)
    [filepath,name,ext] = fileparts(files(ii).name);

    load([name,ext],[name,'_OpTrTTL']);
    Opti = eval([name,'_OpTrTTL']);
    Opti.data = downsample(Opti.values,10);
    Opti.time = downsample(Opti.times,10);
    time_st = round(Opti.time(find(Opti.data>1,1))*2e4);time_nd = round(Opti.time(find(Opti.data>1,1,'last'))*2e4);

    % signal
    load([name,ext],[name,'_AChSig1']);
    ACh_signal = eval([name,'_AChSig1']);
    ACh_signal.data = downsample(ACh_signal.values(time_st:time_nd),200);
    ACh_signal.time = downsample(ACh_signal.times(time_st:time_nd),200)- Opti.time(find(Opti.data>1,1));
    
    p = [];
    p = polyfit(ACh_signal.time,ACh_signal.data,2);
    Ybaseline = polyval(p,ACh_signal.time);
    
    figure
    plot(ACh_signal.time, ACh_signal.data); hold on;
    plot(ACh_signal.time,Ybaseline);
    dFoverF = smoothdata((ACh_signal.data - Ybaseline)./Ybaseline,'movmean',10);
    % dfff(:,1) = [1043:3000:731366];
    % dfff(:,2) = dfff(:,1)+60;
    % dFoverF(dfff(1:2,:))= NaN;
    % dFoverF = fillmissing(dFoverF,'linear');
    hold on;
    plot(ACh_signal.time, dFoverF);xlim([0 inf])

    FluoData.time = ACh_signal.time;
    FluoData.Ach_dFF = dFoverF;
    FluoData.Ach_Fluo = ACh_signal.data;
    FluoData.Ach_baseline = Ybaseline;

    save(fullfile(datpath,[name,'_FluoData.mat']),'FluoData');
end


