/*  
 *  This example creates and writes dataset to the HDF5 file.
 *  Elements of the datasets have an array datatype.
 */
 
#include <hdf5.h>

#define FILE        "SDS_array_type.h5"
#define DATASETNAME "IntArray" 
#define ARRAY_DIM1     5                      /* array dimensions and rank */
#define ARRAY_DIM2     4 
#define ARRAY_RANK     2 
#define SPACE_DIM     10                      /* dataset dimensions and rank */ 
#define RANK  1 

int
main (void)
{
    hid_t       file, dataset;         /* file and dataset handles */
    hid_t       datatype, datatypew, dataspace;   /* handles */
    hsize_t     sdims[] = {SPACE_DIM};              /* dataset dimensions */
    hsize_t     adims[] = {ARRAY_DIM1, ARRAY_DIM2}; /* array dimensions */
    hsize_t     adims_out[2]; 
    herr_t      status;                             
    int         data[SPACE_DIM][ARRAY_DIM1][ARRAY_DIM2];          /* data to write */
    int         k, i, j;
    int         array_rank_out; 

    /* 
     * Data  and output buffer initialization. 
     */
    for (k = 0; k < SPACE_DIM; k++) {
      for (j = 0; j < ARRAY_DIM1; j++) {
	for (i = 0; i < ARRAY_DIM2; i++)
               data[k][j][i] = k;
      }
    }     
    /*
     * Create a new file using H5F_ACC_TRUNC access,
     * default file creation properties, and default file
     * access properties.
     */
    file = H5Fcreate(FILE, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);

    /*
     * Describe the size of the array and create the data space for fixed
     * size dataset. 
     */
    dataspace = H5Screate_simple(RANK, sdims, NULL); 

    /* 
     * Define array datatype for the data in the file.
     */
    datatype = H5Tarray_create(H5T_STD_I32BE, ARRAY_RANK, adims, NULL);
    datatypew = H5Tarray_create(H5T_NATIVE_INT, ARRAY_RANK, adims, NULL);

    /*
     * Create a new dataset within the file using defined dataspace and
     * datatype and default dataset creation properties.
     */
    dataset = H5Dcreate(file, DATASETNAME, datatype, dataspace,
			H5P_DEFAULT);
    printf ("H5Dcreate returns: %i\n", dataset);

    /*
     * Write the data to the dataset using default transfer properties.
     */
    status = H5Dwrite(dataset, datatypew, H5S_ALL, H5S_ALL,
		      H5P_DEFAULT, data);
    printf ("H5Dwrite returns: %i\n", status);


    /*
     * Close/release resources.
     */
    H5Sclose(dataspace);
    H5Tclose(datatype);
    H5Dclose(dataset);
    /*
     * Reopen dataset, and return information about its datatype.
     */
    dataset = H5Dopen(file, DATASETNAME);
    datatype = H5Dget_type(dataset);
    array_rank_out = H5Tget_array_ndims(datatype);
    status = H5Tget_array_dims(datatype, adims_out, NULL); 
    printf(" Array datatype rank is %d \n", array_rank_out);
    printf(" Array dimensions are %d x %d \n", (int)adims_out[0], (int)adims_out[1]);

    H5Tclose(datatype);
    H5Dclose(dataset);
    H5Fclose(file);
 
    return 0;
}     
