/* 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.
*/

#include <Poly.h>
#include <Array.h>
#include <PowerSet.h>
#include <IncidenceMatrix.h>

namespace polymake { namespace polytope {

void triang_boundary(Poly& p)
{
   typedef Array< PowerSet<int> > triang_boundary_type;

   IncidenceMatrix<> VIF=p.give("VERTICES_IN_FACETS");
   const Array< Set<int> > triang=p.give("TRIANGULATION");
   const int dim=triang[0].size()-1;		// #vertices(simplex) == dim+1
   triang_boundary_type triang_boundary(VIF.rows());

   // simplicial facets need not be triangulated
   for (Entire< Rows< IncidenceMatrix<> > >::iterator f=entire(rows(VIF)); !f.at_end(); ++f)
      if (f->size() == dim) {
	 triang_boundary[f.index()].push_back(*f);
	 f->clear();
      }

   for (Entire< Array< Set<int> > >::const_iterator t=entire(triang); !t.at_end(); ++t) {
      typedef Subsets_less_1<const Set<int>&> faces;
      for (Entire<faces>::const_iterator face=entire(all_subsets_less_1(*t)); !face.at_end(); ++face) {
	 faces::value_type::const_iterator v=entire(*face);
	 Set<int> common_facets=VIF.col(*v);
	 for (++v; !v.at_end() && !common_facets.empty(); ++v)
	    common_facets *= VIF.col(*v);
	 if (!common_facets.empty())
	    triang_boundary[common_facets.front()] += *face;
      }
   }

   p.take("TRIANGULATION_BOUNDARY") << triang_boundary;
}

} }

using namespace polymake;

/** @file triang_boundary
 *
 *  For a given polytope triangulation, find the trace on its surface (triangulation of facets)
 *
 *  @synopsis triang_boundary <file>
 *
 *  @reading  VERTICES_IN_FACETS, TRIANGULATION
 *  @writing  TRIANGULATION_BOUNDARY
 */

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