// Routines to handle attributes

#include "hdf5.h"
#include "hdf5_hl.h"
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>

//---------------------------------------------

int mt_aget_int(hid_t hid, char *name, char *attr, int *value) {

  if (H5Aexists_by_name(hid, name, attr, H5P_DEFAULT) == 1)
    return (int)H5LTget_attribute_int(hid, name, attr, value);
  else {
    printf("***mt_aget_int: attribute %s does not exist\n",attr);
    return -1;
  }

}

//---------------------------------------------

int mt_aset_int(hid_t hid, char *name, char *attr, int value) {

  return (int)H5LTset_attribute_int(hid, name, attr, &value, 1);

}

//---------------------------------------------

int mt_aget_float(hid_t hid, char *name, char *attr, float *value) {

  if (H5Aexists_by_name(hid, name, attr, H5P_DEFAULT) == 1)
    return (int)H5LTget_attribute_float(hid, name, attr, value);
  else {
    printf("***mt_aget_float: attribute %s does not exist\n",attr);
    return -1;
  }

}

//---------------------------------------------

int mt_aset_float(hid_t hid, char *name, char *attr, float value) {

  return (int)H5LTset_attribute_float(hid, name, attr, &value, 1);

}

//---------------------------------------------

int mt_aget_string(hid_t hid, char *name, char *attr, char *value) {

  if (H5Aexists_by_name(hid, name, attr, H5P_DEFAULT) == 1) {
      hid_t att = H5Aopen_name(hid, attr);
      hid_t ftype = H5Aget_type(att);
      if(H5Tis_variable_str(ftype)) {
	  char *str;
	  herr_t r = H5Aread(att, ftype, &str);
	  H5Aclose(att);
	  if (r < 0) return -1;
	  strcpy(value, str);
	  free(str);
	  return 0;
      }
      else {
	  herr_t r = H5Aread(att, ftype, value);
	  H5Aclose(att);
	  return r < 0 ? -1 : 0; 
      }
  }
  else {
    printf("***mt_aget_string: attribute %s does not exist\n",attr);
    return -1;
  }

}

//---------------------------------------------

int mt_aset_string(hid_t hid, char *name, char *attr, char *value) {

  return (int)H5LTset_attribute_string(hid, name, attr, value);

}
