function [mat] = muon_matrixfile(directory,numstart,numend)
%[mat] = muon_matrixfile(directory,numstart,numend)
%
%Concatenates text files into a single matrix and saves the result as
%matrix.dat, a tabs-delimited text file, also in the specified directory.
%
%INPUT:     directory - the directory where files live (note text must be
%                           surrounded by apostrophes)
%           numstart - the starting event index
%           numend - the ending event index
%
%OUTPUT:    mat - the matrix is also returned in the workspace
%
%WARNING: THIS PROGRAM DOES NOT WORK WITH FILNAMES THAT INCLUDE A SPACE.
%   Please eliminate all spaces from filenames.  The filename convention is
%       SCxxx.txt where xxx is the file index.
%
%Edit the function file to change the event parameters.
%Written by David Tam, Columbia Univeristy Dept. of Physics, November 2009

directory
cd(directory)

%mkdir('goodfiles')
mat = [];

for findex=numstart:numend
    
    fname = ['SC' num2str(findex) '.txt'];
    
    if exist([directory fname])==0
        continue
    end
    
    fid=fopen(fname);
    event=fscanf(fid,'%g');
    
    mat = [mat event];
    
    fid=fclose(fid);
    
end

%dlmwrite(fname,event.*-1,'newline','pc');
%name = ['matrix' num2str(numstart)]
save matrix mat -ascii -tabs

end