%get average CSD of classified DSL and DSM events
%requires CSD Plotter https://github.com/espenhgn/CSDplotter
%2021 Dino Dvorak, New York University, neuraldino@gmail.com
%Dentate spikes and external control of hippocampal function,
%Cell Reports, Volume 36, Issue 5, 2021,109497,ISSN 2211-1247,
%https://doi.org/10.1016/j.celrep.2021.109497

clear; close all; clc;

addpath(genpath('/Users/dino/DATA/matlab/CSDplotter'));

%directories
drTYPE = 'DS_TYPE12/';
%drDS = 'DS/';
drMAT = 'MAT_EEG/';

%input LFP file (channels x samples)
fnEEG = '2016_09_30_PP12_334_PRETRAIN_BASE_eeg.mat';

%CSD
h = 50e-6; %electrode distance m
ex_cond = 0.3; %external conductivity S/m
top_cond = 0.3; %S/m
diam = 0.5e-3; %mm
gauss_sigma = 0.05e-3; %mm
filter_range = 5*gauss_sigma; % numeric filter must be finite in extent
dt = 0.5; %sampling time ms (for 2k);
scale_plot = 1; %focus
max_plot = 0;
CSDres = 200;
methodSpline = 1;

%create filter for detection
eegFS = 2000;
[b, gd] = getFIRbandpass( 5,100,4,40,eegFS );

winLenHalf = 0.05*eegFS; %window around DS

Nmax = 1000; %max number of DS events to average

load([drMAT fnEEG]);
load([drTYPE fnEEG]);

Nchannels = size(eegData,1);

if Nchannels == 32
    el_pos = 0.1:0.05:1.65; %our tetrode distances
    el_pos = el_pos*1e-3; %mm
elseif Nchannels == 16
    el_pos = 0.1:0.05:0.85; %our tetrode distances
    el_pos = el_pos*1e-3; %mm
end

%filter
eegF = filter(b,1,eegData,[],2);
eegF = cat(2,eegF(:,gd+1:end),zeros(size(eegF,1),gd));

eegData = eegF;

%samples of type1 and type2, superior detection (can be done w inferior as
%well)
samplesDS1 = samplesDS(kType1sup);
samplesDS2 = samplesDS(kType2sup);

figure

for typeI = 1:2

    if typeI == 1
        sDS = samplesDS1;
    else
        sDS = samplesDS2;
    end

    %select Nmax
    if length(sDS) > Nmax
        k = randsample(length(sDS),Nmax);
        sDS = sDS(k);
    end

    resultsCSD = zeros(CSDres,winLenHalf*2+1);
    resultsEEG = zeros(size(eegData,1),winLenHalf*2+1);
    counter = 0;

    for sI = 1:length(sDS)

        s = sDS(sI);

        eeg = eegData(:,s-winLenHalf:s+winLenHalf);

        if methodSpline == 0
            %compute CSD - standard method
            %adding vaknin electrodes not to loose first and last channel
            %duplicate first and last channel
            eeg = cat(1,eeg(1,:),eeg,eeg(end,:));
            eeg = eeg + eeg;

            Nch = size(eeg,1);
            CSD = -ex_cond*D1(Nch,h)*eeeegAvergX;

            %filter iCSD
            b0 = 0.54; %center
            b1 = 0.23; %neighbor
            [n1,n2]=size(CSD);            
            CSD_add(1,:) = zeros(1,n2);   %add top and buttom row with zeros
            CSD_add(n1+2,:)=zeros(1,n2);
            CSD_add(2:n1+1,:)=CSD;        %CSD_add has n1+2 rows
            CSD = S_general(n1+2,b0,b1)*CSD_add; % CSD has n1 row

        else
            % compute spline iCSD:
            Fcs = F_cubic_spline(el_pos,diam,ex_cond,top_cond);
            [zs,CSD_cs] = make_cubic_splines(el_pos,eeg,Fcs);
            if gauss_sigma~=0 %filter iCSD
              [~,CSD_cs]=gaussian_filtering(zs,CSD_cs,gauss_sigma,filter_range);
            end
            CSD = CSD_cs;
        end

        if sum(isnan(CSD(:))) > 0; continue; end;

        resultsCSD = resultsCSD + CSD;
        resultsEEG = resultsEEG + eeg;
        counter = counter + 1;

        %if spline is used, find electrodes
        chs = 1:Nchannels;
        chsInd = zeros(1,length(chs));
        for chI = 1:Nchannels
            [~,k] = min(abs(el_pos(chI) - zs));
            chsInd(chI) = k;
        end

    end

    csd = resultsCSD / counter;
    eeg = resultsEEG / counter;
    
    subplot(1,2,typeI); hold on;
    imagesc(csd,[-5000 5000]);
    axis ij tight
    colormap jet

    %EEG
    scaling = 0.00005;
    for chI = 1:size(eeg,1)
        x = eeg(chI,:);
        x = -1*x; %invert - plot is going to be reversed
        x = x / scaling; %scale for amplitude

        %if spline is used, find electrode where sink/source is present
        [~,k] = min(abs(el_pos(chI) - zs));
        %plot(x + k,'Color',[0.7 0.7 0.7]);
        plot(x + k,'Color',[0.4 0.4 0.4]);
    end

    %middle CSD line
    s = floor(size(csd,2)/2);
    %center line
    plot([s s],[1 size(csd,1)],'k--')

    if typeI == 1
        title('DS_L');
    else
        title('DS_M');
    end
    
    set(gca,'XTick',[1,winLenHalf,winLenHalf*2+1])
    set(gca,'XTickLabel',{'-50','0','50'})
    
    xlabel('Time rel. to DS [ms]')
    
    ylabel('Depth (arbitrary)')
    
            
end
