///////////////////////////////////////////////////////////////////////////////
//  Copyright 2011 John Maddock. Distributed under the Boost
//  Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_MATH_BN_MPFI_HPP
#define BOOST_MATH_BN_MPFI_HPP

#include <boost/multiprecision/number.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <boost/cstdint.hpp>
#include <boost/multiprecision/detail/big_lanczos.hpp>
#include <boost/multiprecision/detail/digits.hpp>
#include <boost/multiprecision/mpfr.hpp>
#include <boost/math/constants/constants.hpp>
#include <mpfi.h>
#include <cmath>
#include <algorithm>

namespace boost{
namespace multiprecision{
namespace backends{

template <unsigned digits10>
struct mpfi_float_backend;

} // namespace backends

template <unsigned digits10>
struct number_category<backends::mpfi_float_backend<digits10> > : public mpl::int_<number_kind_floating_point>{};

struct interval_error : public std::runtime_error
{
   interval_error(const std::string& s) : std::runtime_error(s) {}
};

namespace backends{

namespace detail{

inline int mpfi_sgn(mpfi_srcptr p)
{
   if(mpfi_is_zero(p))
      return 0;
   if(mpfi_is_strictly_pos(p))
      return 1;
   if(mpfi_is_strictly_neg(p))
      return -1;
   BOOST_THROW_EXCEPTION(interval_error("Sign of interval is ambiguous."));
}

template <unsigned digits10>
struct mpfi_float_imp;

template <unsigned digits10>
struct mpfi_float_imp
{
   typedef mpl::list<long, long long>                     signed_types;
   typedef mpl::list<unsigned long, unsigned long long>   unsigned_types;
   typedef mpl::list<double, long double>                 float_types;
   typedef long                                           exponent_type;

   mpfi_float_imp()
   {
      mpfi_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));
   }
   mpfi_float_imp(unsigned prec)
   {
      mpfi_init2(m_data, prec);
   }

   mpfi_float_imp(const mpfi_float_imp& o)
   {
      mpfi_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));
      if(o.m_data[0].left._mpfr_d)
         mpfi_set(m_data, o.m_data);
   }
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
   mpfi_float_imp(mpfi_float_imp&& o) BOOST_NOEXCEPT
   {
      m_data[0] = o.m_data[0];
      o.m_data[0].left._mpfr_d = 0;
   }
#endif
   mpfi_float_imp& operator = (const mpfi_float_imp& o)
   {
      if(m_data[0].left._mpfr_d == 0)
         mpfi_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));
      if(o.m_data[0].left._mpfr_d)
         mpfi_set(m_data, o.m_data);
      return *this;
   }
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
   mpfi_float_imp& operator = (mpfi_float_imp&& o) BOOST_NOEXCEPT
   {
      mpfi_swap(m_data, o.m_data);
      return *this;
   }
#endif
#ifdef _MPFR_H_HAVE_INTMAX_T
   mpfi_float_imp& operator = (unsigned long long i)
   {
      if(m_data[0].left._mpfr_d == 0)
         mpfi_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));
      mpfr_set_uj(left_data(), i, GMP_RNDD);
      mpfr_set_uj(right_data(), i, GMP_RNDU);
      return *this;
   }
   mpfi_float_imp& operator = (long long i)
   {
      if(m_data[0].left._mpfr_d == 0)
         mpfi_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));
      mpfr_set_sj(left_data(), i, GMP_RNDD);
      mpfr_set_sj(right_data(), i, GMP_RNDU);
      return *this;
   }
#else
   mpfi_float_imp& operator = (unsigned long long i)
   {
      if(m_data[0].left._mpfr_d == 0)
         mpfi_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));
      unsigned long long mask = ((1uLL << std::numeric_limits<unsigned>::digits) - 1);
      unsigned shift = 0;
      mpfi_t t;
      mpfi_init2(t, (std::max)(static_cast<unsigned>(std::numeric_limits<unsigned long long>::digits), static_cast<unsigned>(multiprecision::detail::digits10_2_2(digits10))));
      mpfi_set_ui(m_data, 0);
      while(i)
      {
         mpfi_set_ui(t, static_cast<unsigned>(i & mask));
         if(shift)
            mpfi_mul_2exp(t, t, shift);
         mpfi_add(m_data, m_data, t);
         shift += std::numeric_limits<unsigned>::digits;
         i >>= std::numeric_limits<unsigned>::digits;
      }
      mpfi_clear(t);
      return *this;
   }
   mpfi_float_imp& operator = (long long i)
   {
      if(m_data[0].left._mpfr_d == 0)
         mpfi_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));
      bool neg = i < 0;
      *this = boost::multiprecision::detail::unsigned_abs(i);
      if(neg)
         mpfi_neg(m_data, m_data);
      return *this;
   }
#endif
   mpfi_float_imp& operator = (unsigned long i)
   {
      if(m_data[0].left._mpfr_d == 0)
         mpfi_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));
      mpfi_set_ui(m_data, i);
      return *this;
   }
   mpfi_float_imp& operator = (long i)
   {
      if(m_data[0].left._mpfr_d == 0)
         mpfi_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));
      mpfi_set_si(m_data, i);
      return *this;
   }
   mpfi_float_imp& operator = (double d)
   {
      if(m_data[0].left._mpfr_d == 0)
         mpfi_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));
      mpfi_set_d(m_data, d);
      return *this;
   }
   mpfi_float_imp& operator = (long double a)
   {
      if(m_data[0].left._mpfr_d == 0)
         mpfi_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));
      mpfr_set_ld(left_data(), a, GMP_RNDD);
      mpfr_set_ld(right_data(), a, GMP_RNDU);
      return *this;
   }
   mpfi_float_imp& operator = (const char* s)
   {
      using default_ops::eval_fpclassify;

      if(m_data[0].left._mpfr_d == 0)
         mpfi_init2(m_data, multiprecision::detail::digits10_2_2(digits10 ? digits10 : get_default_precision()));

      if(s && (*s == '{'))
      {
         mpfr_float_backend<digits10> a, b;
         std::string part;
         const char* p = ++s;
         while(*p && (*p != ',') && (*p != '}'))
            ++p;
         part.assign(s + 1, p);
         a = part.c_str();
         s = p;
         if(*p && (*p != '}'))
         {
            ++p;
            while(*p && (*p != ',') && (*p != '}'))
               ++p;
            part.assign(s + 1, p);
         }
         else
            part.erase();
         b = part.c_str();

         if(eval_fpclassify(a) == (int)FP_NAN)
         {
            mpfi_set_fr(this->data(), a.data());
         }
         else if(eval_fpclassify(b) == (int)FP_NAN)
         {
            mpfi_set_fr(this->data(), b.data());
         }
         else
         {
            if(a.compare(b) > 0)
            {
               BOOST_THROW_EXCEPTION(std::runtime_error("Attempt to create interval with invalid range (start is greater than end)."));
            }
            mpfi_interv_fr(m_data, a.data(), b.data());
         }
      }
      else if(mpfi_set_str(m_data, s, 10) != 0)
      {
         BOOST_THROW_EXCEPTION(std::runtime_error(std::string("Unable to parse string \"") + s + std::string("\"as a valid floating point number.")));
      }
      return *this;
   }
   void swap(mpfi_float_imp& o) BOOST_NOEXCEPT
   {
      mpfi_swap(m_data, o.m_data);
   }
   std::string str(std::streamsize digits, std::ios_base::fmtflags f)const
   {
      BOOST_ASSERT(m_data[0].left._mpfr_d);

      mpfr_float_backend<digits10> a, b;

      mpfi_get_left(a.data(), m_data);
      mpfi_get_right(b.data(), m_data);

      if(a.compare(b) == 0)
         return a.str(digits, f);

      return "{" + a.str(digits, f) + "," + b.str(digits, f) + "}";
   }
   ~mpfi_float_imp() BOOST_NOEXCEPT
   {
      if(m_data[0].left._mpfr_d)
         mpfi_clear(m_data);
   }
   void negate() BOOST_NOEXCEPT
   {
      BOOST_ASSERT(m_data[0].left._mpfr_d);
      mpfi_neg(m_data, m_data);
   }
   int compare(const mpfi_float_imp& o)const BOOST_NOEXCEPT
   {
      BOOST_ASSERT(m_data[0].left._mpfr_d && o.m_data[0].left._mpfr_d);
      if(mpfr_cmp(right_data(), o.left_data()) < 0)
         return -1;
      if(mpfr_cmp(left_data(), o.right_data()) > 0)
         return 1;
      if((mpfr_cmp(left_data(), o.left_data()) == 0) && (mpfr_cmp(right_data(), o.right_data()) == 0))
         return 0;
      BOOST_THROW_EXCEPTION(interval_error("Ambiguous comparison between two values."));
      return 0;
   }
   template <class V>
   int compare(V v)const BOOST_NOEXCEPT
   {
      mpfi_float_imp d;
      d = v;
      return compare(d);
   }
   mpfi_t& data() BOOST_NOEXCEPT
   {
      BOOST_ASSERT(m_data[0].left._mpfr_d);
      return m_data;
   }
   const mpfi_t& data()const BOOST_NOEXCEPT
   {
      BOOST_ASSERT(m_data[0].left._mpfr_d);
      return m_data;
   }
   mpfr_ptr left_data() BOOST_NOEXCEPT
   {
      BOOST_ASSERT(m_data[0].left._mpfr_d);
      return &(m_data[0].left);
   }
   mpfr_srcptr left_data()const BOOST_NOEXCEPT
   {
      BOOST_ASSERT(m_data[0].left._mpfr_d);
      return &(m_data[0].left);
   }
   mpfr_ptr right_data() BOOST_NOEXCEPT
   {
      BOOST_ASSERT(m_data[0].left._mpfr_d);
      return &(m_data[0].right);
   }
   mpfr_srcptr right_data()const BOOST_NOEXCEPT
   {
      BOOST_ASSERT(m_data[0].left._mpfr_d);
      return &(m_data[0].right);
   }
protected:
   mpfi_t m_data;
   static unsigned& get_default_precision() BOOST_NOEXCEPT
   {
      static unsigned val = 50;
      return val;
   }
};

} // namespace detail

