% IM = pgmRead( FILENAME )
%
% Load a pgm image into a MatLab matrix.  
%   This format is accessible from the XV image browsing utility.
%   Only works for 8bit gray images (raw or ascii)

% Hany Farid, Spring '96.  Modified by Eero Simoncelli, 6/96.
% Modified by Allan Jepson, 9/99.
function im = pgmRead( fname );

global SIZE_LIMIT;
if SIZE_LIMIT
 fprintf(1, 'SIZE_LIMIT recognized by pgmread\n');
end

[fid,msg] = fopen( fname, 'r' );
if (fid == -1)
  error(msg);
end

[pars type]= pgmReadHeader(fid);
if (pars==-1)
  fclose(fid);
  error([fname ': cannot parse pgm header']);
end

xdim = pars(1);
ydim = pars(2);
%%% Maximum pixel value
maxval = pars(3);
fprintf(1, 'original image size: cols %d rows %d\n', xdim, ydim)
sz = xdim * ydim;

if SIZE_LIMIT
 if sz >= 16384
   ydim = floor(16384/xdim);
   sz = xdim * ydim;
   fprintf(1, 'truncated image size: cols %d rows %d\n', xdim, ydim)
 end
end

if (type == 'P2')
  [im,count]  = fscanf(fid,'%d',sz);
elseif (type == 'P5')
  [im,count]  = fread(fid,sz,'uchar');
else
  fclose(fid);
  error([fname ': Not of type P2 or P5.']);
end

fclose(fid);

if (count == sz)
  im = reshape( im, xdim, ydim )';
else
  fprintf(1,'Warning: File ended early!');
  im = reshape( [im ; zeros(sz-count,1)], xdim, ydim)';
end
