#include "gdal_priv.h"
#include <iostream>

static void read_dataset(const char *objpath)
{
  GDALDataset *poDataset;

  // open a child object that corresponds to an HDF5 dataset
  poDataset = (GDALDataset *)GDALOpen(objpath, GA_ReadOnly);
  if (!poDataset) {
    std::cerr << "cannot open " << objpath << std::endl;
    return;
  }

  // read dimension sizes
  int xsize = poDataset->GetRasterXSize();
  int ysize = poDataset->GetRasterYSize();
  std::cout << "X size = " << xsize << ", " << "Y size = " << ysize << std::endl;

  // read elements
  float *buffer = new float[xsize * ysize];
  GDALRasterBand *rb = poDataset->GetRasterBand(1);
  rb->RasterIO(GF_Read, 0, 0, xsize, ysize, buffer, xsize, ysize, GDT_Float32, 0, 0);
  for (int j = 0; j < ysize; ++j) {
    for (int k = 0; k < xsize; ++k) {
      std::cout << buffer[j * xsize + k] << " ";
    }
    std::cout << std::endl;
  }
  delete [] buffer;
}

static void read_ae_rngd(const char *filename)
{
  GDALDataset *poDataset;

  // open an HDF5 file
  poDataset = (GDALDataset *)GDALOpen(filename, GA_ReadOnly);
  if (!poDataset) {
    std::cerr << "cannot open " << filename << std::endl;
    return;
  }

  // dump the first HDF5 attribute
  char **metadata = poDataset->GetMetadata("");
  if (metadata) {
    std::cout << "metadata: " << *metadata << std::endl;
  }

  // open the first child object
  char **children = poDataset->GetMetadata("SUBDATASETS");
  if (children) {
    const char *objpath = strstr(*children, "=");
    objpath++;

    std::cout << "child: " << objpath << std::endl;
    read_dataset(objpath);
  }
}

int main(int argc, char **argv)
{
  GDALAllRegister();

  read_ae_rngd("AMSR_E_L3_RainGrid_B05_200707.h5");

  return 0;
}

// vim:ts=8:sw=2:sts=2

