/*
 */

#include "hdf5.h"
#include "malloc.h"

typedef struct s1 {
   int var1;
   char* var2;
   int var3;
} s1;
s1  st[3];

int main(int argc, char* argv[])
{

    int i, len, nCount  = 3;
    char *bptr;
    char *str[] = {"Wake Me up When", "September", "Ends"};
    hsize_t     dims[1], chunkDims[1], ioffset[1], icnt[1];
    herr_t      status, err1, err2;
    hid_t fileId, dataSetId, dataSpaceId, memSpaceId, vlDataTypeId, dataTypeId, pListId;
    hid_t hid_str;

    /*
     Sample 4 -- Write compound data with variable length (vl) character string
    */ 

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

    /* Create the array datatype */

    hid_str = H5Tcopy(H5T_C_S1);
    printf ("H5Tcopy returns: %i\n", hid_str);
    status = H5Tset_size(hid_str, H5T_VARIABLE);
    printf ("H5Tset_size returns: %i\n", status);
    vlDataTypeId = H5Tcopy(hid_str);
    printf ("H5Tcopy returns: %i\n", vlDataTypeId);

    dataTypeId = H5Tcreate(H5T_COMPOUND, sizeof(s1));
    printf ("H5Tcreate returns: %i\n", dataTypeId);
    H5Tinsert(dataTypeId, "var1", HOFFSET(s1,var1), H5T_NATIVE_INT);
    H5Tinsert(dataTypeId, "var2", HOFFSET(s1,var2), vlDataTypeId);
    H5Tinsert(dataTypeId, "var3", HOFFSET(s1,var3), H5T_NATIVE_INT);

    /* Create the dataSpace */
    dims[0] = nCount;
    dataSpaceId = H5Screate_simple(1, dims, NULL);
    printf ("H5Screate_simple returns: %i\n", dataSpaceId);

    /* Create the propertyList  */
    pListId = H5Pcreate(H5P_DATASET_CREATE);

    /* Create the dataSet */
    chunkDims[0] = 1;
    status = H5Pset_chunk(pListId, 1, chunkDims);
    printf ("%i\n", status);
    dataSetId = H5Dcreate(fileId, "/SAMPLE4", dataTypeId, dataSpaceId, pListId);
	status= H5Pclose(pListId);
    printf ("%i\n", status);

    for (i=0; i<nCount; i++)
    {
		st[i].var1 = i+10;
        len = strlen(str[i]);
        if ( (bptr = (char *)malloc(++len * sizeof(char))) )
        {

            strcpy(bptr, str[i]);

            st[i].var2 = (void *)bptr;
        }
		st[i].var3 = (i+1)*10;
    }
    err2 = H5Dwrite(dataSetId, dataTypeId, H5S_ALL, H5S_ALL, H5P_DEFAULT, &st);
    printf ("H5Dwrite returns: %i\n", err2);

    status = H5Dvlen_reclaim(dataTypeId, dataSpaceId, H5P_DEFAULT, &st);


    /* Close everything */
    status = H5Fclose(fileId);    
    printf ("status: %i\n", status);
    status = H5Dclose(dataSetId);
    printf ("status: %i\n", status);
    status = H5Sclose(dataSpaceId);
    printf ("status: %i\n", status);
    status = H5Tclose(vlDataTypeId);
    printf ("status: %i\n", status);
    status = H5Tclose(dataTypeId);
    printf ("status: %i\n", status);
    status = H5Tclose (hid_str);
    printf ("status: %i\n", status);

    return 0;
}



