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

#include <permutations.h>
#include <Poly.h>
#include <Matrix.h>
#include <Array.h>
#include <cstdlib>

namespace polymake { namespace polytope {

void birkhoff(Poly& p, const int n, const bool even)
{
   Matrix<int> V(even ? Integer::fac(n)/2 : Integer::fac(n),  n*n+1);
   Rows< Matrix<int> >::iterator v_i=rows(V).begin();
  
   AllPermutations<> perms(n);
   for (AllPermutations<>::const_iterator perm=entire(perms);
	!perm.at_end(); ++perm, ++v_i) {
      *v_i = 1 | concat_rows( permutation_matrix<int>(*perm) );

      // only every second permutation is even
      if (even)
	 ++perm;
   }

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

} }

using namespace polymake;

/** @file birkhoff
 *
 *  Constructs a VERY INTERESTING polytope.
 *
 *  @synopsis birkhoff <file> <n> [ -even ]
 *
 *  @writing  VERTICES
 *
 *  @index clients Producing from scratch
 */
int main(int argc, const char *argv[])
{
   if (argc<2 || argc>4) {
      cerr << "usage: " << argv[0] << " <file> <n> [ -even ]" << endl;
      return 1;
   }
   try {
      Poly p(argv[1], ios::out | ios::trunc);
      int n=atoi(argv[2]);
      polytope::birkhoff(p, n, argc>3 && !strcmp(argv[3],"-even"));
   }
   catch (const std::exception& e) {
      cerr << e.what() << endl;
      return 1;
   }
   return 0;
}
