function gr_write ( gr, gr_filename, gr_num, par_num, printstep )

%*****************************************************************************80
%
%% gr_write() writes the Gelman-Rubin R statistics into a file.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    23 January 2018
%
%  Author:
%
%    Original FORTRAN90 version by Guannan Zhang.
%    MATLAB version by John Burkardt.
%
%  Input:
%
%    real GR(PAR_NUM,GR_NUM), the Gelman-Rubin R statistic.
%
%    string GR_FILENAME, the name of the file
%    in which values of the Gelman-Rubin statistic will be recorded,
%    or '' if no such file is to be created.
%
%    integer GR_NUM, the number of times the Gelman-Rubin
%    statistic may be computed.
%
%    integer PAR_NUM, the total number of parameters.
%    1 <= PAR_NUM.
%
%    integer PRINTSTEP, the interval between generations on 
%    which the Gelman-Rubin statistic will be computed and written to a file.
%
  gr_unit = fopen ( gr_filename, 'wt' );

  if ( gr_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'GR_WRITE - Fatal error!\n' );
    fprintf ( 1, '  Could not open "%s"\n', gr_filename );
    error ( 'GR_WRITE - Fatal error!\n' );
  end

  fprintf ( gr_unit, ...
    'DREAM.M:Monitored_parameter_interchains_Gelman_Rubin_R_statistic\n' );

  for j = 1 : gr_num
    fprintf ( gr_unit, ' %9d    ', j );
    for i = 1 : par_num
      fprintf ( gr_unit, '  %14.4f', gr(i,j) );
    end
    fprintf ( 1, '\n' );
  end

  fclose ( gr_unit );

  fprintf ( 1, '\n' );
  fprintf ( 1, 'GR_WRITE:\n' );
  fprintf ( 1, '  Created the file "%s"\n', gr_filename );

  return
end
