/* 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: discard_non_vertices.cc 9522 2010-03-04 13:02:29Z kulas $
*/

#include <list>
#include <string>
#include <Rational.h>
#include <polymake.h>
#include <Vector.h>
#include <Matrix.h>
#include <Set.h>

namespace polymake { namespace tropical {

   namespace {
      Vector<Rational> normalized(const Vector<Rational>& v) {
	 Rational m= accumulate(v, operations::min());
	 return v-same_element_vector(m,v.dim());
      }
   }

void discard_non_vertices(perl::Object p, const char* points_section)
{
   Matrix<Rational> V=p.give(points_section);
   const int n(V.rows()), d(V.cols());
   Set< Vector<Rational> > vertex_coords;
   Set<int> vertex_indices;
 
   for (int i=0; i<n; ++i) {
      const Rational c(V(i,0));
      V[i]-=same_element_vector(c,d);
      if (vertex_coords.contains(V[i])) continue; // notice that it is possible that a point arises more than once
      Set<int> sectors;
      for (int j=0; sectors.size()<d && j<n; ++j) {
	 if (V[j]==V[i]) continue;
	 const Vector<Rational> diff(normalized(V[j]-V[i]));
	 for (int k=0; k<d; ++k)
	    if (diff[k]==0) sectors+=k;
      }
      if (sectors.size()<d) {
	 vertex_coords+=V[i];
	 vertex_indices+=i;
      }
   }
   p.take("VERTICES") << Matrix<Rational>(V.minor(vertex_indices,sequence(0,d)));
}
  UserFunction4perl("# @category Other"
		    "# Given points in the tropical projective space, discard all the non-vertices of the tropical convex hull."
		    "# @param TropicalPolytope P"
		    "# @param char point_section",
		    &discard_non_vertices,"discard_non_vertices");
  
} }
