function [D,L] = pfread(N,U,S,F)
% [D,L] = pfread(N,U,S,R)  Read one utterance from a pfile
%    Read the data and labels for utterance U from pfile named N.
%    S is starting frame (optional, default 0) and F is the 
%    maximum number of frames to read (optional, default to EOS). 
%    Data is returned in D, labels in L.
% 1998aug14 dpwe@icsi.berkeley.edu   M-script version

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,ftrs,labs,absrow] = pfinfo(N,U);

fid = fopen(N,'r','b');
%disp('opened big endian');
% Seek to the row
% Assume std header size
hdrsize=32768;
wdsize=4;
prfxcols = 2;	% 2 columns of prefix (utt, frm) on each pfile row
rowlen = prfxcols+ftrs+labs;

D = [];
L = [];

% Which rows are we actually going to read?
startrow = min(S, utrows);
nrows = utrows - startrow;
if F >= 0
  nrows = min(F, nrows);
end

% First read feature data, if any
if ftrs > 0
	fseek(fid, hdrsize+wdsize*rowlen*(absrow+startrow), -1);
	D = fread(fid, [prfxcols+ftrs+labs,nrows], 'float32');
	% collapse away the non-feature cols (& transpose)
	D = D(prfxcols+[1:ftrs],:)';
end

% Read label data, if any
if labs > 0
	fseek(fid, hdrsize+wdsize*rowlen*(absrow+startrow), -1);
	L = fread(fid, [prfxcols+ftrs+labs,nrows], 'int32');
	% collapse away the non-label cols (& transpose)
	L = L(prfxcols+ftrs+[1:labs],:)';
end

% done
fclose(fid);
