/* 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: schlegel_vertices.cc,v 1.9 2004/09/20 16:06:52 gawrilow Exp $"

#include <Rational.h>
#include <Poly.h>
#include <Matrix.h>
#include <ListMatrix.h>
#include <linalg.h>

namespace polymake { namespace polytope {

void schlegel_vertices(Poly& S, Poly& p, const char *proj_points, const char **points, int n_points)
{
   const Matrix<Rational> tau=S.give("TRANSFORM"),
                          F=p.give("FACETS");
   const int proj_facet=S.give("FACET");
   ListMatrix< Vector<Rational> > Points;
   for (int i=0; i<n_points; ++i) {
      const Matrix<Rational> P=p.give(points[i]);
      Points /= P;
   }

   Matrix<double> P(Points*tau);	// points projected on the facet: need dehomogenization
   for (Entire< Rows< Matrix<double> > >::iterator p_i=entire(rows(P));  !p_i.at_end(); ++p_i)
      p_i->dehomogenize();

   /* rotation matrix: take an affine basis of the projection facet.
      We want a negatively oriented coordinate system, that is, det(R / F)<0,
      since the view point lies on the negative side of the facet. */
   Matrix<double> R(null_space_oriented(F[proj_facet].slice(1), -1));
   orthogonalize(entire(rows(R)));
   normalize(entire(rows(R)));

   const Matrix<double> result= P.minor(All, range(1,P.cols()-1)) * T(R);
   S.take(proj_points) << result;
}

} }

using namespace polymake;

/** @file schlegel_vertices
 *
 *  Apply the Schlegel transformation matrix to the given set of points,
 *  then rotate the projection facet and obtain affine coordinates.
 *
 *  @synopsis schlegel_vertices <file> <points_in> <points_out>
 *
 *  @reading SCHLEGEL_TRANSFORM, SCHLEGEL_PARAMS, FACETS, <points_in>
 *  @writing <points_out>
 */

int main(int argc, const char *argv[])
{
   if (argc<5) {
      cerr << "usage: " << argv[0] << " <SchlegelDiagram> <Polytope> <points_out> <points_in> ..." << endl;
      return 1;
   }
   try {
      Poly S(argv[1], ios::in | ios::out);
      Poly p(argv[2], ios::in);
      polytope::schlegel_vertices(S, p, argv[3], argv+4, argc-4);
   }
   catch (const std::exception& e) {
      cerr << e.what() << endl;
      return 1;
   }
   return 0;
}

// Local Variables:
// c-basic-offset:3
// End:
