/* Copyright (c) 1997-2010
   Ewgenij Gawrilow, Michael Joswig (Technische Universitaet Darmstadt, Germany)
   http://www.polymake.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.
--------------------------------------------------------------------------------
   $Project: polymake $$Id: q_gorenstein_cone.cc 9991 2010-12-12 23:36:28Z gawrilow $
*/

#include "polymake/client.h"
#include "polymake/Integer.h"
#include "polymake/Rational.h"
#include "polymake/SparseMatrix.h"
#include "polymake/SparseVector.h"
#include "polymake/Matrix.h"
#include "polymake/Vector.h"
#include "polymake/Smith_normal_form.h"
#include "polymake/linalg.h"
#include "polymake/polytope/lattice_tools.h"

namespace polymake { namespace polytope {

    // first entry: cone is gorenstein_cone
    // second entry: Gorenstein index if cone is Gorenstein
    std::pair<bool,int> q_gorenstein_cone(Matrix<Rational> rational_rays, int dim) {

    std::pair<bool,int> gorenstein;
    gorenstein.first = false;
    gorenstein.second = -1;
    
    const Matrix<Integer> rays = divide_by_gcd(multiply_by_common_denominator(rational_rays));    
    if ( rank(rays - repeat_row(rays.row(0),rays.rows())) == dim ) 
      return gorenstein;
    
    SparseMatrix<Integer> M(rays), L, R;
    std::list< std::pair<Integer,int> > torsion;
    int r = Smith_normal_form(M, torsion, L, R, pm::True());
    
    for (int i = 0; i < r; ++i) { // adjust orientation of the transformation
      if (M(i,i) < 0) {           // all entries of M >= 0
        M(i,i) *= -1;
        L.col(i) *= -1;
      }
    }
    
    Matrix<Integer> NV = (L * M).minor(All,range(0,r-1));    
    Matrix<Integer> LNV = NV - repeat_row(NV.row(0),NV.rows());
    Matrix<Rational> ns = null_space(Matrix<Rational>(LNV));
    Vector<Integer> normal = divide_by_gcd(multiply_by_common_denominator(ns.row(0)));

    gorenstein.first = true;
    gorenstein.second = abs(NV.row(0)*normal);
    return gorenstein;
  }

  Function4perl( &q_gorenstein_cone, "q_gorenstein_cone(Matrix, $)");
} }

// Local Variables:
// mode:C++
// c-basic-offset:2
// indent-tabs-mode:nil
// End:
