function pgma_write ( file_name, comment, width, height, maxval, gray )

%*****************************************************************************80
%
%% pgma_write() writes gray scale data into an ASCII PGM file.
%
%  Discussion:
%
%    The PGMA file will have the format:
%
%    P2
%    # file_name created by Matlab PGMA_WRITE.
%    width height
%    maxval, the maximum legal value for the data.
%    row 1
%    row 2
%    ...
%    row height
%
%  Example:
%
%    P2
%    # feep.pgm
%    24 7
%    15
%    0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
%    0  3  3  3  3  0  0  7  7  7  7  0  0 11 11 11 11  0  0 15 15 15 15  0
%    0  3  0  0  0  0  0  7  0  0  0  0  0 11  0  0  0  0  0 15  0  0 15  0
%    0  3  3  3  0  0  0  7  7  7  0  0  0 11 11 11  0  0  0 15 15 15 15  0
%    0  3  0  0  0  0  0  7  0  0  0  0  0 11  0  0  0  0  0 15  0  0  0  0
%    0  3  0  0  0  0  0  7  7  7  7  0  0 11 11 11 11  0  0 15  0  0  0  0
%    0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    15 May 2017
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    string FILE_NAME, the name of the ASCII PGM file to be created.
%
%    string COMMENT, a comment.
%
%    integer WIDTH, HEIGHT, the number of columns and rows of data.
%
%    integer MAXVAL, the maximum value allowed.
%
%    integer GRAY(HEIGHT,WIDTH) is the gray scale data.
%
  fid = fopen ( file_name, 'wt' );

  if ( fid < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'PGMA_WRITE - Fatal error!\n' );
    fprintf ( 1, '  Could not open the output file.\n' );
    error ( 'PGMA_WRITE - Fatal error!' );
    return;
  end
%
%  First line identifies the file as an ASCII PGM file.
%
  fprintf ( fid, 'P2\n' );
%
%  Second line is a comment with the filename and creator.
%
  fprintf ( fid, '#%s\n', comment );
%
%  Third line holds HEIGHT and WIDTH.
%
  fprintf ( fid, '%d %d\n', height, width );
%
%  Fourth line contains the maximum gray value.
%
  fprintf ( fid, '%d\n', maxval );
%
%  Subsequent lines contain the gray values, no more than 10 to a line.
%
  for i = 1 : height
    for j = 1 : width
      fprintf ( fid, '%d ', gray(i,j) );
      if ( j == width || rem ( j, 10 ) == 0 )
        fprintf ( fid, '\n' );
      end
    end
  end

  fclose ( fid );

  return
end