template <unsigned digits10>
struct mpfi_float_backend : public detail::mpfi_float_imp<digits10>
{
   mpfi_float_backend() : detail::mpfi_float_imp<digits10>() {}
   mpfi_float_backend(const mpfi_float_backend& o) : detail::mpfi_float_imp<digits10>(o) {}
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
   mpfi_float_backend(mpfi_float_backend&& o) : detail::mpfi_float_imp<digits10>(static_cast<detail::mpfi_float_imp<digits10>&&>(o)) {}
#endif
   template <unsigned D>
   mpfi_float_backend(const mpfi_float_backend<D>& val, typename enable_if_c<D <= digits10>::type* = 0)
       : detail::mpfi_float_imp<digits10>()
   {
      mpfi_set(this->m_data, val.data());
   }
   template <unsigned D>
   explicit mpfi_float_backend(const mpfi_float_backend<D>& val, typename disable_if_c<D <= digits10>::type* = 0)
       : detail::mpfi_float_imp<digits10>()
   {
      mpfi_set(this->m_data, val.data());
   }
   mpfi_float_backend(const mpfi_t val)
       : detail::mpfi_float_imp<digits10>()
   {
      mpfi_set(this->m_data, val);
   }
   mpfi_float_backend& operator=(const mpfi_float_backend& o)
   {
      *static_cast<detail::mpfi_float_imp<digits10>*>(this) = static_cast<detail::mpfi_float_imp<digits10> const&>(o);
      return *this;
   }
   template <unsigned D>
   mpfi_float_backend(const mpfr_float_backend<D>& val, typename enable_if_c<D <= digits10>::type* = 0)
       : detail::mpfi_float_imp<digits10>()
   {
      mpfi_set_fr(this->m_data, val.data());
   }
   template <unsigned D>
   mpfi_float_backend& operator=(const mpfr_float_backend<D>& val)
   {
      mpfi_set_fr(this->m_data, val.data());
      return *this;
   }
   template <unsigned D>
   explicit mpfi_float_backend(const mpfr_float_backend<D>& val, typename disable_if_c<D <= digits10>::type* = 0)
       : detail::mpfi_float_imp<digits10>()
   {
      mpfi_set_fr(this->m_data, val.data());
   }
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
   mpfi_float_backend& operator=(mpfi_float_backend&& o) BOOST_NOEXCEPT
   {
      *static_cast<detail::mpfi_float_imp<digits10>*>(this) = static_cast<detail::mpfi_float_imp<digits10>&&>(o);
      return *this;
   }
#endif
   template <class V>
   mpfi_float_backend& operator=(const V& v)
   {
      *static_cast<detail::mpfi_float_imp<digits10>*>(this) = v;
      return *this;
   }
   mpfi_float_backend& operator=(const mpfi_t val)
   {
      mpfi_set(this->m_data, val);
      return *this;
   }
   // We don't change our precision here, this is a fixed precision type:
   template <unsigned D>
   mpfi_float_backend& operator=(const mpfi_float_backend<D>& val)
   {
      mpfi_set(this->m_data, val.data());
      return *this;
   }
};

template <>
struct mpfi_float_backend<0> : public detail::mpfi_float_imp<0>
{
   mpfi_float_backend() : detail::mpfi_float_imp<0>() {}
   mpfi_float_backend(const mpfi_t val)
      : detail::mpfi_float_imp<0>(mpfi_get_prec(val))
   {
      mpfi_set(this->m_data, val);
   }
   mpfi_float_backend(const mpfi_float_backend& o) : detail::mpfi_float_imp<0>(o) {}
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
   mpfi_float_backend(mpfi_float_backend&& o) BOOST_NOEXCEPT : detail::mpfi_float_imp<0>(static_cast<detail::mpfi_float_imp<0>&&>(o)) {}
#endif
   mpfi_float_backend(const mpfi_float_backend& o, unsigned digits10)
      : detail::mpfi_float_imp<0>(digits10)
   {
      *this = o;
   }
   template <unsigned D>
   mpfi_float_backend(const mpfi_float_backend<D>& val)
      : detail::mpfi_float_imp<0>(mpfi_get_prec(val.data()))
   {
      mpfi_set(this->m_data, val.data());
   }
   mpfi_float_backend& operator=(const mpfi_float_backend& o)
   {
      mpfi_set_prec(this->m_data, mpfi_get_prec(o.data()));
      mpfi_set(this->m_data, o.data());
      return *this;
   }
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
   mpfi_float_backend& operator=(mpfi_float_backend&& o) BOOST_NOEXCEPT
   {
      *static_cast<detail::mpfi_float_imp<0>*>(this) = static_cast<detail::mpfi_float_imp<0> &&>(o);
      return *this;
   }
#endif
   template <class V>
   mpfi_float_backend& operator=(const V& v)
   {
      *static_cast<detail::mpfi_float_imp<0>*>(this) = v;
      return *this;
   }
   mpfi_float_backend& operator=(const mpfi_t val)
   {
      mpfi_set_prec(this->m_data, mpfi_get_prec(val));
      mpfi_set(this->m_data, val);
      return *this;
   }
   template <unsigned D>
   mpfi_float_backend& operator=(const mpfi_float_backend<D>& val)
   {
      mpfi_set_prec(this->m_data, mpfi_get_prec(val.data()));
      mpfi_set(this->m_data, val.data());
      return *this;
   }
   static unsigned default_precision() BOOST_NOEXCEPT
   {
      return get_default_precision();
   }
   static void default_precision(unsigned v) BOOST_NOEXCEPT
   {
      get_default_precision() = v;
   }
   unsigned precision()const BOOST_NOEXCEPT
   {
      return multiprecision::detail::digits2_2_10(mpfi_get_prec(this->m_data));
   }
   void precision(unsigned digits10) BOOST_NOEXCEPT
   {
      mpfi_set_prec(this->m_data, multiprecision::detail::digits2_2_10((digits10)));
   }
};

template <unsigned digits10, class T>
inline typename enable_if<is_arithmetic<T>, bool>::type eval_eq(const mpfi_float_backend<digits10>& a, const T& b) BOOST_NOEXCEPT
{
   return a.compare(b) == 0;
}
template <unsigned digits10, class T>
inline typename enable_if<is_arithmetic<T>, bool>::type eval_lt(const mpfi_float_backend<digits10>& a, const T& b) BOOST_NOEXCEPT
{
   return a.compare(b) < 0;
}
template <unsigned digits10, class T>
inline typename enable_if<is_arithmetic<T>, bool>::type eval_gt(const mpfi_float_backend<digits10>& a, const T& b) BOOST_NOEXCEPT
{
   return a.compare(b) > 0;
}

template <unsigned D1, unsigned D2>
inline void eval_add(mpfi_float_backend<D1>& result, const mpfi_float_backend<D2>& o)
{
   mpfi_add(result.data(), result.data(), o.data());
}
template <unsigned D1, unsigned D2>
inline void eval_subtract(mpfi_float_backend<D1>& result, const mpfi_float_backend<D2>& o)
{
   mpfi_sub(result.data(), result.data(), o.data());
}
template <unsigned D1, unsigned D2>
inline void eval_multiply(mpfi_float_backend<D1>& result, const mpfi_float_backend<D2>& o)
{
   if((void*)&result == (void*)&o)
      mpfi_sqr(result.data(), o.data());
   else
      mpfi_mul(result.data(), result.data(), o.data());
}
template <unsigned D1, unsigned D2>
inline void eval_divide(mpfi_float_backend<D1>& result, const mpfi_float_backend<D2>& o)
{
   mpfi_div(result.data(), result.data(), o.data());
}
template <unsigned digits10>
inline void eval_add(mpfi_float_backend<digits10>& result, unsigned long i)
{
   mpfi_add_ui(result.data(), result.data(), i);
}
template <unsigned digits10>
inline void eval_subtract(mpfi_float_backend<digits10>& result, unsigned long i)
{
   mpfi_sub_ui(result.data(), result.data(), i);
}
template <unsigned digits10>
inline void eval_multiply(mpfi_float_backend<digits10>& result, unsigned long i)
{
   mpfi_mul_ui(result.data(), result.data(), i);
}
template <unsigned digits10>
inline void eval_divide(mpfi_float_backend<digits10>& result, unsigned long i)
{
   mpfi_div_ui(result.data(), result.data(), i);
}
template <unsigned digits10>
inline void eval_add(mpfi_float_backend<digits10>& result, long i)
{
   if(i > 0)
      mpfi_add_ui(result.data(), result.data(), i);
   else
      mpfi_sub_ui(result.data(), result.data(), boost::multiprecision::detail::unsigned_abs(i));
}
template <unsigned digits10>
inline void eval_subtract(mpfi_float_backend<digits10>& result, long i)
{
   if(i > 0)
      mpfi_sub_ui(result.data(), result.data(), i);
   else
      mpfi_add_ui(result.data(), result.data(), boost::multiprecision::detail::unsigned_abs(i));
}
template <unsigned digits10>
inline void eval_multiply(mpfi_float_backend<digits10>& result, long i)
{
   mpfi_mul_ui(result.data(), result.data(), boost::multiprecision::detail::unsigned_abs(i));
   if(i < 0)
      mpfi_neg(result.data(), result.data());
}
template <unsigned digits10>
inline void eval_divide(mpfi_float_backend<digits10>& result, long i)
{
   mpfi_div_ui(result.data(), result.data(), boost::multiprecision::detail::unsigned_abs(i));
   if(i < 0)
      mpfi_neg(result.data(), result.data());
}
//
// Specialised 3 arg versions of the basic operators:
//
template <unsigned D1, unsigned D2, unsigned D3>
inline void eval_add(mpfi_float_backend<D1>& a, const mpfi_float_backend<D2>& x, const mpfi_float_backend<D3>& y)
{
   mpfi_add(a.data(), x.data(), y.data());
}
template <unsigned D1, unsigned D2>
inline void eval_add(mpfi_float_backend<D1>& a, const mpfi_float_backend<D2>& x, unsigned long y)
{
   mpfi_add_ui(a.data(), x.data(), y);
}
template <unsigned D1, unsigned D2>
inline void eval_add(mpfi_float_backend<D1>& a, const mpfi_float_backend<D2>& x, long y)
{
   if(y < 0)
      mpfi_sub_ui(a.data(), x.data(), boost::multiprecision::detail::unsigned_abs(y));
   else
      mpfi_add_ui(a.data(), x.data(), y);
}
template <unsigned D1, unsigned D2>
inline void eval_add(mpfi_float_backend<D1>& a, unsigned long x, const mpfi_float_backend<D2>& y)
{
   mpfi_add_ui(a.data(), y.data(), x);
}
template <unsigned D1, unsigned D2>
inline void eval_add(mpfi_float_backend<D1>& a, long x, const mpfi_float_backend<D2>& y)
{
   if(x < 0)
   {
      mpfi_ui_sub(a.data(), boost::multiprecision::detail::unsigned_abs(x), y.data());
      mpfi_neg(a.data(), a.data());
   }
   else
      mpfi_add_ui(a.data(), y.data(), x);
}
template <unsigned D1, unsigned D2, unsigned D3>
inline void eval_subtract(mpfi_float_backend<D1>& a, const mpfi_float_backend<D2>& x, const mpfi_float_backend<D3>& y)
{
   mpfi_sub(a.data(), x.data(), y.data());
}
template <unsigned D1, unsigned D2>
inline void eval_subtract(mpfi_float_backend<D1>& a, const mpfi_float_backend<D2>& x, unsigned long y)
{
   mpfi_sub_ui(a.data(), x.data(), y);
}
template <unsigned D1, unsigned D2>
inline void eval_subtract(mpfi_float_backend<D1>& a, const mpfi_float_backend<D2>& x, long y)
{
   if(y < 0)
      mpfi_add_ui(a.data(), x.data(), boost::multiprecision::detail::unsigned_abs(y));
   else
      mpfi_sub_ui(a.data(), x.data(), y);
}
template <unsigned D1, unsigned D2>
inline void eval_subtract(mpfi_float_backend<D1>& a, unsigned long x, const mpfi_float_backend<D2>& y)
{
   mpfi_ui_sub(a.data(), x, y.data());
}
template <unsigned D1, unsigned D2>
inline void eval_subtract(mpfi_float_backend<D1>& a, long x, const mpfi_float_backend<D2>& y)
{
   if(x < 0)
   {
      mpfi_add_ui(a.data(), y.data(), boost::multiprecision::detail::unsigned_abs(x));
      mpfi_neg(a.data(), a.data());
   }
   else
      mpfi_ui_sub(a.data(), x, y.data());
}

