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

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

namespace polymake { namespace polytope {

void proj(Poly& p_out, Poly& p_in, const Array<int>& indices, bool negation)
{
   const Matrix<Rational> Points=p_in.give("VERTICES | POINTS");
   const int dim=Points.cols()-1;

   Set<int> coords;
   if (indices.empty()) {
      coords=basis_cols(Points);
   } else {
      for (Entire< Array<int> >::const_iterator i=entire(indices); !i.at_end(); ++i) {
	 if (*i<1 || *i>dim)
	    throw std::runtime_error("index out of range");
	 coords+=*i;
      }
      if (negation)
	 coords=range(0,dim)-coords;
      else 
	 coords+=0;
   }

   p_out.take("POINTS") << Points.minor(All,coords);
}

} }

using namespace polymake;

/** @file proj
 *
 *  Make a orthogonal projection of a polyhedron.
 *
 *  @synopsis proj <output_file> <input_file> [-] [ <k1> [ <k2> ... ] ]
 *  @usage    The subspace the polyhedron is projected on is given by the coordinate numbers
 *            $k<sub>i</sub>$. The dash argument inverts the coordinate list.
 *            If no coordinates are specified the polytope is projected by omitting
 *            "redundant" columns, i.e., the projection becomes full-dimenionsional without
 *            changing the combinatorial type.
 *
 *  @reading  AMBIENT_DIM, POINTS | VERTICES
 *  @writing  POINTS
 *
 *  @index clients Producing a new polyhedron from others
 */

int main(int argc, const char *argv[]) {
   const bool negation=(argc>3) && !strcmp(argv[3],"-");
   if (argc<3 || negation && argc==4) {
      cerr << "usage: " << argv[0] << " <outfile> <infile> [ [-] <k1> [<k2> ...] ]" << endl;
      return 1;
   }
   try {
      Poly p_in(argv[2], ios::in);
      Poly p_out(argv[1], ios::out | ios::trunc);
      const Array<int> indices(argc-3-negation, attach_converter<int>(ptr2container(argv+3+negation)).begin());
      polytope::proj(p_out, p_in, indices, negation);
   }
   catch (const std::exception& e) {
      cerr << e.what() << endl;
      return 1;
   }
   return 0;
}
