program dumptree

! Example of how to write a merger tree.  
! This example needs some data which it reads in from an existing HDF file,
! which makes this whole exercise a bit pointless, but pretend that the data
! was created some other way and now needs to be written out.
! This is not complete, but it gives the general idea.

! The idea is to make this calling routine use Fortran-95 only and hide all the
! underlying HDF libraries and conversions to/from C from the user.

  ! Load function interfaces
  use mt

  ! This defines the merger tree structures as per the standard
  ! and defines some global vairables.
  use mt_data

  implicit none

  character*(csize) :: infile='data/test.hdf5'
  character*(csize) :: outfile='data/dumptest_Fortran.hdf5'
  character*(csize) :: description='Test data set created by dumptree.f90'
  character(c_char) :: root*(csize)

  ! Create some mock data to write
  call read_mock_data(infile)

  ! Open data file
  ! call mt_open(file,ioflags,description)
  ! Inputs: 
  !    file - file name
  !    ioflags - read/write string;
  !           'r' file must exist and will be opened readonly
  !           'rw' file must exist and will be opened for writing
  !           'wo' file will be created, over-writing any existing file
  !           'w' file will be created, will fail if already exists
  !    description - comment to be written/appended to file
  ! NOTE: description cannot be replaced with a string constant
  call mt_open(outfile,'wo',description)

  ! Write top-level attribhutes
  root=mt_str_f2c('.')
  call mt_aset_float(mt_fid,root,mt_str_f2c('BoxsizeMpc'),box);
  call mt_aset_float(mt_fid,root,mt_str_f2c('H100'),h100);
  call mt_aset_float(mt_fid,root,mt_str_f2c('OmegaBaryon'),omega_baryon);
  call mt_aset_float(mt_fid,root,mt_str_f2c('OmegaCDM'),omega_cdm);
  call mt_aset_float(mt_fid,root,mt_str_f2c('OmegaLambda'),omega_lambda);
  call mt_aset_float(mt_fid,root,mt_str_f2c('Sigma8'),sigma8);
  call mt_aset_string(mt_fid,root,mt_str_f2c('Title'),title);

  ! A general routine to write the Snap table out to the hdf file
  call mt_dump_snaptable()

  ! A general routine to write the MergerTree data out to the hdf file
  ! In this test data the HaloIndexOffset is 0 (default fortran value is 1)
  HaloIndexOffset=0
  call mt_dump_mergertree()

  ! Close file
  call mt_close()

  ! Tidy up.  All this does is deallocate some arrays.
  call mt_tidy()

end program dumptree