template <unsigned D1, unsigned D2, unsigned D3>
inline void eval_multiply(mpfi_float_backend<D1>& a, const mpfi_float_backend<D2>& x, const mpfi_float_backend<D3>& y)
{
   if((void*)&x == (void*)&y)
      mpfi_sqr(a.data(), x.data());
   else
      mpfi_mul(a.data(), x.data(), y.data());
}
template <unsigned D1, unsigned D2>
inline void eval_multiply(mpfi_float_backend<D1>& a, const mpfi_float_backend<D2>& x, unsigned long y)
{
   mpfi_mul_ui(a.data(), x.data(), y);
}
template <unsigned D1, unsigned D2>
inline void eval_multiply(mpfi_float_backend<D1>& a, const mpfi_float_backend<D2>& x, long y)
{
   if(y < 0)
   {
      mpfi_mul_ui(a.data(), x.data(), boost::multiprecision::detail::unsigned_abs(y));
      a.negate();
   }
   else
      mpfi_mul_ui(a.data(), x.data(), y);
}
template <unsigned D1, unsigned D2>
inline void eval_multiply(mpfi_float_backend<D1>& a, unsigned long x, const mpfi_float_backend<D2>& y)
{
   mpfi_mul_ui(a.data(), y.data(), x);
}
template <unsigned D1, unsigned D2>
inline void eval_multiply(mpfi_float_backend<D1>& a, long x, const mpfi_float_backend<D2>& y)
{
   if(x < 0)
   {
      mpfi_mul_ui(a.data(), y.data(), boost::multiprecision::detail::unsigned_abs(x));
      mpfi_neg(a.data(), a.data());
   }
   else
      mpfi_mul_ui(a.data(), y.data(), x);
}

template <unsigned D1, unsigned D2, unsigned D3>
inline void eval_divide(mpfi_float_backend<D1>& a, const mpfi_float_backend<D2>& x, const mpfi_float_backend<D3>& y)
{
   mpfi_div(a.data(), x.data(), y.data());
}
template <unsigned D1, unsigned D2>
inline void eval_divide(mpfi_float_backend<D1>& a, const mpfi_float_backend<D2>& x, unsigned long y)
{
   mpfi_div_ui(a.data(), x.data(), y);
}
template <unsigned D1, unsigned D2>
inline void eval_divide(mpfi_float_backend<D1>& a, const mpfi_float_backend<D2>& x, long y)
{
   if(y < 0)
   {
      mpfi_div_ui(a.data(), x.data(), boost::multiprecision::detail::unsigned_abs(y));
      a.negate();
   }
   else
      mpfi_div_ui(a.data(), x.data(), y);
}
template <unsigned D1, unsigned D2>
inline void eval_divide(mpfi_float_backend<D1>& a, unsigned long x, const mpfi_float_backend<D2>& y)
{
   mpfi_ui_div(a.data(), x, y.data());
}
template <unsigned D1, unsigned D2>
inline void eval_divide(mpfi_float_backend<D1>& a, long x, const mpfi_float_backend<D2>& y)
{
   if(x < 0)
   {
      mpfi_ui_div(a.data(), boost::multiprecision::detail::unsigned_abs(x), y.data());
      mpfi_neg(a.data(), a.data());
   }
   else
      mpfi_ui_div(a.data(), x, y.data());
}

template <unsigned digits10>
inline bool eval_is_zero(const mpfi_float_backend<digits10>& val) BOOST_NOEXCEPT
{
   return 0 != mpfi_is_zero(val.data());
}
template <unsigned digits10>
inline int eval_get_sign(const mpfi_float_backend<digits10>& val)
{
   return detail::mpfi_sgn(val.data());
}

template <unsigned digits10>
inline void eval_convert_to(unsigned long* result, const mpfi_float_backend<digits10>& val)
{
   mpfr_float_backend<digits10> t;
   mpfi_mid(t.data(), val.data());
   eval_convert_to(result, t);
}
template <unsigned digits10>
inline void eval_convert_to(long* result, const mpfi_float_backend<digits10>& val)
{
   mpfr_float_backend<digits10> t;
   mpfi_mid(t.data(), val.data());
   eval_convert_to(result, t);
}
#ifdef _MPFR_H_HAVE_INTMAX_T
template <unsigned digits10>
inline void eval_convert_to(unsigned long long* result, const mpfi_float_backend<digits10>& val)
{
   mpfr_float_backend<digits10> t;
   mpfi_mid(t.data(), val.data());
   eval_convert_to(result, t);
}
template <unsigned digits10>
inline void eval_convert_to(long long* result, const mpfi_float_backend<digits10>& val)
{
   mpfr_float_backend<digits10> t;
   mpfi_mid(t.data(), val.data());
   eval_convert_to(result, t);
}
#endif
template <unsigned digits10>
inline void eval_convert_to(double* result, const mpfi_float_backend<digits10>& val) BOOST_NOEXCEPT
{
   *result = mpfi_get_d(val.data());
}
template <unsigned digits10>
inline void eval_convert_to(long double* result, const mpfi_float_backend<digits10>& val) BOOST_NOEXCEPT
{
   mpfr_float_backend<digits10> t;
   mpfi_mid(t.data(), val.data());
   eval_convert_to(result, t);
}

template <unsigned D1, unsigned D2, mpfr_allocation_type AllocationType>
inline void assign_components(mpfi_float_backend<D1>& result, const mpfr_float_backend<D2, AllocationType>& a, const mpfr_float_backend<D2, AllocationType>& b)
{
   using default_ops::eval_fpclassify;
   if(eval_fpclassify(a) == (int)FP_NAN)
   {
      mpfi_set_fr(result.data(), a.data());
   }
   else if(eval_fpclassify(b) == (int)FP_NAN)
   {
      mpfi_set_fr(result.data(), b.data());
   }
   else
   {
      if(a.compare(b) > 0)
      {
         BOOST_THROW_EXCEPTION(std::runtime_error("Attempt to create interval with invalid range (start is greater than end)."));
      }
      mpfi_interv_fr(result.data(), a.data(), b.data());
   }
}

template <unsigned Digits10, class V>
inline typename enable_if_c<is_convertible<V, number<mpfr_float_backend<Digits10, allocate_dynamic>, et_on> >::value >::type
   assign_components(mpfi_float_backend<Digits10>& result, const V& a, const V& b)
{
   number<mpfr_float_backend<Digits10, allocate_dynamic>, et_on> x(a), y(b);
   assign_components(result, x.backend(), y.backend());
}

//
// Native non-member operations:
//
template <unsigned Digits10>
inline void eval_sqrt(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& val)
{
   mpfi_sqrt(result.data(), val.data());
}

template <unsigned Digits10>
inline void eval_abs(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& val)
{
   mpfi_abs(result.data(), val.data());
}

template <unsigned Digits10>
inline void eval_fabs(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& val)
{
   mpfi_abs(result.data(), val.data());
}
template <unsigned Digits10>
inline void eval_ceil(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& val)
{
   mpfr_float_backend<Digits10> a, b;
   mpfr_set(a.data(), val.left_data(), GMP_RNDN);
   mpfr_set(b.data(), val.right_data(), GMP_RNDN);
   eval_ceil(a, a);
   eval_ceil(b, b);
   if(a.compare(b) != 0)
   {
      BOOST_THROW_EXCEPTION(interval_error("Attempt to take the ceil of a value that straddles an integer boundary."));
   }
   mpfi_set_fr(result.data(), a.data());
}
template <unsigned Digits10>
inline void eval_floor(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& val)
{
   mpfr_float_backend<Digits10> a, b;
   mpfr_set(a.data(), val.left_data(), GMP_RNDN);
   mpfr_set(b.data(), val.right_data(), GMP_RNDN);
   eval_floor(a, a);
   eval_floor(b, b);
   if(a.compare(b) != 0)
   {
      BOOST_THROW_EXCEPTION(interval_error("Attempt to take the floor of a value that straddles an integer boundary."));
   }
   mpfi_set_fr(result.data(), a.data());
}
template <unsigned Digits10>
inline void eval_ldexp(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& val, long e)
{
   if(e > 0)
      mpfi_mul_2exp(result.data(), val.data(), e);
   else if(e < 0)
      mpfi_div_2exp(result.data(), val.data(), -e);
   else
      result = val;
}
template <unsigned Digits10>
inline void eval_frexp(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& val, int* e)
{
   mpfr_float_backend<Digits10> t, rt;
   mpfi_mid(t.data(), val.data());
   eval_frexp(rt, t, e);
   eval_ldexp(result, val, -*e);
}
template <unsigned Digits10>
inline void eval_frexp(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& val, long* e)
{
   mpfr_float_backend<Digits10> t, rt;
   mpfi_mid(t.data(), val.data());
   eval_frexp(rt, t, e);
   eval_ldexp(result, val, -*e);
}

template <unsigned Digits10>
inline int eval_fpclassify(const mpfi_float_backend<Digits10>& val) BOOST_NOEXCEPT
{
   return mpfi_inf_p(val.data()) ? FP_INFINITE : mpfi_nan_p(val.data()) ? FP_NAN : mpfi_is_zero(val.data()) ? FP_ZERO : FP_NORMAL;
}

template <unsigned Digits10>
inline void eval_pow(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& b, const mpfi_float_backend<Digits10>& e)
{
   typedef typename boost::multiprecision::detail::canonical<unsigned, mpfi_float_backend<Digits10> >::type ui_type;
   using default_ops::eval_get_sign;
   int s = eval_get_sign(b);
   if(s == 0)
   {
      if(eval_get_sign(e) == 0)
      {
         result = ui_type(1);
      }
      else
      {
         result = ui_type(0);
      }
      return;
   }
   if(s < 0)
   {
      if(eval_get_sign(e) < 0)
      {
         mpfi_float_backend<Digits10> t1, t2;
         t1 = e;
         t1.negate();
         eval_pow(t2, b, t1);
         t1 = ui_type(1);
         eval_divide(result, t1, t2);
         return;
      }
      typename boost::multiprecision::detail::canonical<boost::uintmax_t, mpfi_float_backend<Digits10> >::type an;
      try
      {
         using default_ops::eval_convert_to;
         eval_convert_to(&an, e);
         if(e.compare(an) == 0)
         {
            mpfi_float_backend<Digits10> pb(b);
            pb.negate();
            eval_pow(result, pb, e);
            if(an & 1u)
               result.negate();
            return;
         }
      }
      catch(const std::exception&)
      {
         // conversion failed, just fall through, value is not an integer.
      }
      result = std::numeric_limits<number<mpfi_float_backend<Digits10>, et_on> >::quiet_NaN().backend();
      return;
   }
   mpfi_log(result.data(), b.data());
   mpfi_mul(result.data(), result.data(), e.data());
   mpfi_exp(result.data(), result.data());
}

template <unsigned Digits10>
inline void eval_exp(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg)
{
   mpfi_exp(result.data(), arg.data());
}

template <unsigned Digits10>
inline void eval_log(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg)
{
   mpfi_log(result.data(), arg.data());
}

template <unsigned Digits10>
inline void eval_log10(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg)
{
   mpfi_log10(result.data(), arg.data());
}

