clearvars; close all force; clc;

addpath('C:\Users\Santiago\Ephys Mauthner\Code')
files = dir('C:\Users\Santiago\Ephys Mauthner\Data\**\*.abf');

SR = 25000; %in Hz
ROI = 0.012; %in secs
delayPostTectal = 0.0007; %in secs
tonicDepolarizationShift = 0.004;
tonicDepROIwidth = 0.001;

%For detecting tectal stimulation:
tectalSearchX = 6;%6
tectalSearchY = 3.75;%3.75

d = designfilt('bandstopiir','FilterOrder',2, ...
    'HalfPowerFrequency1', 49, 'HalfPowerFrequency2', 51, ...
    'DesignMethod','butter','SampleRate',SR);

subplot_modality = {'TS','T','S'};


for f = 1:size(files,1) %files
    if and(contains(files(f).folder,'070319Right'),contains(files(f).name,'TS50')) 
        continue
    end

    if ~contains(files(f).name,'TS200') 
        continue
    end

    myFig = figure;
    neuron = strsplit(files(f).folder, '\');
    neuron = neuron{end};
    
    for TS_T_S = 1:3 %Loop through Multimodal (TS_T_S = 1), Tectal (2), or Auditory (3)
        if TS_T_S == 1
            filename = files(f).name; 
        elseif TS_T_S == 2 % Tectal file depends on protocol
                if or(contains(files(f).name,'TS100@'),contains(files(f).name,'TS4'))
                    filename = erase(files(f).name,'S');                    
                elseif contains('TS-50.abf_TS0.abf_TS33.abf_TS100.abf_TS200.abf_TS250.abf',files(f).name)
                    filename = 'T.abf'; 
                else 
                    filename = 'NAN.abf';
                end
        elseif TS_T_S == 3 % Sound file is always the same
                filename = 'S.abf';
        end

        if TS_T_S == 1 % Multimodal always should load
                thisFile = abfload(strcat(files(f).folder,'\',filename)); % A x B x C, where A = index, B = channel, C = sweep
        else
            try %It could be that we are missing unimodals. If so, skip them
                thisFile = abfload(strcat(files(f).folder,'\',filename));
                if TS_T_S == 2
                    file_is_sT = 0;
                end
            catch %If it failed, give another chance to TS-50,-5,0,5,50...
                if and(TS_T_S == 2, contains('TS-50.abf_TS-5.abf_TS0.abf_TS5.abf_TS50.abf',files(f).name))
                    try
                        filename = 'sT.abf';
                        thisFile = abfload(strcat(files(f).folder,'\',filename));
                        file_is_sT = 1;
                    catch
                        continue
                    end
                else
                    continue
                end
            end
        end

        subplot(3,1,TS_T_S)
        title(strcat('f=',num2str(f),'/',num2str(size(files,1)), ' -- ', ...
            neuron, ' - Multimodal protocol:', files(f).name,...
            ' - Modality:',subplot_modality(TS_T_S),' - Filename:',filename)); hold on

        time = linspace(0, size(thisFile,1)/SR, size(thisFile,1));

    
        numberSweeps = size(thisFile,3);
        area_sweeps = NaN(numberSweeps,1);
        tonicDep_sweeps = NaN(numberSweeps,1);
        peakV_sweeps = NaN(numberSweeps,1);
        timeToPeak_sweeps = NaN(numberSweeps,1);

        if TS_T_S == 1

            %Define now, so if the file is missing we can still save the NaN
            T_area = NaN;
            T_peakV = NaN;
            T_timeToPeak = NaN;
            T_tonicDep = NaN;
            S_area = NaN;
            S_peakV = NaN;
            S_timeToPeak = NaN;
            S_tonicDep = NaN;
        end
        
        for s = 1:numberSweeps %sweeps
            V = thisFile(:,1,s); V = V - mean(V(1:SR*0.25));
            mic = thisFile(:,2,s) * 50;

            plot(time,V+(s-1)*1.1); hold on; plot(time,mic -3); hold on
    
            %% 50 Hz filter

            V = filtfilt(d,V);
            plot(time, V+(s-1)*1.1); hold on
    
            %% Optional: check Fourier spectra
            % fourierT = fft(V);
            % L = size(V,1); P2 = abs(fourierT/L); P1 = P2(1:L/2+1); P1(2:end-1) = 2*P1(2:end-1); freq = SR*(0:(L/2))/L;
            % figure; plot(freq(1:1000),P1(1:1000))
            % title('Single-Sided Amplitude Spectrum of X(t)'); xlabel('f (Hz)'); ylabel('|P1(f)|')
    
            %% Look for the appropiate ROI
            if TS_T_S == 1  %For multimodals, we look for sound and tectal stimulation signs
                            %For tectals, we will use the same ROI as multimodal 
                            %For sounds, we will detect the sound and use the same delay as in multimodal 
                if s == 1
                    soundIdx = find(abs(mic) > 0.5, 1, "first");
                    soundDetected = ~isempty(soundIdx);
                    
        
                    tectalIdx = find( abs(V(1:end-tectalSearchX) - V(1+tectalSearchX:end) ) > tectalSearchY,1, "last");
                    if time(tectalIdx)>1.3 % Detected tectal is not a real tectal, but noise
                        tectalSearchY = 6; % Increase tectal detection threshold
                        tectalIdx = find( abs(V(1:1.3*SR-tectalSearchX) - V(1+tectalSearchX:1.3*SR) ) > tectalSearchY,1, "last");
                    end
                    tectalDetected = ~isempty(tectalIdx);
                    
                    if or(contains(files(f).name, 'S') ~= soundDetected, contains(files(f).name, 'T') ~= tectalDetected)
                        msgbox(strcat('Error detecting sound or tectal stimulus on file',files(f).name,' sweep ',num2str(s)))
                    end
            
                    ROIstart = max([soundIdx, tectalIdx + round(delayPostTectal * SR)]);
                    ROIend = ROIstart + round(ROI * SR);
                    
                    % Save this ROI, will be used for unimodals
                    ROIstart_sweeps_multi = ROIstart;
                    ROIend_sweeps_multi = ROIend;
                    soundIdx_sweeps_multi = soundIdx;
                    tectalIdx_sweeps_multi = tectalIdx;
                end
                plot(time(soundIdx), mic(soundIdx)-3,'o','MarkerEdgeColor','k','MarkerFaceColor','k'); hold on
                plot(time(tectalIdx), V(tectalIdx)+(s-1)*1.1,'o','MarkerEdgeColor','k','MarkerFaceColor','k'); hold on
        
            elseif TS_T_S == 2


                if file_is_sT == 1 %Exception is if we are using sT.abf
                    sTIdx = find( abs(V(1:end-tectalSearchX) - V(1+tectalSearchX:end) ) > tectalSearchY,1, "last");
                    plot(time(sTIdx), V(sTIdx)+(s-1)*1.1,'o','MarkerEdgeColor','k','MarkerFaceColor','k'); hold on

                    tectal_ROI_delay_TS = ROIstart_TS - tectalIdx_TS;
                    ROIstart = sTIdx + tectal_ROI_delay_TS;
                    ROIend = ROIstart + round(ROI * SR);                    
                else
                    % Use same ROI as multimodal
                    ROIstart = ROIstart_TS;
                    ROIend = ROIend_TS;
                    plot(time(tectalIdx), V(tectalIdx)+(s-1)*1.1,'o','MarkerEdgeColor','k','MarkerFaceColor','k'); hold on
                end

                if or(contains(files(f).name,'TS200'),contains(files(f).name,'TS250'))
                    ROIstart = ROIstart - round(0.01666 * SR);
                    ROIend = ROIend - round(0.01666 * SR);
                    plot(time(tectalIdx- round(0.01666 * SR)), V(tectalIdx- round(0.01666 * SR))+(s-1)*1.1,'o','MarkerEdgeColor','k','MarkerFaceColor','k'); hold on
                end

            elseif TS_T_S == 3
                % Use same delay between sound and ROI as in multimodal
                soundIdx = find(abs(mic) > 0.5, 1, "first");
                plot(time(soundIdx), mic(soundIdx)-5,'o','MarkerEdgeColor','k','MarkerFaceColor','k'); hold on
        
                sound_ROI_delay_avg_TS = ROIstart_TS - soundIdx_TS;
                ROIstart = soundIdx + sound_ROI_delay_avg_TS;
                ROIend = ROIstart + round(ROI * SR);
            end
            
            plot(time([ROIstart, ROIend]),V([ROIstart, ROIend])+(s-1)*1.1,'o','MarkerEdgeColor','g','MarkerFaceColor','g'); hold on
            xline(time(ROIstart));

            %% Calculate and plot values of interest
           
            area = sum(V(ROIstart : ROIend))/SR;
            [peakV, peakIdx] = max(V(ROIstart : ROIend));
            timeToPeak = time(peakIdx); % This is effectively calculating delay from ROIstart to peak, given how it is defined in the previous line
            plot(time(ROIstart + peakIdx),peakV+(s-1)*1.1,'o','MarkerEdgeColor','r','MarkerFaceColor','r'); hold on
            
            if contains(files(f).name,'TS4') %For TS4, it is not worth it to try to get the inter-tectal ROIs
                tonicDepROIend = 1.02 * SR;
                tonicDepROIstart = 1.0 * SR;
            else
                tonicDepROIend = ROIstart - round(tonicDepolarizationShift * SR);
                tonicDepROIstart = tonicDepROIend - round(tonicDepROIwidth * SR);
            end

            plot(time([tonicDepROIstart, tonicDepROIend]),V([tonicDepROIstart, tonicDepROIend])+(s-1)*1.1,...
                'o','MarkerEdgeColor','b','MarkerFaceColor','b'); hold on
    
                
            tonicDep = mean(V(tonicDepROIstart:tonicDepROIend));
            %yline(tonicDep);
            

            xlim([tonicDepROIstart/SR-0.005 ROIend/SR+0.005])
       
            ylim([-4.5 14])
            
            % Store these values
            area_sweeps(s) = area;
            tonicDep_sweeps(s) = tonicDep;
            peakV_sweeps(s) = peakV;
            timeToPeak_sweeps(s) = timeToPeak;
        end


        area_mean = mean(area_sweeps);
        peakV_mean = mean(peakV_sweeps);
        timeToPeak_mean = mean(timeToPeak_sweeps);
        tonicDep_mean = mean(tonicDep_sweeps);
        
        % Store values with appropiate names according to the current file
        if TS_T_S == 1
            ROIstart_TS = ROIstart_sweeps_multi;
            ROIend_TS = ROIend_sweeps_multi;
            soundIdx_TS = soundIdx_sweeps_multi;
            tectalIdx_TS = tectalIdx_sweeps_multi;

            M_area = area_mean;
            M_peakV = peakV_mean;
            M_timeToPeak = timeToPeak_mean;
            M_tonicDep = tonicDep_mean;
        elseif TS_T_S == 2
            T_area = area_mean;
            T_peakV = peakV_mean;
            T_timeToPeak = timeToPeak_mean;
            T_tonicDep = tonicDep_mean;
        else 
            S_area = area_mean;
            S_peakV = peakV_mean;
            S_timeToPeak = timeToPeak_mean;
            S_tonicDep = tonicDep_mean;
        end
    
    end
    
    myFig.WindowState = 'maximized';
    pause;

    subplot(3,1,1)
    xlim([0.95 1.35])
%    if file_is_sT == 0
        subplot(3,1,2)
        xlim([0.95 1.35])
    %end

    subplot(3,1,3)
    xlim([0.95 1.35] + (soundIdx - soundIdx_TS )/SR )

    pause;
    clear myFig
    close all
    
    % Get some basic info about the neuron and protocol, and save as .mat
    % files
    day = neuron(1:6);
    side = neuron(7);
    protocol = files(f).name(1:end-4);
    save(strcat(...
        'C:\Users\soterocoronel\Desktop\Dropbox (Dropbox @RU)\Ephys Mauthner\ExtractedData\',... %directory
        day,side,'_', protocol,'.mat'),...                      %filename
        'day','side','protocol',...                             %variables
        'M_area','M_peakV','M_timeToPeak','M_tonicDep',...      %variables
        'T_area','T_peakV','T_timeToPeak','T_tonicDep',...      %variables
        'S_area','S_peakV','S_timeToPeak','S_tonicDep')         %variables

end






% Load the .mat files and save the results in an Excel table


clearvars; close all force; clc;

addpath('C:\Users\soterocoronel\Desktop\Ephys Mauthner\Codigo')

files = dir('C:\Users\soterocoronel\Desktop\Ephys Mauthner\ExtractedData\*');
files = files([files(:).bytes] > 1);

T_size = [size(files,1) 19];
varTypes = {'string','string','string',...
            'double','double','double','double',...
            'double','double','double','double', ... 
            'double','double','double','double',...
            'double','double','double','double'};


varNames = {'Protocol','Day','Side',...
            'M_area','M_peakV','M_timeToPeak','M_tonicDep',...
            'GU_area','GU_peakV','GU_peakV_timeToPeak','GU_peakV_tonicDep',...
            'T_area','T_peakV','T_timeToPeak','T_tonicDep',...
            'S_area','S_peakV','S_timeToPeak','S_tonicDep'};
dataTable = table('Size',T_size,'VariableTypes',varTypes,'VariableNames',varNames);

for f = 1:size(files,1)
    protocol = NaN;
    day = NaN;
    side = NaN;

    M_area = NaN;
    M_peakV = NaN;
    M_timeToPeak = NaN; 
    M_tonicDep = NaN ;

    GU_area = NaN;
    GU_peakV = NaN; 
    GU_peakV_timeToPeak = NaN; 
    GU_peakV_tonicDep = NaN; 

    T_area = NaN; 
    T_peakV = NaN; 
    T_timeToPeak = NaN; 
    T_tonicDep = NaN; 

    S_area = NaN; 
    S_peakV = NaN; 
    S_timeToPeak = NaN; 
    S_tonicDep = NaN;

    load(strcat(files(f).folder,'\',files(f).name))
    if and(~isnan(T_area),~isnan(S_area))
        GU_area = max([T_area S_area]);
        if T_peakV > S_peakV
            GU_peakV = T_peakV;
            GU_peakV_timeToPeak = T_timeToPeak;
            GU_peakV_tonicDep = T_tonicDep;
        else
            GU_peakV = S_peakV;
            GU_peakV_timeToPeak = S_timeToPeak;
            GU_peakV_tonicDep = S_tonicDep;
        end
    end

    data_this_file = {protocol,day,side,...
        M_area,M_peakV,M_timeToPeak,M_tonicDep,...
        GU_area,GU_peakV,GU_peakV_timeToPeak,GU_peakV_tonicDep,...
        T_area,T_peakV,T_timeToPeak,T_tonicDep,...
        S_area,S_peakV,S_timeToPeak,S_tonicDep};
    dataTable(f,:) = data_this_file;
end

filename = 'C:\Users\soterocoronel\Desktop\Dropbox (Dropbox @RU)\Ephys Mauthner\dataExcel.xlsx';
writetable(dataTable,filename,'Sheet',1)