function restart_write ( chain_num, fit, gen_num, par_num, ...
  restart_write_filename, z )

%*****************************************************************************80
%
%% RESTART_WRITE writes a restart file.
%
%  Discussion:
%
%    Only data for the final generation is written.
%
%  Licensing:
%
%    This code is distributed under the GNU LGPL license.
%
%  Modified:
%
%    23 January 2018
%
%  Author:
%
%    Original FORTRAN90 version by Guannan Zhang.
%    MATLAB version by John Burkardt.
%
%  Input parameters:
%
%    Input, integer CHAIN_NUM, the total number of chains.
%    3 <= CHAIN_NUM.
%
%    Input, real FIT(CHAIN_NUM,GEN_NUM), the likelihood of
%    each sample.
%
%    Input, integer GEN_NUM, the total number of generations.
%    2 <= GEN_NUM.
%
%    Input, integer PAR_NUM, the total number of parameters.
%    1 <= PAR_NUM.
%
%    Input, string RESTART_WRITE_FILENAME, the name of the 
%    restart file.
%
%    Input, real Z(PAR_NUM,CHAIN_NUM,GEN_NUM), the Markov chain 
%    sample data.
%      
  restart_unit = fopen ( restart_write_filename, 'wt' );

  if ( restart_unit < 0 )
    fprintf ( 1, '\n' );
    fprintf ( 1, 'RESTART_WRITE - Fatal error!\n' );
    fprintf ( 1, '  Could not open "%s"\n', restart_write_filename );
    error ( 'RESTART_WRITE - Fatal error!\n' );
  end

  fprintf ( restart_unit, 'DREAM.M:Parameter_values_for_restart\n' );

  for j = 1 : chain_num
    fprintf ( restart_unit, ' %7d      %14.7e    ', j, fit(j,gen_num) );
    for i = 1 : par_num
      fprintf ( restart_unit, '  %14.7e', z(i,j,gen_num) );
    end
    fprintf ( restart_unit, '\n' );
  end
      
  fclose ( restart_unit );

  fprintf ( 1, '\n' );
  fprintf ( 1, 'RESTART_WRITE:\n' );
  fprintf ( 1, '  Created restart file "%s"\n', restart_write_filename );

  return
end
