/* 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: pvolume.cc,v 1.8 2006/03/09 16:21:35 gawrilow Exp $"

#include <Rational.h>
#include <Poly.h>
#include <Array.h>
#include <Matrix.h>
#include <linalg.h>

namespace polymake { namespace polytope {

void volume(Poly& p, const char* points_section, const char* triangulation_section)
{
   const bool bounded=p.give("BOUNDED");
   if (!bounded) {
      p.take("VOLUME") << Poly::undefined();
      return;
   }

   const Matrix<Rational> Points=p.give(points_section);
   typedef Array< Set<int> > triangulation;
   const triangulation Triangulation=p.give(triangulation_section);

   Rational volume(0);
   for (Entire<triangulation>::const_iterator s=entire(Triangulation); !s.at_end(); ++s)
      volume += std::abs(det( Points.minor(*s,All) ));
   volume /= Integer::fac(Points.cols()-1);

   p.take("VOLUME") << volume;
}

} }

using namespace polymake;

/** @file pvolume
 *
 *  Compute the volume of a polytope using its triangulation.
 *
 *  @synopsis pvolume <file> <points_section> <triangulation_section>
 *
 *  @reading  BOUNDED, <points_section>, <triangulation_section>
 *  @writing  VOLUME
 */

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