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

#include <Graph.h>
#include <Rational.h>
#include <Poly.h>
#include <Matrix.h>
#include <lrs_interface.h>

namespace polymake { namespace polytope {

void graph_from_vertices(Poly& p)
{
   const Matrix<Rational> Vertices=p.give("VERTICES");
   const int n_vertices = Vertices.rows();
   const int dim = Vertices.cols() -1;
   Graph<> graph(n_vertices);

   Matrix<Rational> Ineq(n_vertices,dim+1);
   Matrix<Rational> Eq;
   lrs_interface::solver LRS;

   for (int i = 0; i < n_vertices-1; i++) {
      for (int j = i+1; j < n_vertices; j++) {
	 for (int k = 0; k < n_vertices; k++) {
	    if ( k == i ) {
	       Ineq[k] = Vertices[j] - Vertices[i];
	    } else {
	       Ineq[k] = Vertices[i] - Vertices[k];
	       Ineq[k][0] = (k!=j)?-1:0;
	    }
	 }

	 if (LRS.check_feasibility(Ineq,Eq).first) {
	    graph.edge(i,j);
	 }
      }
   }
   p.take("GRAPH") << graph;
}

} }

using namespace polymake;

/** @file graph_from_vertices
 *
 *  Find the vertex graph of a polytope given by its vertices, without calculating the convex hull.
 *  Currently, can handle only bounded polytopes.
 *
 *  @synopsis graph_from_vertices <file>
 *
 *  @reading  VERTICES
 *  @writing  GRAPH
 */

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