function [pars, type]= pgmReadHeader(fid)
% Read and parse a pgm image file header
% For a successful parse, return:
%  pars = [xdim ydim maxval]
%       xdim, ydim = number of columns, number of rows
%       maxval = maximum pixel value
% and type = 'P2' or 'P5'
% For an unsuccessful parse, returns 
%  pars=-1
% Written by A. Jepson, 9/99

pars = zeros(1,3);
type = 'Unknown';

%%% First line contains ID string:
%%% "P1" = ascii bitmap, "P2" = ascii greymap,
%%% "P3" = ascii pixmap, "P4" = raw bitmap, 
%%% "P5" = raw greymap, "P6" = raw pixmap
TheLine = fgetl(fid);
szLine = size(TheLine);
endLine = szLine(2);

if (endLine < 2)
  fprintf(1,'Not a pgm file\n');
  pars = -1;
  return;
end
 
if ~((TheLine(1:2) == 'P2') | (TheLine(1:2) == 'P5'))
   fprintf(1, 'PGM file must be of type P2 or P5\n');
   pars = -1;
   return;
end

type = TheLine(1:2);
current = 3;

parIndex=1;  % index for next parameter to be read
while(parIndex < 4) 
  while (current > endLine)
    TheLine = fgetl(fid);
    if (TheLine == -1)
      fprintf(1, 'Unexpected EOF\n');
      pars = -1;
      return;
    end
    szLine = size(TheLine);
    endLine = szLine(2);
    current = 1;
  end
  
  [token, count, errmsg, nextindex] = ...
       sscanf(TheLine(current:endLine),'%s',1);
  nextindex = nextindex+current-1;
  
  if (count==0)
    if (nextindex > endLine) % Read to end of line
     current = nextindex;
    else % Problem
     pars = -1;
     fprintf(1, 'Unexpected EOF\n');
     return;
    end
  else  % Found a token
  
   if token(1) == '#'
    current = endLine+1;
   else
    [pars(parIndex), count, errmsg, nextindex] = ...
       sscanf(TheLine(current: endLine), '%d', 1);
    if ~(count==1)
      fprintf(1,'Confused reading pgm header\n');
      pars=-1;
      return;
    end
    parIndex = parIndex+1;
    current = current+nextindex-1;
   end

  end
end
