module h5file

  use mpi
  use hdf5
  implicit none
  
contains

subroutine h5write(path, data, nx, ny, nz, comm)

  character*(*) :: path 
  integer :: nx, ny, nz
  double precision, dimension(0:nx,0:ny,0:nz) :: data

  integer :: comm, ierr,  rank, size, rlen, ii
  integer, parameter :: iounit = 10
  character(len=6) :: crank
  character(len=100) :: filename
  character(len=MPI_MAX_PROCESSOR_NAME) :: hostname
  real* 8  :: start, finish
  
  
  call MPI_Comm_size(comm, size, ierr)
  call MPI_Comm_rank(comm, rank, ierr)

  write(crank, "(I0.6)") rank
  filename = trim(path)//crank//'.h5'

  call MPI_Get_processor_name(hostname, rlen, ierr)
  write(*,*) 'node : ', hostname, 'opening  hdf5 file: ', filename 

  call MPI_Barrier(comm, ierr)  
  
  do ii = 0, size
     if ( rank == ii ) then
       call write_3d(data, filename) 
     else
     end if
  end do
  
end subroutine h5write

subroutine h5delete(path, comm)

  implicit none

  character *(*) :: path
  integer, parameter :: iounit = 15
  integer :: comm, ierr, rank, size
  integer :: stat
  character(len=6) :: crank
  character(len=50) :: filename
  real*8    start, finish

  call MPI_Comm_size(comm, size, ierr)
  call MPI_Comm_rank(comm, rank, ierr)

  write(crank, "(I0.6)") rank
  filename = trim(path)//crank//'.h5'

  open(unit=iounit, iostat=stat, file=filename, status='old')
  if (stat.eq.0) close(unit=iounit, status='delete')

end subroutine h5delete

subroutine write_3d(buf, filename)
  integer, parameter :: ndims = 3
  character( len=* ), intent( in ) :: filename
  character( len=4 ), parameter :: dsetname = "vort"  
  double precision, dimension( :,:,: ), intent( in ) :: buf

  integer(hsize_t)   :: xshape(ndims)
  integer(hsize_t)   :: chunk(ndims)

  integer(hid_t)     :: file_id
  integer(hid_t)     :: group_id
  integer(hid_t)     :: dset_id
  integer(hid_t)     :: dspace_id
  integer(hid_t)     :: dtype_id
  integer(hid_t)     :: prop_id
  integer            :: ierror
  
  xshape = shape(buf)
  chunk  = shape(buf)
  dtype_id = H5T_NATIVE_DOUBLE

  ! Initialize FORTRAN interface of HDF5.
  call h5open_f(ierror)
  ! Create a new file.
  call h5fcreate_f (filename, H5F_ACC_TRUNC_F, file_id, ierror)  
  ! Create dataspace
  call h5screate_simple_f(ndims, xshape, dspace_id, ierror)
  ! Create dataset, prop. list, gzip, chunk size
  call h5pcreate_f(H5P_DATASET_CREATE_F, prop_id, ierror)
  !call h5pset_deflate_f(prop_id, comp_level, ierror)
  !call h5pset_chunk_f(prop_id, ndims, chunk, ierror)
  ! Create dataset in file
  call h5dcreate_f(file_id, dsetname, dtype_id, dspace_id, dset_id, ierror, prop_id)
  ! Write to file
  call h5dwrite_f(dset_id, dtype_id, buf, xshape, ierror)
  ! Close prop. list
  call h5pclose_f(prop_id, ierror)
  ! Close dset
  call h5dclose_f(dset_id, ierror)
  ! Close dataspace
  call h5sclose_f(dspace_id, ierror)
end subroutine write_3d



end module h5file 