template <unsigned Digits10>
inline void eval_sin(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg)
{
   mpfi_sin(result.data(), arg.data());
}

template <unsigned Digits10>
inline void eval_cos(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg)
{
   mpfi_cos(result.data(), arg.data());
}

template <unsigned Digits10>
inline void eval_tan(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg)
{
   mpfi_tan(result.data(), arg.data());
}

template <unsigned Digits10>
inline void eval_asin(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg)
{
   mpfi_asin(result.data(), arg.data());
}

template <unsigned Digits10>
inline void eval_acos(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg)
{
   mpfi_acos(result.data(), arg.data());
}

template <unsigned Digits10>
inline void eval_atan(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg)
{
   mpfi_atan(result.data(), arg.data());
}

template <unsigned Digits10>
inline void eval_atan2(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg1, const mpfi_float_backend<Digits10>& arg2)
{
   mpfi_atan2(result.data(), arg1.data(), arg2.data());
}

template <unsigned Digits10>
inline void eval_sinh(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg)
{
   mpfi_sinh(result.data(), arg.data());
}

template <unsigned Digits10>
inline void eval_cosh(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg)
{
   mpfi_cosh(result.data(), arg.data());
}

template <unsigned Digits10>
inline void eval_tanh(mpfi_float_backend<Digits10>& result, const mpfi_float_backend<Digits10>& arg)
{
   mpfi_tanh(result.data(), arg.data());
}

} // namespace backends

#ifdef BOOST_NO_SFINAE_EXPR

namespace detail{

template<unsigned D1, unsigned D2>
struct is_explicitly_convertible<backends::mpfi_float_backend<D1>, backends::mpfi_float_backend<D2> > : public mpl::true_ {};

}

#endif

template<>
struct number_category<detail::canonical<mpfi_t, backends::mpfi_float_backend<0> >::type> : public mpl::int_<number_kind_floating_point>{};
template <unsigned Digits10>
struct is_interval_number<backends::mpfi_float_backend<Digits10> > : public mpl::true_ {};

using boost::multiprecision::backends::mpfi_float_backend;

typedef number<mpfi_float_backend<50> >    mpfi_float_50;
typedef number<mpfi_float_backend<100> >   mpfi_float_100;
typedef number<mpfi_float_backend<500> >   mpfi_float_500;
typedef number<mpfi_float_backend<1000> >  mpfi_float_1000;
typedef number<mpfi_float_backend<0> >     mpfi_float;

//
// Special interval specific functions:
//
template <unsigned Digits10, expression_template_option ExpressionTemplates>
inline number<mpfr_float_backend<Digits10>, ExpressionTemplates> lower(const number<mpfi_float_backend<Digits10>, ExpressionTemplates>& val)
{
   number<mpfr_float_backend<Digits10> > result;
   mpfr_set(result.backend().data(), val.backend().left_data(), GMP_RNDN);
   return result;
}

template <unsigned Digits10, expression_template_option ExpressionTemplates>
inline number<mpfr_float_backend<Digits10>, ExpressionTemplates> upper(const number<mpfi_float_backend<Digits10>, ExpressionTemplates>& val)
{
   number<mpfr_float_backend<Digits10> > result;
   mpfr_set(result.backend().data(), val.backend().right_data(), GMP_RNDN);
   return result;
}

template <unsigned Digits10, expression_template_option ExpressionTemplates>
inline number<mpfr_float_backend<Digits10>, ExpressionTemplates> median(const number<mpfi_float_backend<Digits10>, ExpressionTemplates>& val)
{
   number<mpfr_float_backend<Digits10> > result;
   mpfi_mid(result.backend().data(), val.backend().data());
   return result;
}

template <unsigned Digits10, expression_template_option ExpressionTemplates>
inline number<mpfr_float_backend<Digits10>, ExpressionTemplates> width(const number<mpfi_float_backend<Digits10>, ExpressionTemplates>& val)
{
   number<mpfr_float_backend<Digits10> > result;
   mpfi_diam_abs(result.backend().data(), val.backend().data());
   return result;
}

template <unsigned Digits10, expression_template_option ExpressionTemplates>
inline number<mpfi_float_backend<Digits10>, ExpressionTemplates> intersect(const number<mpfi_float_backend<Digits10>, ExpressionTemplates>& a, const number<mpfi_float_backend<Digits10>, ExpressionTemplates>&  b)
{
   number<mpfi_float_backend<Digits10>, ExpressionTemplates> result;
   mpfi_intersect(result.backend().data(), a.backend().data(), b.backend().data());
   return result;
}

template <unsigned Digits10, expression_template_option ExpressionTemplates>
inline number<mpfi_float_backend<Digits10>, ExpressionTemplates> hull(const number<mpfi_float_backend<Digits10>, ExpressionTemplates>& a, const number<mpfi_float_backend<Digits10>, ExpressionTemplates>&  b)
{
   number<mpfi_float_backend<Digits10>, ExpressionTemplates> result;
   mpfi_union(result.backend().data(), a.backend().data(), b.backend().data());
   return result;
}

template <unsigned Digits10, expression_template_option ExpressionTemplates>
inline bool overlap(const number<mpfi_float_backend<Digits10>, ExpressionTemplates>& a, const number<mpfi_float_backend<Digits10>, ExpressionTemplates>&  b)
{
  return (lower(a) <= lower(b) && lower(b) <= upper(a)) ||
         (lower(b) <= lower(a) && lower(a) <= upper(b));
}

template <unsigned Digits10, expression_template_option ExpressionTemplates1, expression_template_option ExpressionTemplates2>
inline bool in(const number<mpfr_float_backend<Digits10>, ExpressionTemplates1>& a, const number<mpfi_float_backend<Digits10>, ExpressionTemplates2>&  b)
{
  return mpfi_is_inside_fr(a.backend().data(), b.backend().data()) != 0;
}

template <unsigned Digits10, expression_template_option ExpressionTemplates>
inline bool zero_in(const number<mpfi_float_backend<Digits10>, ExpressionTemplates>&  a)
{
  return mpfi_has_zero(a.backend().data()) != 0;
}

template <unsigned Digits10, expression_template_option ExpressionTemplates>
inline bool subset(const number<mpfi_float_backend<Digits10>, ExpressionTemplates>& a, const number<mpfi_float_backend<Digits10>, ExpressionTemplates>&  b)
{
  return mpfi_is_inside(a.backend().data(), b.backend().data()) != 0;
}

template <unsigned Digits10, expression_template_option ExpressionTemplates>
inline bool proper_subset(const number<mpfi_float_backend<Digits10>, ExpressionTemplates>& a, const number<mpfi_float_backend<Digits10>, ExpressionTemplates>&  b)
{
  return mpfi_is_strictly_inside(a.backend().data(), b.backend().data()) != 0;
}

template <unsigned Digits10, expression_template_option ExpressionTemplates>
inline bool empty(const number<mpfi_float_backend<Digits10>, ExpressionTemplates>&  a)
{
  return mpfi_is_empty(a.backend().data()) != 0;
}

template <unsigned Digits10, expression_template_option ExpressionTemplates>
inline bool singleton(const number<mpfi_float_backend<Digits10>, ExpressionTemplates>&  a)
{
  return mpfr_cmp(a.backend().left_data(), a.backend().right_data()) == 0;
}

template <unsigned Digits10, expression_template_option ExpressionTemplates>
struct component_type<number<mpfi_float_backend<Digits10>, ExpressionTemplates> >
{
   typedef number<mpfr_float_backend<Digits10>, ExpressionTemplates> type;
};

} // namespace multiprecision

namespace math{

namespace tools{

template <>
inline int digits<boost::multiprecision::mpfi_float>()
{
   return boost::multiprecision::backends::detail::get_default_precision();
}
template <>
inline int digits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, boost::multiprecision::et_off> >()
{
   return boost::multiprecision::backends::detail::get_default_precision();
}

} // namespace tools

namespace constants{ namespace detail{

template <class T> struct constant_pi;
template <class T> struct constant_ln_two;
template <class T> struct constant_euler;
template <class T> struct constant_catalan;

//
// Initializer: ensure all our constants are initialized prior to the first call of main:
//
template <class T>
struct mpfi_initializer
{
   struct init
   {
      init()
      {
         boost::math::constants::pi<T>();
         boost::math::constants::ln_two<T>();
         boost::math::constants::euler<T>();
         boost::math::constants::catalan<T>();
      }
      void force_instantiate()const{}
   };
   static const init initializer;
   static void force_instantiate()
   {
      initializer.force_instantiate();
   }
};

template <class T>
const typename mpfi_initializer<T>::init mpfi_initializer<T>::initializer;

template<unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
struct constant_pi<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >
{
   typedef boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> result_type;
   template<int N>
   static inline result_type const& get(const mpl::int_<N>&)
   {
      mpfi_initializer<result_type>::force_instantiate();
      static result_type result;
      static bool has_init = false;
      if(!has_init)
      {
         has_init = true;
         mpfi_const_pi(result.backend().data());
      }
      return result;
   }
};
template<unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
struct constant_ln_two<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >
{
   typedef boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> result_type;
   template<int N>
   static inline result_type const& get(const mpl::int_<N>&)
   {
      mpfi_initializer<result_type>::force_instantiate();
      static result_type result;
      static bool has_init = false;
      if(!has_init)
      {
         has_init = true;
         mpfi_const_log2(result.backend().data());
      }
      return result;
   }
};
template<unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
struct constant_euler<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >
{
   typedef boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> result_type;
   template<int N>
   static inline result_type const& get(const mpl::int_<N>&)
   {
      mpfi_initializer<result_type>::force_instantiate();
      static result_type result;
      static bool has_init = false;
      if(!has_init)
      {
         has_init = true;
         mpfi_const_euler(result.backend().data());
      }
      return result;
   }
};
template<unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
struct constant_catalan<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >
{
   typedef boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> result_type;
   template<int N>
   static inline result_type const& get(const mpl::int_<N>&)
   {
      mpfi_initializer<result_type>::force_instantiate();
      static result_type result;
      static bool has_init = false;
      if(!has_init)
      {
         has_init = true;
         mpfi_const_catalan(result.backend().data());
      }
      return result;
   }
};

}} // namespaces

}}  // namespaces

