// Reads a Snapshot Table from an HDF file in the official mt format

#include <stdio.h>
#include <stdlib.h>

// HDF5
#include "hdf5.h"

// Load function prototypes
#include "mt.h"

// Define the structure that we want to read in.
#define SNAPTABLE_INIT
#include "mt_data.h"

int mt_read_snaptable(void) {

  hid_t gid;
  hsize_t nfields;

  // First check to see whether the Snapshots group exists and either open it or make it
  gid=mt_gopen(mt_fid,"Snapshots");

  // Snap table

  // Can't think of any simple way of reading the table in one go
  // Read the table length
  NSnap=mt_treadinfo(gid,"Snap",&nfields);
  if (nfields < snaptable_nfields) {
    printf("***mt_read_snaptable: nfields < snaptable_nfields***\n");
    return -1;
  }
  if (NSnap <= 0) {
    printf("***mt_read_snaptable: NSnap <= 0***\n");
    return -2;
  }

  // Allocate space for the table
  Snap=(struct snaptable_t *)calloc(NSnap,sizeof(*Snap));

  // Read in the table
  mt_tread(gid,"Snap",
	   snaptable_nfields,snaptable_fieldnames,snaptable_field_types,
	   NSnap,Snap);

  // SnapProp table

  // Can't think of any simple way of reading the table in one go
  // Read the table length
  NSnapProp=mt_treadinfo(gid,"SnapProp",&nfields);
  if (nfields < snapprop_nfields) {
    printf("***mt_read_snaptable: nfields < snapprop_nfields***\n");
    return -1;
  }
  if (NSnapProp <= 0) {
    printf("***mt_read_snaptable: NSnapProp <= 0***\n");
    return -2;
  }

  // Allocate space for the table
  SnapProp=(struct snapprop_t *)calloc(NSnapProp,sizeof(*SnapProp));

  // Read in the table
  mt_tread(gid,"SnapProp",
	   snapprop_nfields,snapprop_fieldnames,snapprop_field_types,
	   NSnapProp,SnapProp);

  // Now close the open group
  mt_gclose(gid);

  return 0;

}
