clear all;close all;

dataname = ['F:\oxytocin\ACh_OXT004\ACh_OXT004_012_230328_141439', %% good ach and good CA1  optitrack         
           'F:\oxytocin\ACh_OXT007\ACh_OXT007_009_230330_104326',
           'F:\oxytocin\ACh_OXT006\ACh_OXT006_006_230311_181030',
           'F:\oxytocin\ACh_OXT004\ACh_OXT004_020_230516_130710',
           'F:\oxytocin\ACh_OXT007\ACh_OXT007_016_230517_114109',
           'F:\oxytocin\ACh_OXT006\ACh_OXT006_013_230517_151258',
           'F:\oxytocin\ACh_OXT007\ACh_OXT007_017_230525_114105'] %% no ach signal but stimulation
RipCh = [58,27,18,62,23,27,23];
%% inhibtion on ACh signal
for ii = 1:size(dataname,1)
    cd(dataname(ii,:))
    basepath = pwd;
    basename = bz_BasenameFromBasepath(basepath);
    load([basename,'.pulses.events.mat']);
    load([basename,'.accel.behavior.mat']);
    load([basename,'.spikes.cellinfo.mat']);
    load([basename,'.cell_metrics.cellinfo.mat']);

    info = read_Intan_RHD2000_file(basepath);
    
    pulse = pulses.intsPeriods;
    pulses.duration = pulses.intsPeriods(:,2) - pulses.intsPeriods(:,1);
    idx = find(pulses.duration>4 & pulses.duration<6);
    pulse = pulse(idx,:)
    %% exclude the move-pulse
  
    pul_NREM = [];
    for jj = 1:length(pulse)
        win = round(pulse(jj,:))+[-5 10];
        pul_in = [];
        if mean(accel.acceleration.motion(win(1):win(2)))<200
            pul_in = pulse(jj,:);
            pul_NREM = [pul_NREM;pul_in];
        end 
    end
   

    if ii == 1;
        pulse = pul_NREM-10;
    else
        pulse = pul_NREM;
    end
    
   binSize = 0.001;
    spkMat = bz_SpktToSpkmat(spikes,'binSize',binSize,'overlap',1);
    types = convertCharsToStrings(cell_metrics.putativeCellType);
    nIntN = find(strcmp(types,'Narrow Interneuron')); % Narrow Interneuron % Pyramidal Cell
    PyN = find(strcmp(types,'Pyramidal Cell')); 
    wIntN = find(strcmp(types,'Wide Interneuron'));

    events = [];
    events = pulse(:,1);
    secondsBefore = 5;secondsAfter = 10;
    binWidth = 0.1;cellnums = nIntN;
    PETHSpikes_nIntN = bz_PETH_Spikes(events,'cellnums',cellnums,'secondsBefore',secondsBefore,'secondsAfter',secondsAfter,'binWidth',binWidth);

    binWidth = 0.1;cellnums =  PyN;
    PETHSpikes_PyN = bz_PETH_Spikes(events,'cellnums',cellnums,'secondsBefore',secondsBefore,'secondsAfter',secondsAfter,'binWidth',binWidth);

    binWidth = 0.1;cellnums =  wIntN;
    PETHSpikes_wIntN = bz_PETH_Spikes(events,'cellnums',cellnums,'secondsBefore',secondsBefore,'secondsAfter',secondsAfter,'binWidth',binWidth);
    
    PETHSpikes.nInN = PETHSpikes_nIntN;
    PETHSpikes.PyN = PETHSpikes_PyN;
    PETHSpikes.wInN = PETHSpikes_wIntN
    datpath = 'G:\My Drive\Papers_Buzsaki\Paper_ACh_OXT\Fig5\Figure 5C\ACh_activation\ACh_activation_spikes';
    save(fullfile(datpath,[basename,'_PETHSpikes.mat']),'PETHSpikes');
end
cd(datpath)