clear all;close all;

dataname = ['F:\oxytocin\ACh_OXT004\ACh_OXT004_008_230306_174435', %% good ach and good CA1  optitrack         
           'F:\oxytocin\ACh_OXT004\ACh_OXT004_009_230309_113459', %% good ach need pick 10s stimulation optitrack   
           'F:\oxytocin\ACh_OXT005\ACh_OXT005_006_230309_151131', %% good ach need pick 10s stimulation optitrack   
           'F:\oxytocin\ACh_OXT006\ACh_OXT006_006_230311_181030', %% good ach need pick 10s stimulation optitrack   
           'F:\oxytocin\ACh_OXT007\ACh_OXT007_006_230310_154051'] %% good ach need pick 10s stimulation optitrack   

%% inhibtion on ACh signal
for ii =2:size(dataname,1)
    cd(dataname(ii,:))
    basepath = pwd;
    basename = bz_BasenameFromBasepath(basepath);
    load([basename,'.SleepState.states.mat']);
    load([basename,'.pulses.events.mat'])
    
    
    % sitmulation and signal
    info = read_Intan_RHD2000_file(basepath);
    digitalin = read_Intan_digitalin_file('digitalin.dat',info.num_board_dig_in_channels)';
    lfp_fbtime = find(digitalin(1,:)>(max(digitalin)+min(digitalin))/2,1);
    delete digitalin
    % sitmulation and signal
    if exist([basename,'_Fluo.mat'])==0
        FluoData = Get_OxtAch_Fluos();
        figure
        plot(FluoData.time,FluoData.Ach_dFF); hold on;
        plot(FluoData.time,FluoData.Oxt_dFF);xlim([0 inf]);
    else load([basename,'_Fluo.mat']);plot(FluoData.Ach_dFF);
    end

    %% get peri_sti signal
    ACh_Opto = [];
    pulse = pulses.intsPeriods-lfp_fbtime(1)/info.sample_rate;
    pulses.duration = pulses.intsPeriods(:,2) - pulses.intsPeriods(:,1);
    pulse = pulse(pulses.duration>4 & pulses.duration<6);
    for jj = 1:length(pulse)
        win = round(pulse(jj,1)*100) + [-10 40]*100;
        if win(1>0) & win(2)<length(FluoData.Ach_dFF)
            ACh_Opto(jj,:) = FluoData.Ach_dFF(win(1):win(2));
             ACh_Opto(jj,995:1015) = nan;
             ACh_Opto(jj,1995:2015) = nan;
            ACh_Opto(jj,:) = fillmissing(ACh_Opto(jj,:),'linear');
        end
    end
    figure;
    options.color_area = [128 193 219]./255;    % Blue theme
    options.color_line = [ 52 148 186]./255;
    options.alpha      = 0.5;
    options.line_width = 2;
    options.error      = 'sem';
    plot_areaerrorbar(ACh_Opto, options);set(gcf,'Position',  [100, 100, 400, 300])
    xlim([1 5000]);
%% divide by behavior
    datpath = 'G:\My Drive\Paper_ACh_OXT\Fig5\Figure 5C\ACh_activation\ACh_activation_signal';
    save(fullfile(datpath,[basename,'ACh_peri_Act.mat']),'ACh_Opto');
end
