program complexcompound

use hdf5

implicit none

! This is the name of the data file we will read. 
character (len = 9), parameter :: filename  = "ep_res.h5"
character (len = 7), parameter :: dsetname0 = "ep_data"     ! name of the Ecopath base dataset
character (len = 7), parameter :: dsetname1 = "ms_data"     ! name of the Ecopath multistanza dataset

integer(8), parameter             :: arraydim0   = 2
integer(hsize_t), DIMENSION(1)    :: arraydims0  = (/arraydim0/)
integer(8), parameter             :: arraydim1   = 3
integer(hsize_t), DIMENSION(1)    :: arraydims1  = (/arraydim1/)

! in-subroutine variable declarations for ms_data
integer          , parameter       :: ms_dim0 = 1
integer                            :: rank = 1
integer(hid_t)                     :: file_id, plist_id, dspace_id, dset_id, dtype_id ! Handles
integer                            :: hdferr
integer(hsize_t), dimension(1:1)   :: ms_dims = (/ms_dim0/)

integer(hid_t)  :: s1t_id, s2t_id, memtype, dt1_id, dt2_id
integer(8)      :: sz1, sz2, sz, offset
real(4), target :: denarray(2), denarray0(3)
type(c_ptr) :: f_ptr
  
 denarray = (/3.2, 4.1/)
 denarray0 = (/9.8, 7.6, 5.1/)

 ! initialize FORTRAN interface
 call h5open_f(hdferr)

 ! set property to preserve partially initialized fields of data
 call h5pcreate_f(H5P_DATASET_XFER_F, plist_id, hdferr)
 call h5pset_preserve_f(plist_id, .TRUE., hdferr)

 ! create file, if it already exists overwrite (H5F_ACC_TRUNC_F)
 call h5fcreate_f(filename, H5F_ACC_TRUNC_F, file_id, hdferr)

 ! create the dataspace
 call h5screate_simple_f(rank, ms_dims, dspace_id, hdferr)

 ! create 2 arrays "s1t_id" and "s2t_id"
 call H5Tarray_create_f(H5T_NATIVE_REAL, rank, arraydims0, s1t_id, hdferr);
 call H5Tarray_create_f(H5T_NATIVE_REAL, rank, arraydims1, s2t_id, hdferr);

 ! get size of each array
 call H5Tget_size_f(s1t_id, sz1, hdferr)
 call H5Tget_size_f(s2t_id, sz2, hdferr)
 sz = sz1 + sz2

 ! create the compound datatype "memtype" includes  "s1t_id" and "s2t_id"
 call H5Tcreate_f(H5T_COMPOUND_F, sz, memtype, hdferr);

 ! insert arrays into the compound datatype
 offset = 0
 call H5Tinsert_f(memtype, "denarray", offset, s1t_id, hdferr)
 offset = offset + sz1
 call H5Tinsert_f(memtype, "denarray0", offset, s2t_id, hdferr)

 ! Create the dataset and write the array data to it.
 call h5dcreate_f(file_id, dsetname1, memtype, dspace_id, dset_id, hdferr)

 ! Create memory types
 call h5tcreate_f(H5T_COMPOUND_F, sz1, dt1_id, hdferr)
 offset = 0
 call h5tinsert_f(dt1_id, "denarray", offset, s1t_id, hdferr)
     
 call h5tcreate_f(H5T_COMPOUND_F, sz2, dt2_id, hdferr)
 offset = 0
 call h5tinsert_f(dt2_id, "denarray0", offset, s2t_id, hdferr)

 call h5dwrite_f(dset_id, dt1_id, denarray, ms_dims, hdferr, xfer_prp = plist_id)
 call h5dwrite_f(dset_id, dt2_id, denarray0, ms_dims, hdferr, xfer_prp = plist_id)

end program complexcompound

