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

#include <Integer.h>
#include <Poly.h>
#include <Matrix.h>
#include <HasseDiagram.h>

namespace polymake { namespace polytope {

namespace {

template <typename IMatrix>
void move_edges(GenericIncidenceMatrix<IMatrix>& G, const sequence& row_range)
{
   for (typename Rows<IMatrix>::iterator r=rows(G).begin()+row_range.front(),
	                                 r_last=rows(G).begin()+row_range.back();  r<=r_last;  ++r) {
      typename Rows<IMatrix>::value_type::iterator e=r->begin();
      for (int n=r->size(); n>0; --n) {
	 *r += G.row(*e);
	 r->erase(e++);
      }
   }
}

}

void f2_vector(Poly& p)
{
   HasseDiagram<> G=p.give("HASSE_DIAGRAM");
   const int d=G.dim();

   Matrix<Integer> F2(d,d);
   F2(0,0) = G.nodes_of_dim(0).size();

   for (int i=1; i<d; ++i) {
      if (i>1) move_edges(neighborhood_matrix(G), G.nodes_of_dim(0,i-2));
      for (int j=0; j<i; ++j) {
	 Integer cnt=0;
	 for (Entire<sequence>::iterator f=entire(G.nodes_of_dim(j)); !f.at_end(); ++f)
	    cnt += G.out_degree(*f);
	 F2(i,j)=F2(j,i)=cnt;
      }
      F2(i,i) = G.nodes_of_dim(i).size();
   }

   p.take("F2_VECTOR") << F2;
   p.take("F_VECTOR") << F2.diagonal();
}

} }

using namespace polymake;

/** @file f2_vector
 *
 *  Compute the f_vector and f2_vector of a polytope.
 *
 *  @synopsis f2_vector <file>
 *
 *  @reading  HASSE_DIAGRAM
 *  @writing  F_VECTOR, F2_VECTOR
 */
int main(int argc, const char *argv[]) {
   if (argc != 2) {
      cerr << "usage: " << argv[0] << " <file>" << endl;
      return 1;
   }
   try {
      Poly p(argv[1], ios::in | ios::out);
      polytope::f2_vector(p);
   }
   catch (const std::exception& e) {
      cerr << e.what() << endl;
      return 1;
   }
   return 0;
}
