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

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

#if __GNUC__==3 && __GNUC_MINOR__<=1
template class pm::IncidenceMatrix<>::row_type;
#endif

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;
}

}

void dim_from_incidence(Poly& p)
{
   const IncidenceMatrix<> VIF=p.give("VERTICES_IN_FACETS");
   const int n_vertices=VIF.cols();

   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;
   }
   d += F.size() - 1;

   p.take("DIM") << d;
}

} }

using namespace polymake;

/** @file dim_from_incidence
 *
 *  Compute the dimension of a polytope which is given combinatorially.
 *
 *  @synopsis dim_from_incidence <file>
 *
 *  @reading  VERTICES_IN_FACETS
 *  @writing  DIM
 */

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