/*
   h5cmpstr.c - String in Compound Datatype 
 */

#include "hdf5.h"

#define FILE          "cstr.h5"
#define DATASETNAME   "Compound String"
#define LENGTH        10
#define RANK          1

typedef struct s1_t {
  char  astr[10];
  char  bstr[13];
} s1_t;

s1_t  s1[LENGTH];
hid_t s1_tid; 

int
main(void)
{

    hid_t   file, dataset, space, atype, btype, s1_tid;
    herr_t  status;
    hsize_t dim[]= {LENGTH};
    int  i;
    size_t  size;

    for (i=0; i< LENGTH; i++)
    {
       strcpy (s1[i].astr, "Astronomy ");
       s1[i].astr[9]='\0';
       strcpy (s1[i].bstr, "Biochemistry ");
       s1[i].bstr[12]='\0';
    }

    /*
     * Create the data space.
     */
    space = H5Screate_simple (RANK, dim, NULL);
    printf ("H5Screate_simple: %i\n", space);

    /*
     * Create the file.
     */
    file = H5Fcreate(FILE, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
    printf ("H5Fcreate: %i\n", file);

    /*
     * Create the memory data type. 
     */

    atype = H5Tcopy (H5T_C_S1);
    size = 10;
    status = H5Tset_size (atype, size);

    btype = H5Tcopy (H5T_C_S1);
    size = 13;
    status = H5Tset_size (btype, size);

    s1_tid = H5Tcreate (H5T_COMPOUND, sizeof(s1_t));
    printf ("H5Tcreate: %i\n", s1_tid);

    status = H5Tinsert(s1_tid, "a_string", HOFFSET(s1_t, astr), atype);
    printf ("H5Tinsert (a_string): %i\n", status);
    status = H5Tinsert(s1_tid, "b_string", HOFFSET(s1_t, bstr), btype);
    printf ("H5Tinsert (b_string): %i\n", status);

    /* 
     * Create the dataset.
     */
    dataset = H5Dcreate(file, DATASETNAME, s1_tid, space, H5P_DEFAULT);
    printf ("H5Dcreate: %i\n", dataset);

    /*
     * Wtite data to the dataset; 
     */
    status = H5Dwrite(dataset, s1_tid, H5S_ALL, H5S_ALL, H5P_DEFAULT, s1);
    printf ("H5Dwrite: %i\n", status);

    /*
     * Release resources
     */
    status = H5Tclose(atype);
    printf ("H5Tclose (atype): %i\n", status);
    status = H5Tclose(btype);
    printf ("H5Tclose (btype): %i\n", status);
    status = H5Tclose(s1_tid);
    printf ("H5Tclose (s1_tid): %i\n", status);
    status = H5Sclose(space);
    printf ("H5Sclose (space): %i\n", status);
    status = H5Dclose(dataset);
    printf ("H5Dclose (dataset): %i\n", status);
    status = H5Fclose(file);
    printf ("H5Fclose (file): %i\n", status);
 
}

