/* 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: pile.cc,v 1.17 2004/06/22 16:23:09 gawrilow Exp $"

#include <Rational.h>
#include <Poly.h>
#include <Vector.h>
#include <Matrix.h>
#include <MultiDimCounter.h>

namespace polymake { namespace polytope {

void pile(Poly& p, const Vector<int>& sizes)
{
   const int d=sizes.size();
   int n=1;
   for (Entire< Vector<int> >::const_iterator s=entire(sizes); !s.at_end(); ++s)
      n *= *s+1;

   Matrix<Rational> V(n,d+2);
   const int factor(d*d);
   Vector<Rational> limits(sizes);
   limits/=2;
   Rows< Matrix<Rational> >::iterator V_i=rows(V).begin();

   for (MultiDimCounter<false,Rational> x(-limits, limits+ones_vector<Rational>(d)); !x.at_end(); ++x, ++V_i)
      *V_i = 1 | *x | (sqr(*x) / factor);

   p.take("VERTICES") << V;
   p.take("N_VERTICES") << n;
}

} }

using namespace polymake;

/** @file pile
 *
 *  Produce a $(d+1)$-dimensional polytope from a pile of cubes.
 *  Start with a $d$-dimensional pile of cubes.  Take a generic convex function
 *  to lift this polytopal complex to the boundary of a $(d+1)$-polytope.
 *
 *  factor_i gives the number of boxes in the i-th dimension.
 *
 *  @synopsis pile <file> <d> <factor_1> .. <factor_d>
 *
 *  @writing  VERTICES, N_VERTICES
 *
 *  @index clients Producing from scratch
 */

int main(int argc, const char *argv[]) {
   const char* usage=" <file> <d> <factor_1> .. <factor_d>";
   if (argc<3) {
      cerr << "usage: " << argv[0] << usage << endl;
      return 1;
   }
   const int d=atoi(argv[2]);
   if (argc!=d+3) {
      cerr << "usage: " << argv[0] << usage << endl;
      return 1;
   }
   try {
      const Vector<int> sizes(d, attach_converter<int>(ptr2container(argv+3)).begin());
      Poly p(argv[1], ios::out | ios::trunc);
      polytope::pile(p, sizes);
   }
   catch (const std::exception& e) {
      cerr << e.what() << endl;
      return 1;
   }
   return 0;
}
