#include "hdf5.h"
#define FNAME "vlchar.h5"
#define DNAME "Dataset"

int main () {
    hid_t  dataspace, datatype, file_id, dataset;
    hvl_t data [2], rdata[2];
    hsize_t dims[1]= {2}, size;
    herr_t status;
    int i,j;
    char * ptr;


    for (i=0; i<2; i++)
    {
      data[i].len = i+5;
      ptr = (char *) malloc (data[i].len);
      data[i].p = ptr;
      for (j=0; j < data[i].len; j++)
        ptr[j] = 'a' + i;
    }
          
    file_id = H5Fcreate (FNAME, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
    printf ("file_id = %i\n", file_id);
    dataspace = H5Screate_simple(1, dims, NULL);
    printf ("dataspace = %i\n", dataspace);
    printf ("datatype = %i\n", datatype);
    datatype = H5Tvlen_create (H5T_NATIVE_CHAR);
    dataset = H5Dcreate(file_id, DNAME, datatype, dataspace, H5P_DEFAULT);
    printf ("dataset = %i\n", dataset);

    status =  H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, data); 
    printf ("H5Dwrite returns = %i\n", status);
    status =  H5Dread(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, rdata); 
    printf ("H5Dread returns = %i\n", status);

    printf ("Data:\n"); 
    for (i=0; i<2; i++)
    {
      ptr = rdata[i].p;
      printf ("  [%i]",i);
      for (j=0; j < rdata[i].len; j++)
         printf ("%c",ptr[j]);
      printf ("\n");
    }  

    status = H5Dvlen_reclaim (datatype, dataspace, H5P_DEFAULT, rdata);
    printf ("H5Dvlen_reclaim (rdata) returns: %i\n", status);
    status = H5Dvlen_reclaim (datatype, dataspace, H5P_DEFAULT, data);
    printf ("H5Dvlen_reclaim (data) returns: %i\n", status);
    status = H5Tclose(datatype);
    printf ("H5Tclose returns = %i\n", status);
    status = H5Dclose(dataset);
    printf ("H5Dclose returns = %i\n", status);
    status = H5Sclose(dataspace);
    printf ("H5Sclose returns = %i\n", status);


    status = H5Fclose (file_id);
    printf ("H5Fclose returns = %i\n", status);
  
}

