%% STATISTIC OXYTOCIN BEHAVIRO
clear all; close all;

dataname = ['F:\oxytocin\OXYT010\OXYT010_004_220126_112539',
            'F:\oxytocin\OXYT011\OXYT011_005_220224_160927',
            'F:\oxytocin\OXYT014\OXYT014_001_220429_155806',
            'F:\oxytocin\OXYT012\OXYT012_001_220323_130702',
            ]
RipCh = [23,70,19,44];
for ii = 1:size(dataname,1)
    cd(dataname(ii,:))
    basepath = pwd;
    basename = bz_BasenameFromBasepath(basepath);
    load([basename,'.SleepState.states.mat']);
    
   
    info = read_Intan_RHD2000_file(basepath);
    analogin= read_Intan_analogin_file('analogin.dat',info.num_board_adc_channels);
    lfp_fbtime = find(analogin(1,:)>(max(analogin(1,:))+min(analogin(1,:)))/2,1)
    if isempty(lfp_fbtime) == 1
        lfp_fbtime = [0]
    else lfp_fbtime(1,2) = find(analogin(1,:)>0.6,1,'last');
    end 
    
    % sitmulation and signal
    if exist('dFoverF.mat')==0
        name = basename(1:11);
        ext = '.mat'
        load([name,ext],[name,'_AChSti']);
        ACh_sti = eval([name,'_AChSti']);
        otr = 0.5;
        fbtime = ACh_sti.times(find(ACh_sti.values(:,1)>otr,1));fbtime(1,2) = ACh_sti.times(find(ACh_sti.values(:,1)>otr,1,'last'));
        fbIDX = round(fbtime*20000);
        load([name,ext],[name,'_AChSig1']);
        ACh_signal = eval([name,'_AChSig1']);
        ACh_signal.data = downsample(ACh_signal.values((fbIDX(1,1)):(fbIDX(1,2))),200);
        ACh_signal.time = downsample(ACh_signal.times((fbIDX(1,1)):(fbIDX(1,2))),200)- fbtime(1,1);
        p = [];
        p = polyfit(ACh_signal.time,ACh_signal.data,5);
        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);
        hold on;
        plot(ACh_signal.time, dFoverF);xlim([0 inf]);
    else load('dFoverF.mat'); figure;plot(dFoverF);
    end
    
    %% get RIPPLES
    delete([basename,'.ripples.events.mat']);
    delete([basename,'.EMGFromLFP.LFP.mat']);
    
    RipLFPs = bz_GetLFP(RipCh(ii),'basepath',basepath,'noPrompts',true);
    RipLFPs.data = double(RipLFPs.data);
    RipLFPs.data(abs(RipLFPs.data)>5000) = nan;
    RipLFPs.data = fillmissing(RipLFPs.data,'linear');

    % get accel into 1250hz
    x = [1:length(SleepState.idx.timestamps)];
    xq = [1:1/1250:length(SleepState.idx.states)];
    SLP_time =  interp1(x,SleepState.idx.states,xq);

    RipLFPs.data( SLP_time~=3 ) = 0;

    ripples = bz_FindRipples(RipLFPs.data,RipLFPs.timestamps);
    
   Oxt_ripples = {};
   Oxt_ripples.ripples = ripples;
   Oxt_ripples.dFoverF = dFoverF;
   Oxt_ripples.alignTim = lfp_fbtime;
   Oxt_ripples.lfpData = RipLFPs;

   datpath = 'G:\My Drive\Paper_ACh_OXT\Fig4\Figure 4B';
   save(fullfile(datpath,[basename,'_Oxt_ripples.mat']),'Oxt_ripples');
end
