/* Copyright (c) 1997-2006
   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: t_volume.cc,v 1.3 2006/03/09 16:21:35 gawrilow Exp $"

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

namespace polymake { namespace topaz {

void t_volume(Poly& p)
{
  const int dim=p.give("DIM");
  const Array< Set<int> > F=p.give("FACETS");
  Matrix<Rational> GR=p.give("GEOMETRIC_REALIZATION");
  Vector<Rational> homogenization(GR.rows(),Rational(1));
  GR = homogenization | GR;
  
  Rational volume(0);
  for (Entire< Array< Set<int> > >::const_iterator f=entire(F); !f.at_end(); ++f) {
    Rational vol = std::abs(det( GR.minor(*f,All) ));
    if (vol == Rational(0))
      cerr << "t_volume: WARNING simplex of volume 0.\n";
    volume += vol;
  }
  volume /= Integer::fac(dim);
  
  p.take("VOLUME") << volume;
}
  
} }

using namespace polymake;

/** @file t_volume
 *
 *  Compute the volume of a simplicial complex.
 *
 *  @synopsis t_volume <file>
 *
 *  @reading  FACETS, GEOMETRIC_REALIZATION, DIM
 *  @writing  VOLUME
 */

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