function L = ilabread(N,U,S,F)
% L = ilabread(N,U,S,R)  Read one utterance's labels from an ilab file
%    Read the data and labels for utterance U from ilab file named N.
%    S is starting frame (optional, default 0) and F is the 
%    maximum number of frames to read (optional, default to EOS). 
% 2003-03-12 dpwe@ee.columbia.edu after pfread

if nargin < 3
  S = 0;
end
if nargin < 4
  F = -1;
end

% Use our sister function to get the raw index into the pfile, from 
% the header and index

[utrows,sents,absrow,bitsplab] = ilabinfo(N,U);

fid = fopen(N,'r','b');

fseek(fid, absrow, -1);
% Check the utterance number is what we asked for
utnum = fread(fid, 1, 'int32');
if utnum ~= U
  fclose(fid)
  error(['Utterance number read as ', num2str(utnum)]);
end

L = zeros(1, utrows);
base = 0;
count = -1;

while count ~= 0
  % Decode RLE blocks until we get enough
  count1 = fread(fid, 1, 'uint8');
  % Does count need to be extended?
  if count1 >= 192
    count2 = fread(fid, 1, 'uint8');
    count3 = fread(fid, 1, 'uint16');
    count = (2^24)*(count1-192)+(2^16)*count2+count3;
  elseif count1 >= 128
    count2 = fread(fid, 1, 'uint8');
    count = 256*(count1-128)+count2;
  else
    count = count1;
  end

  if count > 0
    if bitsplab <= 8
      lab = fread(fid, 1, 'uint8');
    elseif bitsplab <=16
      lab = fread(fid, 1, 'uint16');
    else
      lab = fread(fid, 1, 'uint32');
    end

    L(base + [1:count]) = lab;
    base = base+count;
  end
end

% done
fclose(fid);
