//
// 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 "ProcessThread.hpp"
#include <QCoreApplication>

#include <exception>
#include <unistd.h>
#include <omp.h>
#include <sched.h>

namespace mgx 
{
  static const QString& system_error = "System exception caught";
  
  void ProcessThread::run()
  {
    try {
      #ifdef WIN32
        omp_set_dynamic(1);
      #else
        // Set affinity in thread, it seems to be reset somewhere
        cpu_set_t my_set;
        CPU_ZERO(&my_set);
        int numCPUs = sysconf(_SC_NPROCESSORS_ONLN);     // Linux only?
        for(int i = 0; i < numCPUs; i++)
          CPU_SET(i, &my_set);       /* set the bit that represents core i. */
        sched_setaffinity(0, sizeof(cpu_set_t), &my_set);
  
        // Ask OpenMP to use all processors
        omp_set_dynamic(0);
        omp_set_num_threads(numCPUs);
      #endif
  
      _status = process->run();

      if(!_status)
        _error = process->errorMessage();
      else
        _warning = process->warningMessage();
    }
    catch(std::string s) {
      _status = false;
      _error = QString::fromStdString(s);
    }
    catch(QString s) {
      _status = false;
      _error = s;
    }
    catch(std::exception& ex) {
      _status = false;
      _error = QString::fromLocal8Bit(ex.what());
    }
    catch(...) {
      _status = false;
      _error = system_error;
    }
  }
}
