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)    :: arraydims   = (/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               ! number of stanzas
integer(hid_t)                     :: file_id, plist_id, space, dset ! Handles
integer                            :: hdferr
integer(hsize_t), dimension(1:1)   :: ms_dims = (/ms_dim0/)
integer(hsize_t), dimension(1:2)   :: maxdims

integer(hid_t)  :: s1_tid, s2_tid, s3_tid, dt1_id, dt2_id
integer(8)      :: sz1, sz2, sz, offset

real(4), target :: denarray(2), denarray0(3)

  
 denarray = (/3.2, 4.1/)
 denarray0 = (/9.8, 7.6, 5.1/)

 ! initialize FORTRAN interface
 call h5open_f(hdferr)

 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 (H%F_ACC_TRUNC_F)
 call h5fcreate_f(filename, H5F_ACC_TRUNC_F, file_id, hdferr)

 call h5screate_simple_f(1, ms_dims, space, hdferr)

 ! create 2 arrays "s1_tid" and "s2_tid"
 call H5Tarray_create_f(H5T_NATIVE_REAL, 1, arraydims, s1_tid, hdferr);
 call H5Tarray_create_f(H5T_NATIVE_REAL, 1, arraydims1, s2_tid, hdferr);

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

 ! create the compound datatype "s3_tid"  which will embrace the "s1_tid" and "s2_tid" arrays
 call H5Tcreate_f(H5T_COMPOUND_F, sz, s3_tid, hdferr);

 ! insert arrays into the compound datatype
 offset = 0
 call H5Tinsert_f(s3_tid, "denarray", offset, s1_tid, hdferr)
 offset = offset + sizeof(denarray)
 call H5Tinsert_f(s3_tid, "denarray0", offset, s2_tid, hdferr)

 ! Create the dataset and write the array data to it.

 call h5dcreate_f(file_id, dsetname1, s3_tid, space, dset, hdferr)

 call h5tcreate_f(H5T_COMPOUND_F, sz1, dt1_id, hdferr)
 offset = 0
 call h5tinsert_f(dt1_id, "denarray", offset, H5T_NATIVE_REAL, hdferr)
     
 call h5tcreate_f(H5T_COMPOUND_F, sz2, dt2_id, hdferr)
 offset = offset + sz1
 call h5tinsert_f(dt2_id, "denarray0", offset, H5T_NATIVE_REAL, hdferr)

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


 call h5dclose_f(dset, hdferr)
 call h5dclose_f(dset, hdferr)
 call h5sclose_f(space, hdferr)
 call h5fclose_f(file_id, hdferr)



end program complexcompound

