/* 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: faces_to_facets.cc,v 1.6 2005/09/23 14:05:48 witte Exp $"

#include <Poly.h>
#include <Array.h>
#include <FacetList.h>
#include <Set.h>

namespace polymake { namespace topaz {

void faces_to_facets(Poly& p, const char* input_section)
{
   typedef Array< std::list<int> > face_list;
   const face_list F_in = p.give(input_section);
   
   FacetList F;
   Set<int> V;
      
   for (Entire<face_list>::const_iterator f_it=entire(F_in); !f_it.at_end(); ++f_it) {
      // provide vertex ordering
      Set<int> facet;
      accumulate_in(entire(*f_it), operations::add(), facet);

      // add facet to vertex set
      V+=facet;
      F.insertMax(facet);
   }

   // checking numbering
   bool renumber= !V.empty() && (V.front()!=0 || V.back()+1!=V.size());

   if (renumber) F.squeeze();
   if (F.empty()) {
      p.take("FACETS") << Array< Set<int> >(1, V);
   } else {
      p.take("FACETS") << F;
   }

   p.take("VERTEX_LABELS") << as_array(V);
}
   
} }

using namespace polymake;
   
/** @file faces_to_facets
 *
 *  Consistency check and redundancy removal.
 *
 *  @synopsis faces_to_facets <file> <input_section>
 *
 *  @reading  <input_section>
 *  @writing  FACETS, VERTEX_LABELS
 */

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


// Local Variables:
// mode:C++
// c-basic-offset:3
// End:
