clear all;
close all;
%addpath('C:\Documents and Settings\mingfaifong\My Documents\MiniAnalysis Data\shared_functions');

cultureID = 'anchovy2';
dirID = 'C:\Users\mingfaifong\Documents\2012-06-20_anchovy2_13DIV_Patch_post-TTX-CTZ\waveform\';
y = dir(dirID); z = [y.isdir];
fidlist = {y(~z).name}';
fidlist = fidlist(~cellfun('isempty',strfind(fidlist,'_rise50.txt')));
maxBufSize = max(cell2mat({y.bytes}));


%% loading data into matrix variables
for i = 1:length(fidlist)
    fid = fidlist{i};
    fstring = fileread([dirID fid]);
    x = textscan(fstring,'%[^\n\r]','Headerlines',6,'delimiter','\t','BufSize',maxBufSize);
    ncol = length(strfind(x{1,1}{1,1},'	'))+1;
    fmt = repmat('%f',1,ncol);
    data = cell2mat(textscan(fstring,fmt,'Headerlines',6,'delimiter','\t','BufSize',maxBufSize));
    save([dirID fid(1:end-4) '.mat'],'data','fid');
end
    
%% loading mat data
for i = 1:length(fidlist)
    fid = fidlist{i};
    load([dirID fid(1:end-4) '.mat']);
    curr{i,1} = data(:,2:end)';
end
time = data(:,1)';

%% combine files from same recording
i_combine = {[1,2],[5,6],[7,8,9]};
i_remove = [];
for i = 1:length(i_combine)
    for j = 1:length(i_combine{i})-1
        curr{i_combine{i}(1)} = [curr{i_combine{i}(1)}; curr{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
curr(i_remove) = [];
fidlist(i_remove) = [];

%% save data by cultureID
% dat_tmp = curr;
save([dirID(1:length(dirID)-9) cultureID '_waveform_rise50'],'curr','time','fidlist');