%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This function preprocesses .abf files: imports files, filters, subsamples 
% and extracts events and their features and stores then in a file
% structure: in the current folder, each session in a separate folder, 
% named Session <session_number>, each trace in a separate file with the 
% last two digits representing the recording number.
%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear all;
close all;

% TO START, create a file structure with the datasets:
%
% file_struct(file_number, feature_number) = [session_number recording_number
% baseline/response control/target dpf errors]
% 
% Note that:
% session_number = number of the session - should be present in the
% folder name;
% recording_number = number of the recording - should be present in the
% last digits of the recording name;
% baseline/response = 0 if the trace is recorded only during spontaneous
% activity; 1 if trace contains response to PTZ 
% control/target = 0 if the trace is recorded from a Mismatch control fish;
% 1 if trace is recorded from a DEPDC5 animal

file_struct(1,:) = [12 2 1 0 5 0];
file_struct(2,:) = [15 3 1 1 5 0];

% set the initial parameters
f_subsample = 250;      % [Hz] = sampling frequency of the trace

f_lpf = 100;            % [Hz] = low pass filter frequency for anti-aliasing
f_hpf_extract = 0.5;    % [Hz] = high pass filter frequency for the DETECTION signal (V_extract)

threshold_amp = 0.3;    % [mV] = threshold for detecting events in the DETECTION signal (V_extract)
width_th = 0.04;        % [s] = threshold for event length in order to be considered a depolarization event
threshold_dist = 4;     % [s] = threshold for inter-event distance in order to be considered separate depolarization events
verbose = 1;            % flag to select wether to plot intermediate computations (1) or not (0)

% the path to the directory where the raw data is saved. In here, each 
% session in a separate folder, named Session <session_number>, inside the 
% session folder is another folder named Data, and inside, each trace is in 
% a separate file with the last two digits representing the recording number.
data_folder = [];     

% iterate through sessions
for i_session=[12 15];
    % set source and destination locations 
    session = ['Session ' num2str(i_session)];
    dir_name = [data_folder session '\Data'];
    file_id = file_struct(file_struct(:,1) == i_session,2);
    dir_save = session;
    % extract data from the .abf file - anti aliasing filter and subsampling
    ExtractAbfData(dir_name, dir_save, file_id, f_lpf, f_subsample, verbose);
    % generate DETECTION and ANALYSIS signals 
    FilterMatData(dir_save, file_id, f_subsample, f_hpf_extract, verbose);
    % Extract event features and save them in a matrix format
    ExtractFeatures(dir_save, file_id, f_subsample, threshold_amp, threshold_dist, width_th, verbose);
end





