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

#include <Poly.h>
#include <HasseDiagram.h>
#include <argv_options.h>

namespace polymake { namespace polytope {

namespace {

template <typename Iterator> inline
void fill_graph(Graph<>& G, Iterator vertex_set_i, int first_vertex) {
   for (; !vertex_set_i.at_end(); ++vertex_set_i)
      (void)G.edge(vertex_set_i->front() - first_vertex,
		   vertex_set_i->back() - first_vertex);
}

}

void graph_from_face_lattice(Poly& p, bool primal)
{
   const HasseDiagram<> D=p.give("HASSE_DIAGRAM");
   const sequence vertex_nodes=D.nodes_of_dim(primal ? 0 : -1);
   Graph<> G(vertex_nodes.size());

   if (primal) {
      // vertex sets stored by the polytope edge faces (dim==1)
      // are exactly the vertex pairs we need for the graph
      fill_graph(G, entire(select(nodes(D), D.nodes_of_dim(1))), 0);
   } else {
      // the node numbers of the polytope facets (which are neighbors of the ridge faces, dim==-2)
      // relate to the whole Hasse diagram graph!
      fill_graph(G, entire(select(rows(neighborhood_matrix(D)), D.nodes_of_dim(-2))), vertex_nodes.front());
   }

   p.take(primal ? "GRAPH" : "DUAL_GRAPH") << G;
}

} }

using namespace polymake;

/** @file graph_from_face_lattice
 *
 *  Compute the vertex or facet graph of a polyhedron from its face lattice.
 *
 *  $mode$ may be -primal or -dual
 *
 *  @synopsis graph_from_face_lattice <file> <mode>
 *
 *  @reading  HASSE_DIAGRAM
 *  @writing  in primal mode: GRAPH
 *            in dual mode:   DUAL_GRAPH
 */

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