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

#ifdef HAVE_DEMANGLE
#include <demangle.h>

const char* ezt_demangle(const char* mangled_str) {
  /* todo: add an option to get only the function name */
  /* get the full function prototype (including parameters and return type)  */

  char* res_str = cplus_demangle(mangled_str, DMGL_AUTO | DMGL_PARAMS);

  if (!res_str) {
    /* demangling failed. return the mangled string */
    int len = strlen(mangled_str) + 1;
    res_str = malloc(sizeof(char) * len);
    if(res_str) {
      memcpy(res_str, mangled_str, len*sizeof(char));
    }
  }
  return res_str;
}

#else /* HAVE_DEMANGLE */

/* Libiberty is not available, return a copy of the mangled string */
const char* ezt_demangle(const char* mangled_str) {
  int len = strlen(mangled_str) + 1;
  char* res_str = malloc(sizeof(char) * len);
  if( res_str ) {
    memcpy(res_str, mangled_str, len);
  }
  return res_str;
}

#endif /* HAVE_DEMANGLE */
