% PGMREAD  Reads in an image from a binary PGM (Portable GrayMap) file.
%
%          IMG = PGMREAD('filename.pgm') returns the image as a 2D array of
%          values, in the orientation suitable for calls to IMAGE and IMAGESC.
%          Each value corresponds to the intensity of one pixel.
%
%          [IMG,MAXVAL] = PGMREAD('filename.pgm') returns the image and the
%          maximum value of a pixel in the image (from the PNM file).


function [pnm,maxval] = pgmread(name)

[fd,msg] = fopen(name,'r');

if (fd < 0)
  fprintf(2,'pgmread: ERROR in fopen\n -- %s\n',msg);
  pnm=[];
  return;
end

[id,size] = fread(fd, 3, 'char');
if ~((size == 3) & strcmp(setstr(id([1,2])'),'P5') & (id(3) == 10))
  fprintf(2,'pgmread: ERROR reading magic number\n -- %s\n',msg);
  pnm=[]; maxval=0
  return;
end

[line,lsz] = fscanf(fd,'%[^\012]s');
[dim, dsz] = fscanf(fd,'%d',2);
[maxval, msz] = fscanf(fd,'%d');

if ~((lsz == 1) & (dsz == 2) & (msz == 1))
  fprintf(2,'pgmread: ERROR reading header\n -- %s\n',msg);
  pnm=[]; maxval=0;
  return;
end

% pnm = rot90(fread(fd,dim'),-1);
pnm = fread(fd,dim')';
