/***********************************************************************
*  bitfield datatype example                                           *
*  blw 6/5/03                                                          *
***********************************************************************/

/* HDF5 Library                                                       */
#include "hdf5.h"

/* System libraries to include                                        */
#include <stdlib.h>
#include <assert.h>

/* Name of file for database output                                   */
#define DATAFILE "bitfield.h5"

/* Name of dataset to create in datafile                              */
#define DATASETNAME    "Bitfield"

int
main(void) {

   hid_t                file, dataset;       /* Resource handles      */
   hid_t                datatype,dataspace;  /* Resource handles      */
   herr_t               status;              /* Error checking status */
   size_t               i;                   /* Loop control variable */
   hsize_t              bufsize;             /* Buffer size           */
   unsigned char        buf[8];              /* Data buffer           */

   /* Create the file for data output                                 */
   file = H5Fcreate(DATAFILE, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);

   /* Set the buffer size                                             */
   bufsize = sizeof(buf);
   
   /* Create the datatype                                             */
   datatype = H5Tcopy(H5T_STD_B8LE);
   assert (datatype >= 0);

   /* Set the datatype precision                                      */
   status = H5Tset_precision(datatype, 4);
   assert (status >= 0);

   /* Set the datatype offset                                         */
   status = H5Tset_offset(datatype, 2);
   assert (status >= 0);

   /* Set the datatype padding                                        */
   status = H5Tset_pad(datatype, H5T_PAD_ZERO, H5T_PAD_ZERO);
   assert (status >= 0);

   /* Create the dataspace                                            */
   dataspace = H5Screate_simple(1, &bufsize, NULL);
   assert (dataspace >= 0);

   /* Create the dataset                                              */
   dataset = H5Dcreate(file, DATASETNAME, datatype, dataspace,
		   H5P_DEFAULT);
   assert (dataset >= 0);

   /* Fill the buffer with data                                       */
   for (i=0; i<bufsize; i++) {
	   buf[i] = i ;
   }

   /* Write the data out to the dataset                               */
   status = H5Dwrite(dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT,
		   buf);
   assert (status >= 0);
   
   /* Close resource handles                                          */
   status = H5Sclose (dataspace);
   assert (status >= 0);

   status = H5Tclose(datatype);
   assert (status >= 0);

   status = H5Dclose (dataset);
   assert (status >= 0);

   status = H5Fclose (file);
   assert (status >= 0);
}
