function chain_write ( chain_filename, chain_num, fit, gen_num, par_num, z )

%*****************************************************************************80
%
%% CHAIN_WRITE writes samples of each chain to separate files.
%
%  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, string CHAIN_FILENAME, the "base" filename
%    to be used for the chain files.  If this is the empty string '',
%    then the chain files will not be written.  This name should 
%    include a string of 0's which will be replaced by the chain 
%    indices.  For example, "chain000.txt" would work as long as the
%    number of chains was 1000 or less.
%
%    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, real Z(PAR_NUM,CHAIN_NUM,GEN_NUM), the Markov chain 
%    sample data.
%

%
%  Write parameter samples of all chains.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'CHAIN_WRITE:\n' );

  for j = 1 : chain_num

    chain_filename = filename_inc ( chain_filename );

    chain_unit = fopen ( chain_filename, 'wt' );
 
    if ( chain_unit < 0 )
      fprintf ( 1, '\n' );
      fprintf ( 1, 'CHAIN_WRITE - Fatal error!\n' );
      fprintf ( 1, '  Could not open "%s"\n', chain_filename );
      error ( 'CHAIN_WRITE - Fatal error!\n' );
    end

    fprintf ( chain_unit, ...
      'DREAM.M:Parameters_and_log_likelihood_for_chain_#%d', j );

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

    fclose ( chain_unit );

    fprintf ( 1, '  Created file "%s"\n', chain_filename );

  end

  return
end
