function [ LABELS ] = mlfread(FILE)
%
% [ LABELS ] = mlfread(FILE)
% 
  % Read the HTK master label file FILE, and return transcriptions
%
% FILE (string) - the name of the file to be read
% LABELS (N) - a struct array containing
%      LABELS(n).t - an (NSEGx2) matrix of start and end times
%      LABELS(n).l - an (NSEGxDEPTH) cell array of labels
%      LABELS(n).f - string: name of the nth .lab file
%
% Mark Hasegawa-Johnson
% Last revised 12/7/2003

% First, read lines into a cell array, ignoring #!MLF!# line
[lines] = textread(FILE,'%s','delimiter','\n','commentstyle','shell');

% Create output
nfiles = 1;
nseg = 0;
nlines = 1;
LABELS(1).f = lines{nlines};

for nlines=2:length(lines),
    % Increment nfiles and reset nseg if line is '.'
    if lines{nlines}=='.',
       nfiles=nfiles+1;
       nseg=0;
    
    % If this is a '.lab' entry, store as the filename
    elseif findstr(lines{nlines},'.lab'),
       LABELS(nfiles).f = lines{nlines};

    % Otherwise, read this line as a transcription
    else,
	nseg=nseg+1;
	% Divide the line into whitespace-separated fields
	fields = strread(lines{nlines},'%s');

	% If first field begins with digit, interpret as start-time
	if findstr('0123456789-',fields{1}(1)),
	   LABELS(nfiles).t(nseg,1) = str2num(fields{1})/1e7;
	   fields = fields(2:length(fields));
	end

	% If second field begins with digit, interpret as end-time
	if findstr('0123456789-',fields{1}(1)),
	   LABELS(nfiles).t(nseg,2) = str2num(fields{1})/1e7;
	   fields = fields(2:length(fields));
	end
	
	% Put remaining fields into LABELS.l
	if isfield(LABELS(nfiles),'l'),
          if size(LABELS(nfiles).l,2) < length(fields),
           LABELS(nfiles).l = [ LABELS(nfiles).l, ...
			    cell(size(LABELS(nfiles),1), ...
			    length(fields)-size(LABELS(nfiles).l,2))];
         end
        end
        LABELS(nfiles).l(nseg,1:length(fields)) = fields(:);
    end
end
