/* 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: center.cc,v 1.14 2004/06/22 16:23:10 gawrilow Exp $"

#include <Rational.h>
#include <Poly.h>
#include <Vector.h>
#include <SparseMatrix.h>
#include <transform.h>

namespace polymake { namespace polytope {

void center(Poly& p_out, Poly& p_in, const std::string& comment)
{
   // read some point in the relative interior
   const Vector<Rational> point=p_in.give("REL_INT_POINT");
   const int d = point.dim();

   // check if point is affine
   if (!point[0])
      throw std::runtime_error("relative interior point not affine");

   SparseMatrix<Rational> tau=unit_matrix<Rational>(d);
   tau[0].slice(1)=-point.slice(1);
   polytope::transform(p_out, p_in, comment, tau);

   p_out.take("CENTERED") << comment << true;
}

} }

using namespace polymake;

/** @file center
 *
 *  Make a polyhedron centered.
 *  Apply a linear transformation to a polyhedron such that a relatively interior point
 *  (preferably the vertex barycenter) is moved to the origin $(1,0,...,0)$.
 *
 *  @synopsis center <output_file> <input_file>
 *
 *  @reading  VERTICES, FACETS, AFFINE_HULL, REL_INT_POINT
 *  @writing  VERTICES, FACETS, AFFINE_HULL, REVERSE_TRANSFORMATION, CENTERED
 *
 *  @index clients Transforming a polyhedron
 */

int main(int argc, const char *argv[]) {
   if (argc != 3) {
      cerr << "usage: " << argv[0] << " <out_file> <in_file>" << endl;
      return 1;
   }
   try {
      Poly p_in(argv[2], ios::in);
      Poly p_out(argv[1], ios::out | ios::trunc);
      polytope::center(p_out, p_in, polytope::transform_comment("center", argv[2]));
   }
   catch (const std::exception& e) {
      cerr << e.what() << endl;
      return 1;
   }
   return 0;
}