namespace std{

//
// numeric_limits [partial] specializations for the types declared in this header:
//
template<unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
class numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >
{
   typedef boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> number_type;
public:
   BOOST_STATIC_CONSTEXPR bool is_specialized = true;
   static number_type (min)()
   {
      initializer.do_nothing();
      static std::pair<bool, number_type> value;
      if(!value.first)
      {
         value.first = true;
         value.second = 0.5;
         mpfi_div_2exp(value.second.backend().data(), value.second.backend().data(), -mpfr_get_emin());
      }
      return value.second;
   }
   static number_type (max)()
   {
      initializer.do_nothing();
      static std::pair<bool, number_type> value;
      if(!value.first)
      {
         value.first = true;
         value.second = 0.5;
         mpfi_mul_2exp(value.second.backend().data(), value.second.backend().data(), mpfr_get_emax());
      }
      return value.second;
   }
   BOOST_STATIC_CONSTEXPR number_type lowest()
   {
      return -(max)();
   }
   BOOST_STATIC_CONSTEXPR int digits = static_cast<int>((Digits10 * 1000L) / 301L + ((Digits10 * 1000L) % 301 ? 2 : 1));
   BOOST_STATIC_CONSTEXPR int digits10 = Digits10;
   // Is this really correct???
   BOOST_STATIC_CONSTEXPR int max_digits10 = Digits10 + 2;
   BOOST_STATIC_CONSTEXPR bool is_signed = true;
   BOOST_STATIC_CONSTEXPR bool is_integer = false;
   BOOST_STATIC_CONSTEXPR bool is_exact = false;
   BOOST_STATIC_CONSTEXPR int radix = 2;
   static number_type epsilon()
   {
      initializer.do_nothing();
      static std::pair<bool, number_type> value;
      if(!value.first)
      {
         value.first = true;
         value.second = 1;
         mpfi_div_2exp(value.second.backend().data(), value.second.backend().data(), std::numeric_limits<number_type>::digits - 1);
      }
      return value.second;
   }
   // What value should this be????
   static number_type round_error()
   {
      // returns epsilon/2
      initializer.do_nothing();
      static std::pair<bool, number_type> value;
      if(!value.first)
      {
         value.first = true;
         value.second = 1;
         mpfi_div_2exp(value.second.backend().data(), value.second.backend().data(), 1);
      }
      return value.second;
   }
   BOOST_STATIC_CONSTEXPR long min_exponent = MPFR_EMIN_DEFAULT;
   BOOST_STATIC_CONSTEXPR long min_exponent10 = (MPFR_EMIN_DEFAULT / 1000) * 301L;
   BOOST_STATIC_CONSTEXPR long max_exponent = MPFR_EMAX_DEFAULT;
   BOOST_STATIC_CONSTEXPR long max_exponent10 = (MPFR_EMAX_DEFAULT / 1000) * 301L;
   BOOST_STATIC_CONSTEXPR bool has_infinity = true;
   BOOST_STATIC_CONSTEXPR bool has_quiet_NaN = true;
   BOOST_STATIC_CONSTEXPR bool has_signaling_NaN = false;
   BOOST_STATIC_CONSTEXPR float_denorm_style has_denorm = denorm_absent;
   BOOST_STATIC_CONSTEXPR bool has_denorm_loss = false;
   static number_type infinity()
   {
      initializer.do_nothing();
      static std::pair<bool, number_type> value;
      if(!value.first)
      {
         boost::multiprecision::mpfr_float_backend<Digits10> t;
         mpfr_set_inf(t.data(), 1);
         value.first = true;
         mpfi_set_fr(value.second.backend().data(), t.data());
      }
      return value.second;
   }
   static number_type quiet_NaN()
   {
      initializer.do_nothing();
      static std::pair<bool, number_type> value;
      if(!value.first)
      {
         boost::multiprecision::mpfr_float_backend<Digits10> t;
         mpfr_set_nan(t.data());
         value.first = true;
         mpfi_set_fr(value.second.backend().data(), t.data());
      }
      return value.second;
   }
   BOOST_STATIC_CONSTEXPR number_type signaling_NaN()
   {
      return number_type(0);
   }
   BOOST_STATIC_CONSTEXPR number_type denorm_min() { return number_type(0); }
   BOOST_STATIC_CONSTEXPR bool is_iec559 = false;
   BOOST_STATIC_CONSTEXPR bool is_bounded = true;
   BOOST_STATIC_CONSTEXPR bool is_modulo = false;
   BOOST_STATIC_CONSTEXPR bool traps = true;
   BOOST_STATIC_CONSTEXPR bool tinyness_before = false;
   BOOST_STATIC_CONSTEXPR float_round_style round_style = round_to_nearest;

private:
   struct data_initializer
   {
      data_initializer()
      {
         std::numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<digits10> > >::epsilon();
         std::numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<digits10> > >::round_error();
         (std::numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<digits10> > >::min)();
         (std::numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<digits10> > >::max)();
         std::numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<digits10> > >::infinity();
         std::numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<digits10> > >::quiet_NaN();
      }
      void do_nothing()const{}
   };
   static const data_initializer initializer;
};

template<unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
const typename numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::data_initializer numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::initializer;

#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION

template <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::digits;
template <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::digits10;
template <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::max_digits10;
template <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::is_signed;
template <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::is_integer;
template <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::is_exact;
template <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::radix;
template <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST long numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::min_exponent;
template <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST long numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::min_exponent10;
template <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST long numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::max_exponent;
template <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST long numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::max_exponent10;
template <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::has_infinity;
template <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::has_quiet_NaN;
template <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::has_signaling_NaN;
template <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST float_denorm_style numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::has_denorm;
template <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::has_denorm_loss;
template <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::is_iec559;
template <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::is_bounded;
template <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::is_modulo;
template <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::traps;
template <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::tinyness_before;
template <unsigned Digits10, boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST float_round_style numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<Digits10>, ExpressionTemplates> >::round_style;

#endif

template<boost::multiprecision::expression_template_option ExpressionTemplates>
class numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >
{
   typedef boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> number_type;
public:
   BOOST_STATIC_CONSTEXPR bool is_specialized = false;
   static number_type (min)() { return number_type(0); }
   static number_type (max)() { return number_type(0); }
   static number_type lowest() { return number_type(0); }
   BOOST_STATIC_CONSTEXPR int digits = 0;
   BOOST_STATIC_CONSTEXPR int digits10 = 0;
   BOOST_STATIC_CONSTEXPR int max_digits10 = 0;
   BOOST_STATIC_CONSTEXPR bool is_signed = false;
   BOOST_STATIC_CONSTEXPR bool is_integer = false;
   BOOST_STATIC_CONSTEXPR bool is_exact = false;
   BOOST_STATIC_CONSTEXPR int radix = 0;
   static number_type epsilon() { return number_type(0); }
   static number_type round_error() { return number_type(0); }
   BOOST_STATIC_CONSTEXPR int min_exponent = 0;
   BOOST_STATIC_CONSTEXPR int min_exponent10 = 0;
   BOOST_STATIC_CONSTEXPR int max_exponent = 0;
   BOOST_STATIC_CONSTEXPR int max_exponent10 = 0;
   BOOST_STATIC_CONSTEXPR bool has_infinity = false;
   BOOST_STATIC_CONSTEXPR bool has_quiet_NaN = false;
   BOOST_STATIC_CONSTEXPR bool has_signaling_NaN = false;
   BOOST_STATIC_CONSTEXPR float_denorm_style has_denorm = denorm_absent;
   BOOST_STATIC_CONSTEXPR bool has_denorm_loss = false;
   static number_type infinity() { return number_type(0); }
   static number_type quiet_NaN() { return number_type(0); }
   static number_type signaling_NaN() { return number_type(0); }
   static number_type denorm_min() { return number_type(0); }
   BOOST_STATIC_CONSTEXPR bool is_iec559 = false;
   BOOST_STATIC_CONSTEXPR bool is_bounded = false;
   BOOST_STATIC_CONSTEXPR bool is_modulo = false;
   BOOST_STATIC_CONSTEXPR bool traps = false;
   BOOST_STATIC_CONSTEXPR bool tinyness_before = false;
   BOOST_STATIC_CONSTEXPR float_round_style round_style = round_toward_zero;
};

#ifndef BOOST_NO_INCLASS_MEMBER_INITIALIZATION

template <boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::digits;
template <boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::digits10;
template <boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::max_digits10;
template <boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::is_signed;
template <boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::is_integer;
template <boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::is_exact;
template <boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::radix;
template <boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::min_exponent;
template <boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::min_exponent10;
template <boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::max_exponent;
template <boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST int numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::max_exponent10;
template <boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::has_infinity;
template <boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::has_quiet_NaN;
template <boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::has_signaling_NaN;
template <boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST float_denorm_style numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::has_denorm;
template <boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::has_denorm_loss;
template <boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::is_iec559;
template <boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::is_bounded;
template <boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::is_modulo;
template <boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::traps;
template <boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST bool numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::tinyness_before;
template <boost::multiprecision::expression_template_option ExpressionTemplates>
BOOST_CONSTEXPR_OR_CONST float_round_style numeric_limits<boost::multiprecision::number<boost::multiprecision::mpfi_float_backend<0>, ExpressionTemplates> >::round_style;

#endif
} // namespace std
#endif


/************************************************************************
 * Software License Agreement (BSD License)
 *
 * Copyright (c) 2014, Péter Fankhauser, Christian Gehring, Stelian Coros
 * All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Autonomous Systems Lab nor ETH Zurich
 *     nor the names of its contributors may be used to endorse or
 *     promote products derived from this software without specific
 *     prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 */

/*!
* @file    OoqpEigenInterface.hpp
* @author  Péter Fankhauser, Christian Gehring
* @date    Aug 13, 2013
* @brief   Uses the Object Oriented QP solver package (OOQP) to solve
*          convex quadratic optimization problems of the type:
*          Find x: min 1/2 x' Q x + c' x such that A x = b, d <= Cx <= f, and l <= x <= u
*          where Q is symmetric positive semidefinite (nxn), x is a vector (nx1),
*          A and C are (possibly null) matrices and b and d are vectors of appropriate dimensions.
*          We are using sparse matrices in the Harwell-Boeing row-major format.
*          Adapted from 'simulationandcontrol' by Stelian Coros.
*/

#pragma once

#include <Eigen/Core>
#include <Eigen/SparseCore>

namespace ooqpei {

class OoqpEigenInterface
{
 public:
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW

  /*!
   * Solve min 1/2 x' Q x + c' x, such that A x = b, d <= Cx <= f, and l <= x <= u.
   * @param [in] Q a symmetric positive semidefinite matrix (nxn)
   * @param [in] c a vector (nx1)
   * @param [in] A a (possibly null) matrices (m_axn)
   * @param [in] b a vector (m_ax1)
   * @param [in] C a (possibly null) matrices (m_cxn)
   * @param [in] d a vector (m_cx1)
   * @param [in] f a vector (m_cx1)
   * @param [in] l a vector (nx1)
   * @param [in] u a vector (nx1)
   * @param [out] x a vector of variables (nx1)
   * @return true if successful
   */
  static bool solve(const Eigen::SparseMatrix<double, Eigen::RowMajor>& Q,
                    const Eigen::VectorXd& c,
                    const Eigen::SparseMatrix<double, Eigen::RowMajor>& A,
                    const Eigen::VectorXd& b,
                    const Eigen::SparseMatrix<double, Eigen::RowMajor>& C,
                    const Eigen::VectorXd& d, const Eigen::VectorXd& f,
                    const Eigen::VectorXd& l, const Eigen::VectorXd& u,
                    Eigen::VectorXd& x,
                    const bool ignoreUnknownError = false);

  /*!
   * Solve min 1/2 x' Q x + c' x, such that A x = b, and d <= Cx <= f
   * @param [in] Q a symmetric positive semidefinite matrix (nxn)
   * @param [in] c a vector (nx1)
   * @param [in] A a (possibly null) matrices (m_axn)
   * @param [in] b a vector (m_ax1)
   * @param [in] C a (possibly null) matrices (m_cxn)
   * @param [in] d a vector (m_cx1)
   * @param [in] f a vector (m_cx1)
   * @param [out] x a vector of variables (nx1)
   * @return true if successful
   */
  static bool solve(const Eigen::SparseMatrix<double, Eigen::RowMajor>& Q,
                    const Eigen::VectorXd& c,
                    const Eigen::SparseMatrix<double, Eigen::RowMajor>& A,
                    const Eigen::VectorXd& b,
                    const Eigen::SparseMatrix<double, Eigen::RowMajor>& C,
                    const Eigen::VectorXd& d, const Eigen::VectorXd& f,
                    Eigen::VectorXd& x,
                    const bool ignoreUnknownError = false);

