/* Copyright (c) 1997-2009
   Ewgenij Gawrilow, Michael Joswig (Technische Universitaet Darmstadt, Germany)
   http://www.polymake.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.
--------------------------------------------------------------------------------
   $Project: polymake $$Id: signature.cc 9298 2009-09-02 23:10:56Z gawrilow $
*/

#include <polymake.h>
#include <Matrix.h>
#include <Graph.h>
#include <linalg.h>
#include <Rational.h>
#include <bipartite.h>

namespace polymake { namespace topaz {

int signature(perl::Object p)
{
   const Graph<> DG=p.give("DUAL_GRAPH.ADJACENCY");
   Matrix<Rational> GR=p.give("GEOMETRIC_REALIZATION");
   GR = ones_vector<Rational>(GR.rows()) | GR;

   const Array< Set<int> > F=p.give("FACETS");
   graph::BFSiterator<Graph<>, graph::Visitor<graph::BipartiteColoring> > it(DG, nodes(DG).front());
   int sign=0;

   try {
      while (!it.at_end()) ++it;

      // if it has survived so far, then the dual graph is really bipartite
      for (int f=0, end=F.size(); f<end; ++f)
	 if ( abs(numerator(det(GR.minor(F[f],All))))%2 == 1 )
	    sign += it.node_visitor().get_color(f);

      sign=abs(sign);
   } catch (int) {
      sign=-1;
   }

   return sign;
}

Function4perl(&signature, "signature(SimplicialComplex)");

} }
