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

#include <algorithm>
#include <Integer.h>
#include <Poly.h>
#include <Vector.h>

namespace polymake { namespace polytope {

void h_vector(Poly& p, bool simplicial)
{
   Vector<Integer> f=p.give("F_VECTOR");
   if (!simplicial) std::reverse(f.begin(), f.end());

   const int d=f.size();
   Vector<Integer> h(d+1);
   Vector<Integer>::iterator h_k=h.begin();
   for (int k=0, startsign=1;  k<=d;  ++k, ++h_k, startsign=-startsign) {
      *h_k = startsign * Integer::binom(d,d-k);
      for (int i=1, sign=-startsign;  i<=k;  ++i, sign=-sign)
	 *h_k += sign * Integer::binom(d-i,d-k) * f[i-1];
   }

   p.take("H_VECTOR") << h;
}

} }

using namespace polymake;

/** @file h_vector
 *  Compute the h-vector of a simplicial or simple polytope from the f-vector.
 *
 *  @synopsis h_vector <file> { SIMPLICIAL,SIMPLE }
 *
 *  @reading  SIMPLICIAL or SIMPLE, F_VECTOR
 *  @writing  H_VECTOR
 */

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