  /*!
   * Solve min 1/2 x' Q x + c' x, such that A x = b, and l <= x <= u.
   * @param [in] Q a symmetric positive semidefinite matrix (nxn)
   * @param [in] c a vector (nx1)
   * @param [in] A a (possibly null) matrices (m_axn)
   * @param [in] b a vector (m_ax1)
   * @param [in] l a vector (nx1)
   * @param [in] u a vector (nx1)
   * @param [out] x a vector of variables (nx1)
   * @return true if successful
   */
  static bool solve(const Eigen::SparseMatrix<double, Eigen::RowMajor>& Q,
                    const Eigen::VectorXd& c,
                    const Eigen::SparseMatrix<double, Eigen::RowMajor>& A,
                    const Eigen::VectorXd& b,
                    const Eigen::VectorXd& l, const Eigen::VectorXd& u,
                    Eigen::VectorXd& x,
                    const bool ignoreUnknownError = false);

  /*!
   * Solve min 1/2 x' Q x + c' x, such that Cx <= f
   * @param [in] Q a symmetric positive semidefinite matrix (nxn)
   * @param [in] c a vector (nx1)
   * @param [in] C a (possibly null) matrices (m_cxn)
   * @param [in] f a vector (m_cx1)
   * @param [out] x a vector of variables (nx1)
   * @return true if successful
   */
  static bool solve(const Eigen::SparseMatrix<double, Eigen::RowMajor>& Q,
                    const Eigen::VectorXd& c,
                    const Eigen::SparseMatrix<double, Eigen::RowMajor>& C,
                    const Eigen::VectorXd& f,
                    Eigen::VectorXd& x,
                    const bool ignoreUnknownError = false);

  /*!
   * Solve min 1/2 x' Q x + c' x
   * @param [in] Q a symmetric positive semidefinite matrix (nxn)
   * @param [in] c a vector (nx1)
   * @param [out] x a vector of variables (nx1)
   * @return true if successful
   */
  static bool solve(const Eigen::SparseMatrix<double, Eigen::RowMajor>& Q,
                    const Eigen::VectorXd& c,
                    Eigen::VectorXd& x,
                    const bool ignoreUnknownError = false);

  /*!
   * Change to true to print debug information.
   * @return true if in debug mode
   */
  static bool isInDebugMode() { return isInDebugMode_; };
  static void setIsInDebugMode(bool isInDebugMode) {
    isInDebugMode_ = isInDebugMode;
  }

 private:
  /*!
   * Determine which limits are active and which are not.
   * @param [in]  l
   * @param [in]  u
   * @param [out] useLowerLimit
   * @param [out] useUpperLimit
   * @param [out] lowerLimit
   * @param [out] upperLimit
   */
  static void generateLimits(const Eigen::VectorXd& l, const Eigen::VectorXd& u,
                      Eigen::Matrix<char, Eigen::Dynamic, 1>& useLowerLimit,
                      Eigen::Matrix<char, Eigen::Dynamic, 1>& useUpperLimit,
                      Eigen::VectorXd& lowerLimit, Eigen::VectorXd& upperLimit);

  static void printProblemFormulation(
      const Eigen::SparseMatrix<double, Eigen::RowMajor>& Q, const Eigen::VectorXd& c,
      const Eigen::SparseMatrix<double, Eigen::RowMajor>& A, const Eigen::VectorXd& b,
      const Eigen::SparseMatrix<double, Eigen::RowMajor>& C, const Eigen::VectorXd& d, const Eigen::VectorXd& f,
      const Eigen::VectorXd& l, const Eigen::VectorXd& u);

  static void printLimits(const Eigen::Matrix<char, Eigen::Dynamic, 1>& useLowerLimit,
                          const Eigen::Matrix<char, Eigen::Dynamic, 1>& useUpperLimit,
                          const Eigen::VectorXd& lowerLimit,
                          const Eigen::VectorXd& upperLimit);

  static void printSolution(const int status, const Eigen::VectorXd& x);

 private:
  static bool isInDebugMode_;
};

} /* namespace ooqpei */


#pragma once
#include <graph/graph.hpp>
#include <graph/properties.hpp>
#include <graph/static_graph.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <graph/queue/DijkstraQueue.hpp>
#include <limits>

namespace graph
{
	template <typename PredecessorMapTag, class DisanceMapTag, typename WeightMapTag,
	          typename IndexMapTag, typename ColorMapTag, typename BundledVertexProperties,
	          typename BundledEdgeProperties>
	struct GenerateDijkstraGraph {};

	template <typename PredecessorMapTag, class DisanceMapTag, typename WeightMapTag,
	          typename IndexMapTag, typename ColorMapTag, typename... P1s, typename... P2s>
	struct GenerateDijkstraGraph<PredecessorMapTag, DisanceMapTag, WeightMapTag,
	                             IndexMapTag, ColorMapTag, Properties<P1s...>, Properties<P2s...>> {
		using type = StaticGraph<
			Properties<
				Property<PredecessorMapTag,
				         typename graph_traits<StaticGraph<Properties<>, Properties<>>>::vertex_descriptor>,
				Property<DisanceMapTag, uint32_t>,
				Property<ColorMapTag, boost::two_bit_color_type>,
				P1s...>,
			Properties<
				Property<WeightMapTag, uint32_t>,
				P2s...>>;
	};

	template <typename DistanceMap>
	constexpr typename DistanceMap::value_type InfinityDistance() {
		return std::numeric_limits<typename DistanceMap::value_type>::max();
	}

	template <typename Graph>
	struct IDijkstraVisitor {
		// This is invoked one each vertex of the graph when it is initialized.
		void initialize_vertex(const typename graph_traits<Graph>::vertex_descriptor&, const Graph&) {};

		// This is invoked on a vertex as it is popped from the queue.
		// This happens immediately before examine_edge() is invoked on each of the out - edges of vertex u.
		void examine_vertex(const typename graph_traits<Graph>::vertex_descriptor&, const Graph&) {};

		// This is invoked on every out - edge of each vertex after it is discovered.
		void examine_edge(const typename graph_traits<Graph>::edge_descriptor&, const Graph&) {};

		// This is invoked when a vertex is encountered for the first time.
		void discover_vertex(const typename graph_traits<Graph>::vertex_descriptor&, const Graph&) {};

		// Upon examination, if the following condition holds then the edge is relaxed(its distance is reduced), and this method is invoked.
		void edge_relaxed(const typename graph_traits<Graph>::edge_descriptor&, const Graph&) {};

		// Upon examination, if the edge is not relaxed(see above) then this method is invoked.
		void edge_not_relaxed(const typename graph_traits<Graph>::edge_descriptor&, const Graph&) {};

		// This invoked on a vertex after all of its out edges have been added to the search tree and
		// all of the adjacent vertices have been discovered(but before their out - edges have been examined).
		void finish_vertex(const typename graph_traits<Graph>::vertex_descriptor&, const Graph&) {};

		// A predicate which is invoked on every out - edge of each vertex to check if the algorithm should relax it
		bool should_relax(const typename graph_traits<Graph>::edge_descriptor&, const Graph&) {
			return true;
		};

		// A predicate  which is invoked after finish_vertex to check if the algorithm should continue
		bool should_continue() {
			return true;
		};
	};

	template <typename Graph>
	class LazyVertexInitializer {
	private:
		using VertexType = typename graph_traits<Graph>::vertex_descriptor;
		using IterationIdType = uint32_t;
		std::vector<IterationIdType> vertexIterationId;
		IterationIdType currentIterationId;
	public:

		void Initialize(Graph& graph) {
			auto verticesCount = num_vertices(graph);
			vertexIterationId.resize(verticesCount, 0);
			if (currentIterationId == std::numeric_limits<IterationIdType>::max()) {
				currentIterationId = 0;
				vertexIterationId.assign(verticesCount, 0);
			}
			++currentIterationId;
		}

		template <typename IndexMap>
		bool IsInitialized(const VertexType& v, const IndexMap& index) const {
			auto vertexIndex = get(index, v);
			return vertexIterationId[vertexIndex] == currentIterationId;
		}

		template <typename IndexMap>
		bool TryInitializeVertex(const VertexType& v, const IndexMap& index) {
			auto vertexIndex = get(index, v);
			if (vertexIterationId[vertexIndex] == currentIterationId)
				return false;
			vertexIterationId[vertexIndex] = currentIterationId;
			return true;
		}
	};

	template <typename Graph>
	struct DefaultDijkstraVisitor : public IDijkstraVisitor<Graph> {
		struct SharedDataStorage {
			using QueueType = queue::DijkstraQueue<
				uint32_t,
				typename graph_traits<Graph>::vertex_descriptor,
				typename property_map<Graph, vertex_index_t>::type>;
			QueueType Queue;
			LazyVertexInitializer<Graph> VertexInitializer;
		};

		SharedDataStorage Stored;

		DefaultDijkstraVisitor()
			: Stored() {}

		void Initialize(Graph& graph) {
			auto verticesCount = num_vertices(graph);
			Stored.Queue.Resize(verticesCount);
			Stored.Queue.Clear();

			Stored.VertexInitializer.Initialize(graph);
		}
	};

	template <class Graph, class PredecessorMap, class DistanceMap,
	          class IndexMap, class ColorMap, class DijkstraVisitor>
	void EnsureVertexInitialization(Graph& graph,
	                                const typename graph_traits<Graph>::vertex_descriptor& v,
	                                PredecessorMap& predecessor,
	                                DistanceMap& distance,
	                                IndexMap& index, ColorMap& color,
	                                DijkstraVisitor& visitor) {
		using DistanceType = typename DistanceMap::value_type;

		if (!visitor.Stored.VertexInitializer.TryInitializeVertex(v, index))
			return;

		visitor.initialize_vertex(v, graph);
		put(distance, v, InfinityDistance<DistanceMap>());
		put(predecessor, v, v);
		put(color, v, boost::two_bit_color_type::two_bit_white);
	}

	template <class Graph, class PredecessorMap, class DistanceMap, class IndexMap,
	          class ColorMap, class DijkstraVisitor, class Queue>
	void init_first_vertex(Graph& graph,
	                       const typename graph_traits<Graph>::vertex_descriptor& v,
	                       PredecessorMap& predecessor,
	                       DistanceMap& distance,
	                       IndexMap& index, ColorMap& color,
	                       DijkstraVisitor& visitor, Queue& queue) {
		using DistanceType = typename DistanceMap::value_type;
		const DistanceType startDistance = 0;

		EnsureVertexInitialization(graph, v, predecessor, distance, index, color, visitor);
		visitor.discover_vertex(v, graph);
		put(distance, v, startDistance);
		put(color, v, boost::two_bit_color_type::two_bit_green);
		queue.Insert(startDistance, v, index);
	}

