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

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

namespace polymake { namespace polytope {

void voronoi(Poly& v, Poly& p, const char* input_section)
{
   const Matrix<Rational> points=p.give(input_section);
   const int n=points.rows(), d=points.cols();
   Vector<Rational> min_val=points[0];
   Vector<Rational> max_val=min_val;
   ListMatrix< Vector<Rational> > voronoi_ineq(0,d+1);
   Rational maxx(0);

   for (int i=0; i<n; ++i) {
      if (points(i,0)!=1)
	 throw std::runtime_error("voronoi: input points must be finite");
      Vector<Rational> next_voronoi_ineq=unit_vector<Rational>(d+1,d);
      next_voronoi_ineq[0]=sqr(points[i])-1;
      if (next_voronoi_ineq[0]>maxx) maxx=next_voronoi_ineq[0];
      for (int k=1; k<d; ++k) {
	 const Rational& x(points(i,k));
	 if (x>max_val[k])
	    max_val[k]=x;
	 else if (x<min_val[k])
	    min_val[k]=x;
	 next_voronoi_ineq[k]=(-2)*x;
      }
      voronoi_ineq /= next_voronoi_ineq;
   }

   // since all SITES are required to be distinct, the defining inequalities are, in fact, facets;
   // the unbounded face is not a facet
   v.take("FACETS") << voronoi_ineq;
   v.take("SITES") << points;
}

} } 

using namespace polymake;

/** @file voronoi
 *
 *  Compute the Voronoi polyhedron of a given set of points.  The polyhedron is unbounded.  Introduce artificial cut facets later
 *  (e.g., for visualization); this must be done after the vertex have been computed.
 *
 *  @synopsis voronoi <output_file> <input_file> <input_section>
 *
 *  @reading <input_section>
 *  @writing INEQUALITIES
 */

int main(int argc, char *argv[])
{
   if (argc!=4) {
      cerr << "usage: " << argv[0] << " <output_file> <input_file> <input_section>" << endl;
      return 1;
   }
   try {
      Poly p(argv[2], ios::in);
      Poly v(argv[1], ios::out | ios::trunc);
      polytope::voronoi(v,p,argv[3]);
   } catch (const std::exception& e) {
      cerr << e.what() << endl;
      return 1;
   }
   return 0;
}
