%mergefile   merge csv files in a directory to all0.csv 
%   mergefile merges the content of all the csv files in a directory into a
%   single file all0.csv. It also adds a column indicating the original
%   file name. 
%
%   It assumes the files to be merged have the same header, and only the
%   header of the first file will be kept (i.e. the first row of the files
%   - except for the 1st file, will be ignored).
%
%   Author: Xu Cui (http://www.alivelearn.net/)
%   2018-10-10


delete all0.csv
f = dir('*.csv');
fid2 = fopen('all0.csv','wt');
for i=1:length(f)
    fname = f(i).name;
    
    fid = fopen(fname);
    tline = fgetl(fid);
    j=1;
    while ischar(tline)
        disp(tline)
        if (i==1 || j>1)
            fprintf(fid2, [tline ',' fname '\n']);
        end
        tline = fgetl(fid);
        j=j+1;
    end
    fclose(fid);
end
fclose(fid2);