	template <class Graph, class PredecessorMap, class DistanceMap, class WeightMap,
	          class IndexMap, class ColorMap, class DijkstraVisitor>
	bool dijkstra_iteration(Graph& graph,
	                        PredecessorMap& predecessor, DistanceMap& distance, WeightMap& weight,
	                        IndexMap& index, ColorMap& color, DijkstraVisitor& visitor) {
		auto& queue = visitor.Stored.Queue;
		// Get vertex from queue
		auto topItem = queue.PeekMin();
		queue.DeleteMin();
		auto& v = topItem.Vertex;
		auto& vDistance = topItem.Distance;
		visitor.examine_vertex(v, graph);

		// Process edges
		for (const auto& edge : graphUtil::Range(out_edges(v, graph))) {
			visitor.examine_edge(edge, graph);
			if (!visitor.should_relax(edge, graph))
				continue;
			// Get edge Properties
			auto to = target(edge, graph);
			EnsureVertexInitialization(graph, to, predecessor, distance, index, color, visitor);
			auto edgeWeight = get(weight, edge);
			auto newDistance = vDistance + edgeWeight;
			auto toDistance = get(distance, to);
			if (newDistance < toDistance) {
				// Found better distance -> update
				put(distance, to, newDistance);
				put(predecessor, to, v);
				if (get(color, to) == boost::two_bit_color_type::two_bit_white) {
					// Vertex is new
					visitor.discover_vertex(to, graph);
					put(color, to, boost::two_bit_color_type::two_bit_green);
					queue.Insert(newDistance, to, index);
				}
				else {
					queue.DecreaseKey(newDistance, to, index);
				}
				visitor.edge_relaxed(edge, graph);
			}
			else {
				// Found same or worse distance
				visitor.edge_not_relaxed(edge, graph);
			}
		}

		// Teardown vertex
		put(color, v, boost::two_bit_color_type::two_bit_black);
		visitor.finish_vertex(v, graph);
		return visitor.should_continue();
	};

	template <class Graph, class PredecessorMap, class DistanceMap, class WeightMap,
	          class IndexMap, class ColorMap, class DijkstraVisitor = DefaultDijkstraVisitor<Graph>>
	void dijkstra(Graph& graph,
	              const typename graph_traits<Graph>::vertex_descriptor& s,
	              PredecessorMap& predecessor, DistanceMap& distance, WeightMap& weight,
	              IndexMap& index, ColorMap& color) {
		DijkstraVisitor visitor;
		dijkstra(graph, s, predecessor, distance, weight, index, color, visitor);
	}

	template <class Graph, class PredecessorMap, class DistanceMap, class WeightMap,
	          class IndexMap, class ColorMap, class DijkstraVisitor = DefaultDijkstraVisitor<Graph>>
	void dijkstra(Graph& graph,
	              const typename graph_traits<Graph>::vertex_descriptor& s,
	              PredecessorMap& predecessor, DistanceMap& distance, WeightMap& weight,
	              IndexMap& index, ColorMap& color, DijkstraVisitor& visitor) {
		using Vertex = typename graph_traits<Graph>::vertex_descriptor;
		visitor.Initialize(graph);
		auto& queue = visitor.Stored.Queue;

		// Process start vertex
		init_first_vertex(graph, s, predecessor, distance, index, color, visitor, queue);

		while (!queue.IsEmpty()) {
			auto allRight = dijkstra_iteration(graph, predecessor, distance, weight, index, color, visitor);
			if (!allRight)
				break;
		}
	};
}


#ifndef __TRIAL_HPP__
#define __TRIAL_HPP__

#include <armadillo>
#include <random>
#include <cmath>
#include <vector>
#include <initializer_list>
#include "seed.hpp"

namespace pauth {

/*! \brief Trial move for continuous degrees of freedom e.g. positions in space
 */
class continuous_trial_move {
public:
  /*! \brief Trial move generator for a continuous monte carlo phase space
   *
   * \param     delta_max     Maximum step size
   * \param     sg            Seed generator
   * \return                  Trial move generator
   */
  continuous_trial_move(const double delta_max, seed_gen sg = _default_seed_gen)
    : _delta_dist(-delta_max, delta_max) { _rng.seed(sg()); }

  /*! \brief Copy constructor for continuous trial move generator
   *
   * \param     ctm           Continuous trial move generator
   * \param     sg            Seed generator
   * \return                  Copy
   */
  continuous_trial_move(const continuous_trial_move &ctm,
                        seed_gen sg = _default_seed_gen)
    : _delta_dist(ctm._delta_dist.param()) { _rng.seed(sg()); }

  /*! \brief Generators trial moves for a continuous phase space
   *
   * \param     positions     Molecular positions
   * \param     j             Index of molecule to move
   * \return                  Trial move
   */
  arma::vec operator()(const arma::mat &positions, const size_t) {
    arma::vec dx(positions.n_rows);
    for (size_t i = 0; i < positions.n_rows; ++i) dx(i) = _delta_dist(_rng);
    return dx;
  }

private:
  std::uniform_real_distribution<double> _delta_dist;
  std::default_random_engine _rng;
};

/*! \brief Trial move for discrete states as opposed to continuous positions
 */
class state_trial_move {
public:
  /*! \brief Trial move generator for a phase space that consists of "states"
   *
   * \param     num_states     Number of available states
   * \param     sg             Seed generator
   * \return                   Trial move generator
   */
  state_trial_move(const unsigned num_states = 2,
                   seed_gen sg = _default_seed_gen)
    : _state_dist(0, num_states-1) { _rng.seed(sg()); }

  /*! \brief Copy constructor for state trial move generator
   *
   * \param     stm           State trial move generator
   * \param     sg            Seed generator
   * \return                  Copy
   */
  state_trial_move(const state_trial_move &stm, seed_gen sg = _default_seed_gen)
    : _state_dist(stm._state_dist.param()) { _rng.seed(sg()); }

  /*! \brief Generates trial move for a two-state system
   *
   * \param     positions     Molecular positions
   * \param     j             Index of molecule to move
   * \return                  Trial move
   */
  arma::vec operator()(const arma::mat &positions, const size_t j) {
    arma::vec dx(1);
    dx(0) = _state_dist(_rng);
    return dx - positions(0, j);
  }

private:
  std::uniform_int_distribution<unsigned> _state_dist;
  std::default_random_engine _rng;
};

/*! \brief Direct sampling trial move generator
 */
template <class T> class direct_sample {
public:
  /*! \brief Trial move generator for direct sampling by distributions
   *
   * \param     dists          Sampling distributions
   * \param     sg             Seed generator
   * \return                   Trial move generator
   */
  direct_sample<T>(std::initializer_list<T> dists,
                   seed_gen sg = _default_seed_gen) : _dof_dists(dists),
    _choice_dist(0, _dof_dists.size()-1) {
    _rng.seed(sg());
  }

  /*! \brief Trial move generator for direct sampling by a distribution
   *
   * \param     dist           Sampling distribution
   * \param     N              Degrees of freedom per particle
   * \param     sg             Seed generator
   * \return                   Trial move generator
   */
  direct_sample<T>(T dist, size_t N, seed_gen sg = _default_seed_gen) :
    _dof_dists(dist, N), _choice_dist(0, _dof_dists.size()-1) {
    _rng.seed(sg());
  }

  /*! \brief Generates trial move for a two-state system
   *
   * \param     positions     Molecular positions
   * \param     j             Index of molecule to move
   * \return                  Trial move
   */
  arma::vec operator()(const arma::mat &positions, const size_t j) {
    auto dx = arma::zeros<arma::vec>(_dof_dists.size());
    auto choice = _rng(_choice_dist); // choose a degree of freedom
    // directly sample a degree of freedom from its associated distribution
    dx(choice) = _rng(_dof_dists(choice)) - positions(choice, j);
    return dx;
  }

private:
  std::vector<T> _dof_dists;
  std::uniform_int_distribution<size_t> _choice_dist;
  std::default_random_engine _rng;
};

}

#endif


/**
 * @file
 * This file is part of SeisSol.
 *
 * @author Sebastian Rettenberger (sebastian.rettenberger AT tum.de, http://www5.in.tum.de/wiki/index.php/Sebastian_Rettenberger)
 *
 * @section LICENSE
 * Copyright (c) 2015-2016, SeisSol Group
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * @section DESCRIPTION
 **/

#include <cstring>
#include <limits>
#include <string>

#include <pthread.h>

#include <pstream.h>

#include <Eigen/Dense>

#include <netcdf.h>

#include <proj_api.h>

#include "utils/args.h"
#include "utils/logger.h"
#include "utils/stringutils.h"

const static float MIN_VALID = -10000;

typedef Eigen::Array<unsigned long, 3, 1> ularr3;
typedef Eigen::Array<unsigned long, 2, 1> ularr2;

struct inputData_t
{
        Eigen::Array3d minVert;
        ularr3 gridSize;
	Eigen::Array3d gridDist;

	const char* meshProj;
	bool meshIsGeo;
	const char* queryProj;
	bool queryIsGeo;

	redi::rpstream& query;
};

/**
 * Check netCDF return value for errors
 */
static void checkNcIError(int error)
{
	if (error != NC_NOERR)
		logError() << "Error while reading netCDF file:" << nc_strerror(error);
}

/**
 * Check netCDF return value for errors
 */
static void checkNcOError(int error)
{
	if (error != NC_NOERR)
		logError() << "Error while writing netCDF file:" << nc_strerror(error);
}

/**
 * The input thread for the query program
 */
static void* runInput(void* p)
{
	inputData_t* i = reinterpret_cast<inputData_t*>(p);

	// Project from mesh to sample code
	unsigned long totalArea = i->gridSize(0) * i->gridSize(1);
	double* projX = new double[totalArea];
	double* projY = new double[totalArea];

	const bool meshIsGeo = i->meshIsGeo;

	for (unsigned long y = 0; y < i->gridSize(1); y++) {
		for (unsigned long x = 0; x < i->gridSize(0); x++) {
			ularr2 pos(x, y);
                        Eigen::Array2d coord = i->minVert.block<2,1>(0,0) + pos.cast<double>() * i->gridDist.block<2,1>(0,0);
			if (meshIsGeo)
				coord *= Eigen::Array2d(DEG_TO_RAD, DEG_TO_RAD);

			projX[y*i->gridSize(0) + x] = coord(0);
			projY[y*i->gridSize(0) + x] = coord(1);
		}
	}

	// Project coordinates
	projPJ pjMesh = pj_init_plus(i->meshProj);
	projPJ pjQuery = pj_init_plus(i->queryProj);
	if (pj_transform(pjMesh, pjQuery, totalArea, 1, projX, projY, 0L) != 0)
		logError() << "Coordinate transformation failed";

	// Convert to degree
	if (i->queryIsGeo) {
		for (unsigned long x = 0; x < totalArea; x++) {
			projX[x] *= RAD_TO_DEG;
			projY[x] *= RAD_TO_DEG;
		}
	}

	// Send the input data
	i->query << (totalArea * i->gridSize(2)) << std::endl;
	for (unsigned long z = 0; z < i->gridSize(2); z++) {
		double depth = i->minVert(2) + z * i->gridDist(2);
		for (unsigned long x = 0; x < totalArea; x++)
			i->query << projX[x] << ' ' << projY[x] << ' ' << depth << std::endl;
	}

	// Send eof
	i->query << redi::peof;

	delete [] projX;
	delete [] projY;

	return 0L;
}

