//
// This file is part of MorphoGraphX - http://www.MorphoGraphX.org
// Copyright (C) 2012-2015 Richard S. Smith and collaborators.
//
// If you use MorphoGraphX in your work, please cite:
//   http://dx.doi.org/10.7554/eLife.05864
//
// MorphoGraphX is free software, and is licensed under under the terms of the 
// GNU General (GPL) Public License version 2.0, http://www.gnu.org/licenses.
// 
#include "Mangling.hpp"
#include <sstream>
#include <QString>
#include <stdlib.h>

#ifdef __GNUC__
#  include <cxxabi.h>
#endif

namespace mgx {
  #ifdef __GNUC__
  QString qdemangle(std::string s)
  {
    std::istringstream ss(s);
    int status;
    std::string name;
    QString result;
    while(ss) {
      ss >> name;
      if(!ss)
        break;
      char* realname = abi::__cxa_demangle(name.c_str(), 0, 0, &status);
      if(status) {
        result += QString::fromStdString(name);
      } else {
        result += QString::fromLocal8Bit(realname);
        free(realname);
      }
      result += " ";
    }
    result.chop(1);
    return result;
  }
  
  std::string demangle(std::string s)
  {
    QString res = qdemangle(s);
    return res.toStdString();
  }
  
  #else
  std::string demangle(std::string s) {
    return s;
  }
  
  QString qdemangle(std::string s) {
    return QString::fromStdString(s);
  }
  #endif
}
