function pgm_write ( pgm, filename )

%*****************************************************************************80
%
%% pgm_write() writes a matrix to a binary PGM file.
%
%  Modified:
%
%    04 December 2018
%
%  Modifier:
%
%    John Burkardt
%
%  Author:
%
%    Matthew Dailey, 1999
%
%  Input:
%
%    integer pgm(h,w), an integer array of h rows and w columns.
%
%    string filename, the name of the file.
%
  if ( ~ ( 0 <= pgm && pgm <= 255 ) )
    error ( 'PGM_WRITE - Error, image pixels out of range.' );
  end
%
%  Open the file
%
  fid = fopen ( filename, 'w' );

  if ( fid <= 0 )
    error ( 'PGM_WRITE - Error, could not open the file for writing.' );
  end
%
%  Get the shape of the image.
%
  [ height, width ] = size ( pgm );
%
%  Write the header information.
%
  fprintf ( fid, 'P5\n' );
  fprintf ( fid, '%d %d\n', width, height );
  fprintf ( fid, '255\n' );
%
%  Transpose the data.
%
  pgm = pgm';
%
%  Write the raw data.
%
  count = fwrite ( fid, pgm, 'uchar' );

  if ( count ~= width * height )
    error ( 'PGM_WRITE - Error, could not write all data to the file.' );
  end

  fclose ( fid )

  return
end

