/* 
 * This example shows how to create a dataset with the variable length datatype
 * using default functions for memory management.
 */

#include <hdf5.h>

#define FILE   "vltypes.h5"

/* 1-D dataset with fixed dimensions */
#define SPACE_NAME  "Space"
#define SPACE_RANK	1
#define SPACE_DIM	4


int main(void)

{   
    hvl_t wdata[SPACE_DIM];   /* Information to write */
    hvl_t rdata[SPACE_DIM];   /* Information read in */
    hid_t		fid;        /* HDF5 File ID */  
    hid_t		dataset;    /* Dataset ID */
    hid_t		sid;       /* Dataspace ID */
    hid_t		tid;       /* Datatype ID */
    hsize_t		dims[] = {SPACE_DIM};
    uint       i,j;        /* counting variables */
    herr_t		ret;		/* Generic return value		*/

    /*
     * Allocate and initialize VL data to write 
     */
    for(i=0; i<SPACE_DIM; i++) {

        wdata[i].p= (unsigned int *)malloc((i+1)*sizeof(unsigned int));
        wdata[i].len=i+1;
        for(j=0; j<(i+1); j++)
            ((unsigned int *)wdata[i].p)[j]=i*10+j;
    } /* end for */

    /* 
     * Create file. 
     */
    fid = H5Fcreate(FILE, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);

    /* 
     * Create dataspace for datasets. 
     */
    sid = H5Screate_simple(SPACE_RANK, dims, NULL);

    /* 
     * Create a datatype to refer to. 
     */
    tid = H5Tvlen_create (H5T_NATIVE_UINT);

    /* 
     * Create a dataset. 
     */
    dataset=H5Dcreate(fid, "Dataset", tid, sid, H5P_DEFAULT);

    /* 
     * Default memory allocation function (C language malloc function) 
     * will be used to manage memory. 
     */
      
    /* 
     * Write dataset to disk. 
     */
    ret=H5Dwrite(dataset, tid, H5S_ALL, H5S_ALL, H5P_DEFAULT, wdata);

    /* 
     * Read dataset from disk. 
     */
     ret = H5Dread(dataset, tid, H5S_ALL, H5S_ALL, H5P_DEFAULT, rdata);

    /* 
     * Display data read in 
     */
    for(i=0; i<SPACE_DIM; i++) {
        printf("%d-th element length is %d \n", i, (unsigned) rdata[i].len);
        for(j=0; j<rdata[i].len; j++) {
            printf(" %d ",((unsigned int *)rdata[i].p)[j] );   
        } 
        printf("\n"); 
    } /* end for */
   
    /* 
     * Reclaim the read VL data. Default function (C language free function) 
     * will be used to reclaim the space. 
     */
    ret=H5Dvlen_reclaim(tid, sid, H5P_DEFAULT, rdata);

    /* 
     * Reclaim the write VL data.  C language free function will be used 
     * to reclaim space. 
     */
    ret=H5Dvlen_reclaim(tid, sid, H5P_DEFAULT, wdata);

    /* 
     * Close Dataset 
     */
    ret = H5Dclose(dataset);

    /* 
     * Close datatype 
     */
    ret = H5Tclose(tid);

    /* 
     * Close disk dataspace 
     */
    ret = H5Sclose(sid);
    
    /* 
     * Close file 
     */
    ret = H5Fclose(fid);

} 
      
