/* 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: centroid.cc 9457 2010-02-08 12:23:14Z sherrmann $
*/

#include <Rational.h>
#include <polymake.h>
#include <Array.h>
#include <GenericMatrix.h>
#include <linalg.h>

namespace polymake { namespace polytope {

  template <typename _Matrix , typename Triangulation>
  void centroid(perl::Object p, const GenericMatrix<_Matrix>& Points, const Triangulation& tr)
   {
     typedef typename _Matrix::element_type Coord;
     Coord volume(0);
     Vector<Coord> centroid(Points.cols());
     int d=tr.front().size()-1;
     
     for (typename Entire<Triangulation>::const_iterator s=entire(tr); !s.at_end(); ++s) {
       const _Matrix sim=Points.minor(*s,All);
       Coord v=abs(det(sim));
       volume +=v;
       Vector<Coord> b(Points.cols());
       for (typename Entire< Rows <_Matrix > >::const_iterator i=entire(rows(sim));!i.at_end(); ++i)
	 b+=*i;
       centroid+=v*b;
     }
     centroid/=volume*(d+1);
     volume /= Integer::fac(d);

     p.take("CENTROID")<<centroid;
     p.take("VOLUME") << volume;
   }
  
   FunctionTemplate4perl("centroid(Polytope Matrix Array<Set<Int> >) : void");
    FunctionTemplate4perl("centroid(Polytope SparseMatrix Array<Set<Int>>) : void");
} }

