% This script takes all data files (presumably *.mat) in a specified folder
% and concatenates them into one data file containing [1] mean/std/n for
% each cell, to be used to generate an overall culture average, and [2]
% random samples of minis from each cell to be used for rank plots and
% cumulative histograms.

clear all; close all;

n_cutoff = 30;
bootstrap = 1;

feature = 'amplitude';
% -- setting values for feature of interest -- %
switch feature
    case 'amplitude'
        f_label = 'Amplitude';
        f_unit = 'pA';
        f_datcol = 3;
        f_bounds = [5 400];
        f_cumhist = 1;
    case 'frequency'
        f_label = 'Frequency';
        f_unit = 'Hz';
        f_datcol = 19;
        f_bounds = [1/200 1000];
        f_cumhist = 0;
    case 'decay'
        f_label = 'Decay Time Constant';
        f_unit = 'ms';
        f_datcol = 5;
        f_bounds = [0.2 6]; %for AMPAergic minis
        f_cumhist = 0;
    case 'charge'
        f_label = 'Charge Transfer';
        f_unit = 'fC';
        f_datcol = 6;
        f_bounds = [1 inf];
        f_cumhist = 0;
end


dirID = 'C:\Users\mingfaifong\Documents\2013-01-16_TTX-CTZ-vehicle_patch-analysis\';
type = 'TTX-CTZ';
y = dir([dirID,type,'\']); z = [y.isdir];
culturelist = {y(~z).name}';

i_cell = 1;
for i_culture = 1:length(culturelist) %loop through files
    load([dirID,type,'\',culturelist{i_culture}]);
    for i_dat = 1:length(dat) %loop through cells within a file
        if size(dat{i_dat},1) < n_cutoff
            continue
        end
        x = dat{i_dat}(:,f_datcol);
        x = x(x>=f_bounds(1) & x<=f_bounds(2));
        stats.avg(i_cell) = nanmean(x);
        stats.std(i_cell) = nanstd(x);
        stats.n(i_cell) = length(x);
        cellID(i_cell) = i_cell;
        cultureID(i_cell) = i_culture;
        if bootstrap==1
            sample.mEPSC(:,i_cell) = randsample(x,10000,true);
        else
            sample.mEPSC(:,i_cell) = randsample(x,n_cutoff);
        end
        i_cell = i_cell+1;
    end
end

save([dirID,'bootstrap_03\',type,'_',num2str(n_cutoff),'events'],'n_cutoff','stats','cellID','cultureID','sample','feature','culturelist');
