function pgm = pgm_read ( filename )

%*****************************************************************************80
%
%% pgm_read() reads a raw (binary) pgm file as a numeric matrix
%
%  Discussion:
%
%    The command
%      pgm = pgm_read ( filename )
%    reads the binary PGM image data from filename and returns a 2-dimensional
%    array of integers as pgm. 
%
%    The function assumes that the file is a raw pgm file containing 8-bit 
%    unsigned character data to represent pixel values.
%
%    Because the image data is numeric, it cannot be displayed by 
%    MATLAB's imshow() function without some processing.  However, it
%    can be displayed by the imshow_numeric() command:
%      imshow_numeric ( pgm )
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    29 November 2018
%
%  Author:
%
%    Original MATLAB version by Matthew Dailey.
%    This version by John Burkardt.
%
%  Input:
%
%    string filename, the name of the file.
%
%  Output:
%
%    integer pgm(h,w), an integer array of h rows and w columns.
%

%
%  Open the file.
%
  fid = fopen ( filename, 'r' );
%
%  Parse and check the header information.  
%  No # comments allowed.
%  Check for the binary PGM magic number.
%
  A = fgets ( fid );
  if ( strcmp ( A(1:2), 'P5' ) ~= 1 )
    error ( 'pgm_read: File is not a raw PGM' );
  end
%
%  Get W and H, the "width" and "height" of the image.
%
  A = fgets ( fid );
  wh = sscanf ( A, '%d' );
  w = wh ( 1 );
  h = wh ( 2 );
%
%  Get gmax, the maximum gray level.
%
  A = fgets ( fid );
  gmax = sscanf ( A, '%d' );
  if ( gmax ~= 255 )
    error ( 'pgm_read: Cannot handle anything but 8-bit graymaps' );
  end
%
%  Read the raw data
%
  [ v, count ] = fread ( fid, inf, 'uchar' );

  if ( count ~= w * h )
    error ( 'pgm_read: File size does not agree with specified dimensions.' );
  end
%
%  Pack the column vector V into image;
%
  pgm = reshape ( v, w, h );
%
%  Transpose image;
%
  pgm = pgm';
%
%  Close the file.
%
  fclose ( fid );

  return
end
