/* 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 <Rational.h>
#include <Array.h>
#include <Set.h>
#include <Matrix.h>
#include <Poly.h>
#include <PowerSet.h>
#include <hypersimplex.h>

namespace polymake { namespace polytope {

void metric2hyp_triang(Poly& pout, Poly& pin) {
   const Array< Set <int> > ftv=pin.give("FACETS_THRU_VERTICES");
   const int n_vertices=ftv.size();
   const Set<int> far_face=pin.give("FAR_FACE");
   const int n=far_face.size();
   
   //all simplexes of the triangulation
   Set< Set <int> > triang;
   
   for (int i=0; i<n_vertices;++i) 
      if (!far_face.contains(i)) {
	 Set<int> simplex;
	 bool stop=false;
	 bool pstop=false;
	 for (Entire<Set <int> >::const_iterator j=entire(ftv[i]);!stop && !j.at_end(); ++j)
	    if (*j>=n) simplex.insert(*j-n);
	    else if (pstop || ftv[i].size()!=n+1) stop=true;
	    else pstop=true;
	 
	 if (!stop) triang.insert(simplex);
      }
   
   Array< Set <int> > triangA(triang.size(),triang.begin());
   
   hypersimplex(pout,n-1,2);
   pout.take("TRIANGULATION") << triangA;
 
}

} }

using namespace polymake;

/** @file metric2hyp_triang
 *
 *  Given a generic finite metric space, construct the associated (i.e. dual) triangulation of the hypersimplex.
 *  The newly created object is of type RationalPolytope.
 *
 *  @synopsis metric2hyp_triang <outfile> <infile>
 *
 *  @reading  FACETS_THRU_VERTICES FAR_FACE
 *  @writes   AMBIENT_DIM, DIM, VERTICES, N_VERTICES, TRIANGULATION
 *
 *  @index clients Tight Spans
 *
 *  @author Sven Herrmann
 */

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