// File-handling routines

#include <stdarg.h>
#include <stdlib.h>
#include <string.h>

#include "hdf5.h"
#include "hdf5_hl.h"

#include "mt_version.h"

int mt_aget_string(hid_t hid, char *name, char *attr, char *value);
int mt_aset_int(hid_t hid, char *name, char *attr, int value);
hid_t mt_gopen(hid_t hid, char *name);

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

// Flushes a file, closes it, and frees resources

int mt_fclose(hid_t fid) {

  return (int)H5Fclose(fid);

}

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

// Opens a file, writes version numbers, and read/writes a comment

hid_t mt_fopen(char *file, char *ioflags, char *description) {

  char *flag_r, *flag_w, *flag_o;
  hid_t fid, gid;
  char description_in[1024];

  // Search for io attributes
  flag_o=strchr(ioflags,'o');
  flag_r=strchr(ioflags,'r');
  flag_w=strchr(ioflags,'w');

  if (flag_w==NULL) // If write attribute not found then open readonly
    fid = H5Fopen(file, H5F_ACC_RDONLY, H5P_DEFAULT);
  else if (flag_r!=NULL) // Open read/write
    fid = H5Fopen(file, H5F_ACC_RDWR, H5P_DEFAULT);
  else if (flag_o!=NULL) // Open for writing, overwriting any existing file
    fid = H5Fcreate(file, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
  else // Open for writing but fail on existing file
    fid = H5Fcreate(file, H5F_ACC_EXCL, H5P_DEFAULT, H5P_DEFAULT);

  if (fid < 0) {
    fprintf(stderr, "mt_fopen: Can't open file %s with \'%s\' attrributes\n",file,ioflags);
    return -1;
  }

  // Add version and subversion numbers
  int version=VERSION;
  int subversion=SUBVERSION;
  if (flag_w != NULL) {
    // The following call is required or we get a group access failure.
    // The equivalent call with "/" instead of "." works but gives numerous error messages
    gid=mt_gopen(fid,".");
    mt_aset_int(gid,".","Version",version);
    mt_aset_int(gid,".","Subversion",subversion);
  }
    
  // Update file description
  // Save value passed into function
  strcpy(description_in,description);
  strcpy(description,"");
  // If readable file, then recover existing description
  if (flag_r != NULL)
    mt_aget_string(fid,"/","Description",description);
  // If writeable file, then append new description to existing one
  if (flag_w != NULL) {
    if (strcmp(description,"") != 0) strcat(description," ");
    strcat(description,description_in);
    H5LTset_attribute_string(fid, "/", "Description", description);
  }

  return fid;

}
