program hdfproblem
 use hdf5
 use h5lt
 implicit none
 include 'mpif.h'

 integer :: ierr, npid, maxprocs

 character(len=14), parameter :: filename = "scalar_flux.h5" ! File name
 character(LEN=11), parameter :: dsetname = "scalar_flux"

 integer :: rank, info
 integer(hid_t) :: file_id, dspace_id, dset_id, plist_id, mspace_id 
 integer(hsize_t), dimension(4) :: dims, offset, cnt, block, write_size

 integer :: im, jm, km, igm
 real,dimension(:,:,:,:),allocatable :: phim
 integer :: kmloc(2)

 call mpi_init(ierr)
 call mpi_comm_rank(mpi_comm_world,npid,ierr)
 call mpi_comm_size(mpi_comm_world,maxprocs,ierr)

 im=8
 jm=8
 km=8
 igm=67
 kmloc(1)=4; kmloc(2)=4

 allocate(phim(im,jm,km/2,igm)); phim=1
 if(npid == 1) phim=2

 ! Initialize FORTRAN interface.
 call h5open_f(ierr)

 info = MPI_INFO_NULL                                                                                                                                                                                          
 ! Create a new file property list using defaults.
 call h5pcreate_f(H5P_FILE_ACCESS_F, plist_id, ierr)
 call h5pset_fapl_mpio_f(plist_id, mpi_comm_world, info, ierr)

 ! Create the file
 call h5fcreate_f(filename, H5F_ACC_TRUNC_F, file_id, ierr, access_prp = plist_id)
 call h5pclose_f(plist_id, ierr)

 ! Create the file dataspace.
 rank = 4
 dims = (/im,jm,km,igm/) 
 call h5screate_simple_f(rank, dims, dspace_id, ierr)

 ! Create the dataset with default properties.
 call h5dcreate_f(file_id, dsetname, H5T_NATIVE_REAL, dspace_id, dset_id, ierr)

 ! Select the hyperslab in the file
 offset = (/0,0,sum(kmloc(1:npid)),0/)
 block  = (/im,jm,kmloc(npid+1),1/)
 cnt    = (/1,1,1,igm/)
 call h5sselect_hyperslab_f (dspace_id, H5S_SELECT_SET_F, offset, cnt, ierr, block=block)
 call h5screate_simple_f(rank, block*cnt, mspace_id, ierr)

 ! Create property list for collective dataset write
!call h5pcreate_f(H5P_DATASET_XFER_F, plist_id, ierr) 
!call h5pset_dxpl_mpio_f(plist_id, H5FD_MPIO_COLLECTIVE_F, ierr)

 ! Write the data set collectively
 write_size  = (/im,jm,kmloc(npid+1),igm/)
!write(*,*) "NPID:",npid," WRITE_SIZE:",write_size
!call h5dwrite_f(dset_id, H5T_NATIVE_REAL, phim(:,:,:,:), write_size, ierr, &
!                file_space_id = dspace_id, xfer_prp = plist_id)
 call h5dwrite_f(dset_id, H5T_NATIVE_REAL, phim(:,:,:,:), write_size, ierr, &
                 file_space_id = dspace_id, mem_space_id = mspace_id)

 ! Append Attributes
 call h5ltset_attribute_int_f(file_id, dsetname, "IM" , (/im/) , 1, ierr)
 call h5ltset_attribute_int_f(file_id, dsetname, "JM" , (/jm/) , 1, ierr)
 call h5ltset_attribute_int_f(file_id, dsetname, "KM" , (/km/) , 1, ierr)
 call h5ltset_attribute_int_f(file_id, dsetname, "IGM", (/igm/), 1, ierr)

 ! Close the resources
 call h5sclose_f(dspace_id, ierr)
 call h5dclose_f(dset_id, ierr)
!call h5pclose_f(plist_id, ierr)
 call h5fclose_f(file_id, ierr)

 ! Close the Fortran interface
 CALL h5close_f(ierr)

 call mpi_finalize(ierr)

end program