static float vs2mu(float vs, float rho)
{
	return vs*vs * rho;
}

static float vp2lambda(float vp, float rho, float mu)
{
	return vp*vp * rho - 2*mu;
}

int main(int argc, char* argv[])
{
	// Parse command line arguments
	utils::Args args;
	args.addOption("mesh", 'm', "The mesh for which the data should be collected");
	args.addOption("border", 'b', "Border around the mesh for which data should be included",
			utils::Args::Required, false);
	args.addOption("size", 's', "Size of the out grid (Format x:y:z)");
	args.addOption("query", 'q', "Path to the query program (Default: ./scripts/vx_lite_wrapper)",
			utils::Args::Required, false);
//	args.addOption("elevation", 'e', "Path to x_SRTM3, y_SRTM3, z_SRTM3 containing an elevation map\n"
//			"                              If empty, elevation instead of elevation offset is used for querying.",
//			utils::Args::Required, false);
	// See http://spatialreference.org/
	args.addOption("mesh-proj", 0, "Mesh coordinate projection (Default: UTM11)",
			utils::Args::Required, false);
	args.addOption("mesh-proj-geo", 0, "Mesh coordinates are geographic locations (Default: No)",
			utils::Args::Required, false);
	args.addOption("query-proj", 0, "Query coordinate projection (Default: WGS84)",
			utils::Args::Required, false);
	args.addOption("query-proj-geo", 0, "Query coordinates are geographic locations (Default: Yes)",
			utils::Args::Required, false);
	args.addOption("paraview", 'p', "Viewable by Paraview", utils::Args::No, false);
	args.addOption("chunk-size", 'c', "Chunk size for the netCDF file",
			utils::Args::Required, false);
	args.addAdditionalOption("output", "netCDF output file");

	// Parse/check command line arguments
	if (!args.parse(argc, argv) == utils::Args::Success)
		return 1;

	// Get the grid size
	std::vector<std::string> sizeVec = utils::StringUtils::split(args.getArgument<std::string>("size"), ':');
	if (sizeVec.size() != 3)
		logError() << "Size format must be \"x:y:z\"";
	ularr3 gridSize(utils::StringUtils::parse<unsigned long>(sizeVec[0]),
			utils::StringUtils::parse<unsigned long>(sizeVec[1]),
			utils::StringUtils::parse<unsigned long>(sizeVec[2]));

	logInfo() << "Grid size:" << utils::nospace
			<< "[" << gridSize(0) << ", " << gridSize(1) << ", " << gridSize(2) << "]";

	// Read the coordinates from the mesh
	const char* mesh = args.getArgument<const char*>("mesh");

	int ncFile;
	checkNcIError(nc_open(mesh, NC_NOWRITE, &ncFile));

	// Get the number of partitions
	int ncDimPart;
	checkNcIError(nc_inq_dimid(ncFile, "partitions", &ncDimPart));
	size_t partitions;
	checkNcIError(nc_inq_dimlen(ncFile, ncDimPart, &partitions));

	// Get max number of vertices
	int ncDimVertices;
	checkNcIError(nc_inq_dimid(ncFile, "vertices", &ncDimVertices));
	size_t maxVertices;
	checkNcIError(nc_inq_dimlen(ncFile, ncDimVertices, &maxVertices));

	// Get min/max vertices
	Eigen::Array3d minVert(
			std::numeric_limits<double>::infinity(),
			std::numeric_limits<double>::infinity(),
			std::numeric_limits<double>::infinity());
	Eigen::Array3d maxVert(
			-std::numeric_limits<double>::infinity(),
			-std::numeric_limits<double>::infinity(),
			-std::numeric_limits<double>::infinity());

	double* vertices = new double[maxVertices*3];

	int ncVarVrtxSize;
	checkNcIError(nc_inq_varid(ncFile, "vertex_size", &ncVarVrtxSize));
	int ncVarVrtxCoords;
	checkNcIError(nc_inq_varid(ncFile, "vertex_coordinates", &ncVarVrtxCoords));
	for (size_t i = 0; i < partitions; i++) {
		size_t start[3] = {i, 0, 0};
		int size;
		checkNcIError(nc_get_var1_int(ncFile, ncVarVrtxSize, start, &size));

		size_t count[3] = {1, static_cast<size_t>(size), 3};
		checkNcIError(nc_get_vara_double(ncFile, ncVarVrtxCoords, start, count, vertices));

		for (int j = 0; j < size; j++) {
			Eigen::Array3d v = Eigen::Map<Eigen::Array3d>(&vertices[j*3]);

			minVert = minVert.min(v);
			maxVert = maxVert.max(v);
		}
	}

	checkNcIError(nc_close(ncFile));

	delete [] vertices;

	// Add borders
	double border = args.getArgument("border", 0.);
	minVert -= Eigen::Array3d(border, border, border);
	maxVert += Eigen::Array3d(border, border, border);

	logInfo() << "Grid dimension (incl. border):" << utils::nospace
			<< "[" << minVert(0) << ", " << minVert(1) << ", " << minVert(2) << "] x ["
			<< maxVert(0) << ", " << maxVert(1) << ", " << maxVert(2) << "]";

	// Distance between grid points
	Eigen::Vector3d gridDist = (maxVert - minVert)
			* (gridSize - ularr3(1, 1, 1)).cast<double>().inverse();

	logInfo() << "Grid interval:" << utils::nospace
			<< "[" << gridDist(0) << ", " << gridDist(1) << ", " << gridDist(2) << "]";

	// Create query process
	redi::rpstream pstream(args.getArgument("query", "./scripts/vx_lite_wrapper"),
			redi::pstreambuf::pstdin | redi::pstreambuf::pstdout);

	// Start the input and error thread
	inputData_t inputData {
		minVert,
		gridSize,
		gridDist,
		args.getArgument("mesh-proj", "+proj=utm +zone=11 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"),
		args.getArgument("mesh-proj-geo", false),
		args.getArgument("query-proj", "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"),
		args.getArgument("query-proj-geo", true),
		pstream
	};

	pthread_t inputThread;
	pthread_create(&inputThread, 0L, runInput, &inputData);

	// Viewable by Paraview?
	bool paraview = args.getArgument("paraview", false);

	// Open the netCDF file
	const char* outputName = args.getAdditionalArgument<const char*>("output");
	checkNcOError(nc_create(outputName, NC_NETCDF4, &ncFile));

	// Create dimensions
	int ncDims[3];
	checkNcOError(nc_def_dim(ncFile, "x", gridSize(0), &ncDims[2]));
	checkNcOError(nc_def_dim(ncFile, "y", gridSize(1), &ncDims[1]));
	checkNcOError(nc_def_dim(ncFile, "z", gridSize(2), &ncDims[0]));

	// Create dimension variables
	int ncX, ncY, ncZ;
	checkNcOError(nc_def_var(ncFile, "x", NC_FLOAT, 1, &ncDims[2], &ncX));
	checkNcOError(nc_def_var(ncFile, "y", NC_FLOAT, 1, &ncDims[1], &ncY));
	checkNcOError(nc_def_var(ncFile, "z", NC_FLOAT, 1, &ncDims[0], &ncZ));

	// Create variables
	int ncData, ncRho, ncMu, ncLambda;
	if (paraview) {
		checkNcOError(nc_def_var(ncFile, "rho", NC_FLOAT, 3, ncDims, &ncRho));
		checkNcOError(nc_def_var(ncFile, "mu", NC_FLOAT, 3, ncDims, &ncMu));
		checkNcOError(nc_def_var(ncFile, "lambda", NC_FLOAT, 3, ncDims, &ncLambda));
	} else {
		// Create compound type
		int ncType;
		checkNcOError(nc_def_compound(ncFile, 3*sizeof(float), "material", &ncType));
		checkNcOError(nc_insert_compound(ncFile, ncType, "rho", 0, NC_FLOAT));
		checkNcOError(nc_insert_compound(ncFile, ncType, "mu", sizeof(float), NC_FLOAT));
		checkNcOError(nc_insert_compound(ncFile, ncType, "lambda", 2*sizeof(float), NC_FLOAT));

		checkNcOError(nc_def_var(ncFile, "data", ncType, 3, ncDims, &ncData));

		if (args.isSet("chunk-size")) {
			unsigned int chunkSize = args.getArgument<unsigned int>("chunk-size");

			size_t chunks[3] = {chunkSize, chunkSize, chunkSize};
			checkNcOError(nc_def_var_chunking(ncFile, ncData, NC_CHUNKED, chunks));
		}
	}

	checkNcOError(nc_enddef(ncFile));

	// Fill dimension variables
	float* x = new float[gridSize(0)];
	for (unsigned int i = 0; i < gridSize(0); i++) {
		x[i] = minVert(0) + gridDist(0) * i;
	}
	checkNcOError(nc_put_var_float(ncFile, ncX, x));
	delete [] x;

	float* y = new float[gridSize(1)];
	for (unsigned int i = 0; i < gridSize(1); i++) {
		y[i] = minVert(1) + gridDist(1) * i;
	}
	checkNcOError(nc_put_var_float(ncFile, ncY, y));
	delete [] y;

	float* z = new float[gridSize(2)];
	for (unsigned int i = 0; i < gridSize(2); i++) {
		z[i] = minVert(2) + gridDist(2) * i;
	}
	checkNcOError(nc_put_var_float(ncFile, ncZ, z));
	delete [] z;

	// Read the data from the query tool
	unsigned long totalArea = gridSize(0) * gridSize(1);
	float* data = new float[totalArea*3];

	// Initialize data with invalid values
	for (unsigned long i = 0; i < totalArea*3; i++)
		data[i] = std::numeric_limits<float>::infinity();

	for (unsigned long z = 0; z < gridSize(2); z++) {
		for (unsigned long i = 0; i < totalArea; i++) {
			// Ignore the coordinates
			float x, y, z;
			pstream.out() >> x >> y >> z;

			float vp, vs, rho;
			pstream.out() >> vp >> vs >> rho;

			float mu, lambda;
			if (vp >= MIN_VALID && vs >= MIN_VALID && rho >= MIN_VALID) {
				mu = vs2mu(vs, rho);
				lambda = vp2lambda(vp, rho, mu);

				if (paraview) {
					data[i] = rho;
					data[i + totalArea] = mu;
					data[i + totalArea*2] = lambda;
				} else {
					data[i*3] = rho;
					data[i*3 + 1] = mu;
					data[i*3 + 2] = lambda;
				}
			} else {
				if (z == 0)
					logError() << "Invalid value in deepest level.";
			}
		}

		size_t start[3] = {z, 0, 0};
		size_t count[3] = {1, gridSize(1), gridSize(0)};

		if (paraview) {
			checkNcOError(nc_put_vara_float(ncFile, ncRho, start, count, data));
			checkNcOError(nc_put_vara_float(ncFile, ncMu, start, count, &data[totalArea]));
			checkNcOError(nc_put_vara_float(ncFile, ncLambda, start, count, &data[totalArea*2]));
		} else {
			checkNcOError(nc_put_vara(ncFile, ncData, start, count, data));
		}
	}

	pthread_join(inputThread, 0L);

	// Cleanup
	checkNcOError(nc_close(ncFile));

	delete [] data;

	logInfo() << "Finished";
}