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

#include <cstdlib>
#include <Rational.h>
#include <Poly.h>
#include <Vector.h>
#include <Matrix.h>
#include <Graph.h>

namespace polymake {
namespace polytope {

void edge_middle(Poly& p_out, Poly& p_in)
{
   const bool bounded=p_in.give("BOUNDED");
   if (!bounded)
      throw std::runtime_error("unbounded polyhedron");

   const Matrix<Rational> V=p_in.give("VERTICES");
   const Graph<> G=p_in.give("GRAPH");

   Matrix<Rational> V_out(edges(G).size(), V.cols());
   Rows< Matrix<Rational> >::iterator v_out=rows(V_out).begin();
   for (Entire< Edges< Graph<> > >::const_iterator e=entire(edges(G));  !e.at_end();  ++e, ++v_out)
      *v_out = (V[e.from_node()] + V[e.to_node()]) / 2;
	    
   p_out.take("VERTICES") << V_out;
   p_out.take("BOUNDED") << true;
}

} }
using namespace polymake;

/** @file edge_middle
 *
 *  Produce the convex hull of all edge middle points of some polytope.
 *  The polytope must be bounded.
 *
 *  @synopsis edge_middle <output_file> <input_file>
 *
 *  @reading  BOUNDED, VERTICES, GRAPH
 *  @writing  BOUNDED, VERTICES
 *
 *  @index clients Producing a new polyhedron from others
 */

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