/* Copyright (c) 1997-2004
   Ewgenij Gawrilow, Michael Joswig (Technische Universitaet Berlin, Germany)
   http://www.math.tu-berlin.de/polymake,  mailto:polymake@math.tu-berlin.de

   This program is free software; you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by the
   Free Software Foundation; either version 2, or (at your option) any
   later version: http://www.gnu.org/licenses/gpl.txt.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
*/

#ident "$Project: polymake $$Id: inner_point.cc,v 1.18 2004/09/20 16:12:43 gawrilow Exp $"

#include <Poly.h>
#include <Rational.h>
#include <linalg.h>
#include <Matrix.h>
#include <Vector.h>

namespace polymake { namespace polytope {

template <typename Coord>
void inner_point(Poly& p, const char *matrix_section, const char *result_section)
{
   const Matrix<Coord> V=p.give(matrix_section);
   const Set<int> b=basis_rows(V);

   // center of gravity of the basis vectors
   const Vector<Coord> rel_int_pt=average(rows(V.minor(b,All)));

   // we require rel_int_pt to be affine
   // otherwise we might be in trouble with the orientation
   if (!rel_int_pt[0])
      throw std::runtime_error("computed point not affine");

   p.take(result_section) << rel_int_pt;
}

} }

using namespace polymake;

/** @file inner_point
 *
 *  Compute a true inner point of a convex hull of the given set of points
 *
 *  @synopsis inner_point <file> <matrix_section> <inner_point_section>
 *
 *  @reading  <matrix_section>
 *  @writing  <inner_point_section>
 */

int main (int argc, char *argv[])
{
   if (argc != 4) {
      cerr << "usage: " << argv[0] << " <file> <matrix_section> <inner_point_section>" << endl;
      return 1;
   }
   try {
      Poly p(argv[1], ios::in | ios::out);
      if (p.isa("RationalPolytope")) {
	 polytope::inner_point<Rational>(p, argv[2], argv[3]);
      } else if (p.isa("FloatPolytope")) {
	 polytope::inner_point<double>(p, argv[2], argv[3]);
      } else {
	 throw std::runtime_error("don't know how to proceed with " + p.type());
      }
   }
   catch (const std::exception& e) {
      cerr << e.what() << endl;
      return 1;
   }
   return 0;
}
