/* 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: edge_lengths.cc,v 1.2 2004/06/22 16:22:36 gawrilow Exp $"

#include <cmath>

#include <Poly.h>
#include <Rational.h>
#include <argv_options.h>
#include <Graph.h>
#include <Matrix.h>

namespace {

  enum { opt_redirect };

} // end unnamed namespace

namespace polymake { namespace graph {

void edge_lengths(Poly& p, const char* coords_section, const char* graph_section, const char* result_section, const argv_option *options)
{
   const Matrix<Rational> coords=p.give(coords_section);
   Graph<int,double> G;

   if (options[opt_redirect]) {
      const Graph<int> G_without_edge_attrs=p.give(graph_section);
      G=G_without_edge_attrs;
   } else {
      const Graph<> G_without_any_attrs=p.give(graph_section);
      G=G_without_any_attrs;
      for (int i=G.nodes()-1; i>=0; --i) G.node(i)=i;
   }

   for (Entire< Graph<int,double>::edge_container >::iterator e_it=entire(edges(G)); !e_it.at_end(); ++e_it)
      *e_it=std::sqrt(double(sqr(coords[G.node(e_it.from_node())]-coords[G.node(e_it.to_node())])));

   p.take(result_section) << G;
}

} }

using namespace polymake;

/** @file edge_lengths
 *
 *  Compute the lenghts of all edges of a given graph with assigned coordinates for the nodes.  If the -redirect option is set
 *  then it is assumed that the graph has indices as node attributes which point into the coordinate section.
 *
 *  @synopsis edge_lengths <file> <coords_section> <graph_section> <result_section> [ -redirect ]
 *
 *  @reading  <coords_section>, <graph_section>
 *  @writing  <result_section>
 */

int main(int argc, const char *argv[]) {
   argv_option options[]={ { "-redirect" } };

   if (!extract_options(argc,argv,4,options) || argc < 5) {
      cerr << "usage: " << argv[0] << " <file> <coords_section> <graph_section> <result_section> [ -redirect ] \n";
      return 1;
   }
   try {
      Poly p(argv[1], ios::in | ios::out);
      graph::edge_lengths(p, argv[2], argv[3], argv[4], options);
   }
   catch (const std::exception& e) {
      cerr << e.what() << endl;
      return 1;
   }
   return 0;
}
