%% get directory names of analysis (all folders containing "DIV" in title)

clear all; close all;
parentdir = 'C:\Users\mingfaifong\Documents\new\';
filelist = dir(parentdir);
dirlist = {filelist([filelist.isdir]).name};
%dirlist = dirlist(~(strcmp('.',dirlist)|strcmp('..',dirlist)|~cellfun(@isempty,strfind(dirlist,'patch-analysis'))))';
dirlist = dirlist(~cellfun(@isempty,strfind(dirlist,'DIV')))';


%% batch created "alldata" files for each experiment

for i = 1:length(dirlist)
    dirID = dirlist{i};
    uloc = strfind(dirID,'_');
    cultureID = dirID(uloc(1)+1:uloc(2)-1);
    dirID_full = [parentdir,dirID,'/ascii/'];
    y = dir(dirID_full); z = [y.isdir];
    fidlist = {y(~z).name}';
    
    % replacing all commas with nothing
    for i = 1:length(fidlist)
        fid = fidlist{i};
        replaceinfile(',','',[dirID_full fid],'-nobak');
    end
    
    % importing data
    for i = 1:length(fidlist)
        fid = fidlist{i};
        dat{i,1} = importdata([dirID_full fid]);
        dat{i,1} = sortrows(dat{i},2);
    end
    
    % combine files from same recording
    i_combine = {};
    i_remove = [];
    keyboard;
    for i = 1:length(i_combine)
        for j = 1:length(i_combine{i})-1
            dat{i_combine{i}(1)} = [dat{i_combine{i}(1)}; dat{i_combine{i}(j+1)}];
            i_remove(end+1) = i_combine{i}(j+1)
            fidlist{i_combine{i}(1)} = [fidlist{i_combine{i}(1)},'; ',fidlist{i_combine{i}(j+1)}]
        end
    end
    dat(i_remove) = [];
    fidlist(i_remove) = [];

    % add frequencies in Hz
    for i = 1:length(dat)
        dat{i,1}(:,19) = [1000./diff(dat{i,1}(:,2)); NaN]; %frequency in Hz
    end

    % save data by cultureID
    dat_tmp = dat;
%    save([dirID_full(1:length(dirID_full)-6) cultureID '_alldata'],'dat','fidlist');
    save([parentdir dirID '/' cultureID '_alldata'],'dat','fidlist');

end