/* 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: dim_from_incidence.cc 9298 2009-09-02 23:10:56Z gawrilow $
*/

#include <polymake.h>
#include <IncidenceMatrix.h>
#include <FacetList.h>

namespace polymake { namespace polytope {

namespace {
   template <typename Iterator>
   FacetList
   ridges_of_first(int n_vertices, Iterator set)
   {
      FacetList R(n_vertices);
      Iterator set2=set;

      for (++set2; !set2.at_end(); ++set2)
	 R.replaceMax((*set) * (*set2));

      return R;
   }
}

   int dim_from_incidence(const IncidenceMatrix<>& VIF)
   {
      const int n_vertices=VIF.cols();
      if (n_vertices<=3) return n_vertices-1;

      FacetList F=ridges_of_first(n_vertices, entire(rows(VIF)));
      int d=1;
      // for each n=F.size() <= 3 there is a unique combinatorial class
      // of polytopes with n facets
      while (F.size() > 3) {
	 F=ridges_of_first(n_vertices, entire(F));
	 ++d;
      }
      return d + F.size() - 1;
   }

   Function4perl(&dim_from_incidence, "dim_from_incidence");
} }
