// Copyright (C) 2010, Guy Barrand. All rights reserved.
// See the file tools.license for terms.

#ifndef toolx_hdf5_group_exists
#define toolx_hdf5_group_exists

#include "hdf5_h"

#include <string>

namespace toolx {
namespace hdf5 {

class group_exists_struct {
public:
  group_exists_struct(const std::string& a_what):m_what(a_what),m_found(false){}
  virtual ~group_exists_struct() {}
protected:
  group_exists_struct(const group_exists_struct& a_from):m_what(a_from.m_what),m_found(a_from.m_found){}
  group_exists_struct& operator=(const group_exists_struct&){return *this;}
public:
  std::string m_what;
  bool m_found;
};

inline herr_t group_exists_visit(hid_t a_id,const char* a_name,void* a_tag){ //a_id = parent of a_name object.
  group_exists_struct* visitor = (group_exists_struct*)a_tag;
  H5G_stat_t statbuf;
  ::H5Gget_objinfo(a_id,a_name,0,&statbuf);
  switch(statbuf.type) {
  case H5G_GROUP:{
    if(a_name==visitor->m_what) {visitor->m_found=true;return 0;} //found
  }break;
  default:
    break;
  }
  return 0;
}

inline bool group_exists(hid_t a_file_id,const std::string& a_name) {
  group_exists_struct visitor(a_name);
  ::H5Giterate(a_file_id,".",NULL,group_exists_visit,&visitor);
  return visitor.m_found;
}

}}

#endif
