/* -*- C++ -*-
 * src/lemon/graph_to_eps.h - Part of LEMON, a generic C++ optimization library
 *
 * Copyright (C) 2005 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
 * (Egervary Combinatorial Optimization Research Group, EGRES).
 *
 * Permission to use, modify and distribute this software is granted
 * provided that this copyright notice appears in all copies. For
 * precise terms see the accompanying LICENSE file.
 *
 * This software is provided "AS IS" with no warranty of any kind,
 * express or implied, and with no claim as to its suitability for any
 * purpose.
 *
 */

#ifndef LEMON_GRAPH_TO_EPS_H
#define LEMON_GRAPH_TO_EPS_H

#include <sys/time.h>
#include <time.h>

#include<iostream>
#include<fstream>
#include<sstream>
#include<algorithm>
#include<vector>

#include<lemon/xy.h>
#include<lemon/maps.h>
#include<lemon/bezier.h>

///\ingroup misc
///\file
///\brief Simple graph drawer
///
///\author Alpar Juttner

namespace lemon {

///Data structure representing RGB colors.

///Data structure representing RGB colors.
///\ingroup misc
class Color
{
  double _r,_g,_b;
public:
  ///Default constructor
  Color() {}
  ///Constructor
  Color(double r,double g,double b) :_r(r),_g(g),_b(b) {};
  ///Returns the red component

  ///\todo \c red() could be a better name...
  double getR() const {return _r;}
  ///Returns the green component
  double getG() const {return _g;}
  ///Returns the blue component
  double getB() const {return _b;}
  ///Set the color components
  void set(double r,double g,double b) { _r=r;_g=g;_b=b; };
};

///Maps <tt>int</tt>s to different \ref Color "Color"s

///This map assing one of the predefined \ref Color "Color"s
///to each <tt>int</tt>. It is possible to change the colors as well as their
///number. The integer range is cyclically mapped to the provided set of colors.
///
///This is a true \ref concept::ReferenceMap "reference map", so you can also
///change the actual colors.

class ColorSet : public MapBase<int,Color>
{
  std::vector<Color> colors;
public:
  ///Constructor

  ///Constructor
  ///\param have_white indicates wheter white is
  ///amongst the provided color (\c true) or not (\c false). If it is true,
  ///white will be assigned to \c 0.
  ///\param num the number of the allocated colors. If it is \c 0
  ///the default color configuration is set up (26 color plus the while).
  ///If \c num is less then 26/27 then the default color list is cut. Otherwise
  ///the color list is filled repeatedly with the default color list.
  ColorSet(bool have_white=false,int num=0)
  {
    do {
      if(have_white) colors.push_back(Color(1,1,1));

      colors.push_back(Color(0,0,0));
      colors.push_back(Color(1,0,0));
      colors.push_back(Color(0,1,0));
      colors.push_back(Color(0,0,1));
      colors.push_back(Color(1,1,0));
      colors.push_back(Color(1,0,1));
      colors.push_back(Color(0,1,1));
      
      colors.push_back(Color(.5,0,0));
      colors.push_back(Color(0,.5,0));
      colors.push_back(Color(0,0,.5));
      colors.push_back(Color(.5,.5,0));
      colors.push_back(Color(.5,0,.5));
      colors.push_back(Color(0,.5,.5));
      
      colors.push_back(Color(.5,.5,.5));
      colors.push_back(Color(1,.5,.5));
      colors.push_back(Color(.5,1,.5));
      colors.push_back(Color(.5,.5,1));
      colors.push_back(Color(1,1,.5));
      colors.push_back(Color(1,.5,1));
      colors.push_back(Color(.5,1,1));
      
      colors.push_back(Color(1,.5,0));
      colors.push_back(Color(.5,1,0));
      colors.push_back(Color(1,0,.5));
      colors.push_back(Color(0,1,.5));
      colors.push_back(Color(0,.5,1));
      colors.push_back(Color(.5,0,1));
    } while(int(colors.size())<num);
    //    colors.push_back(Color(1,1,1));
    if(num>0) colors.resize(num);
  }
  ///\e
  Color &operator[](int i)
  {
    return colors[i%colors.size()];
  }
  ///\e
  const Color &operator[](int i) const
  {
    return colors[i%colors.size()];
  }
  ///\e
  void set(int i,const Color &c)
  {
    colors[i%colors.size()]=c;
  }
  ///Sets the number of the exiting colors.
  void resize(int s) { colors.resize(s);}
  ///Returns the munber of the existing colors.
  std::size_t size() { return colors.size();}
};

///Returns a visible distinct \ref Color

///Returns a \ref Color which is as different from the given parameter
///as it is possible.
inline Color distantColor(const Color &c) 
{
  return Color(c.getR()<.5?1:0,c.getG()<.5?1:0,c.getB()<.5?1:0);
}
///Returns black for light colors and white for the dark ones.

///Returns black for light colors and white for the dark ones.
///\todo weighted average would be better
inline Color distantBW(const Color &c){
  //  double v=(c.getR()+c.getG()+c.getB())<1.5?1:0;
  double v=(.2125*c.getR()+.7154*c.getG()+.0721*c.getB())<.5?1:0;
  return Color(v,v,v);
}

///Default traits class of \ref GraphToEps

///Default traits class of \ref GraphToEps
///
///\c G is the type of the underlying graph.
template<class G>
struct DefaultGraphToEpsTraits
{
  typedef G Graph;
  typedef typename Graph::Node Node;
  typedef typename Graph::NodeIt NodeIt;
  typedef typename Graph::Edge Edge;
  typedef typename Graph::EdgeIt EdgeIt;
  typedef typename Graph::InEdgeIt InEdgeIt;
  typedef typename Graph::OutEdgeIt OutEdgeIt;
  

  const Graph &g;

  std::ostream& os;
  
  ConstMap<typename Graph::Node,xy<double> > _coords;
  ConstMap<typename Graph::Node,double > _nodeSizes;
  ConstMap<typename Graph::Node,int > _nodeShapes;

  ConstMap<typename Graph::Node,Color > _nodeColors;
  ConstMap<typename Graph::Edge,Color > _edgeColors;

  ConstMap<typename Graph::Edge,double > _edgeWidths;

  static const double A4HEIGHT = 841.8897637795276;
  static const double A4WIDTH  = 595.275590551181;
  static const double A4BORDER = 15;

  
  double _edgeWidthScale;
  
  double _nodeScale;
  double _xBorder, _yBorder;
  double _scale;
  double _nodeBorderQuotient;
  
  bool _drawArrows;
  double _arrowLength, _arrowWidth;
  
  bool _showNodes, _showEdges;

  bool _enableParallel;
  double _parEdgeDist;

  bool _showNodeText;
  ConstMap<typename Graph::Node,bool > _nodeTexts;  
  double _nodeTextSize;

  bool _showNodePsText;
  ConstMap<typename Graph::Node,bool > _nodePsTexts;  
  char *_nodePsTextsPreamble;
  
  bool _undir;
  bool _pleaseRemoveOsStream;

  bool _scaleToA4;

  std::string _title;
  std::string _copyright;

  enum NodeTextColorType 
    { DIST_COL=0, DIST_BW=1, CUST_COL=2, SAME_COL=3 } _nodeTextColorType;
  ConstMap<typename Graph::Node,Color > _nodeTextColors;

  ///Constructor

  ///Constructor
  ///\param _g is a reference to the graph to be printed
  ///\param _os is a reference to the output stream.
  ///\param _os is a reference to the output stream.
  ///\param _pros If it is \c true, then the \c ostream referenced by \c _os
  ///will be explicitly deallocated by the destructor.
  ///By default it is <tt>std::cout</tt>
  DefaultGraphToEpsTraits(const G &_g,std::ostream& _os=std::cout,
			  bool _pros=false) :
    g(_g), os(_os),
    _coords(xy<double>(1,1)), _nodeSizes(1.0), _nodeShapes(0),
    _nodeColors(Color(1,1,1)), _edgeColors(Color(0,0,0)),
    _edgeWidths(1), _edgeWidthScale(0.3),
    _nodeScale(1.0), _xBorder(10), _yBorder(10), _scale(1.0),
    _nodeBorderQuotient(.1),
    _drawArrows(false), _arrowLength(1), _arrowWidth(0.3),
    _showNodes(true), _showEdges(true),
    _enableParallel(false), _parEdgeDist(1),
    _showNodeText(false), _nodeTexts(false), _nodeTextSize(1),
    _showNodePsText(false), _nodePsTexts(false), _nodePsTextsPreamble(0),
    _undir(false),
    _pleaseRemoveOsStream(_pros), _scaleToA4(false),
    _nodeTextColorType(SAME_COL), _nodeTextColors(Color(0,0,0))
  {}
};

///Helper class to implement the named parameters of \ref graphToEps()

///Helper class to implement the named parameters of \ref graphToEps()
///\todo Is 'helper class' a good name for this?
///
///\todo Follow PostScript's DSC.
/// Use own dictionary.
///\todo Useful new features.
/// - Linestyles: dotted, dashed etc.
/// - A second color and percent value for the lines.
template<class T> class GraphToEps : public T 
{
  typedef typename T::Graph Graph;
  typedef typename Graph::Node Node;
  typedef typename Graph::NodeIt NodeIt;
  typedef typename Graph::Edge Edge;
  typedef typename Graph::EdgeIt EdgeIt;
  typedef typename Graph::InEdgeIt InEdgeIt;
  typedef typename Graph::OutEdgeIt OutEdgeIt;

  static const int INTERPOL_PREC=20;

  bool dontPrint;

public:
  ///Node shapes

  ///Node shapes
  ///
  enum NodeShapes { 
    /// = 0
    ///\image html nodeshape_0.png
    ///\image latex nodeshape_0.eps "CIRCLE shape (0)" width=2cm
    CIRCLE=0, 
    /// = 1
    ///\image html nodeshape_1.png
    ///\image latex nodeshape_1.eps "SQUARE shape (1)" width=2cm
    ///
    SQUARE=1, 
    /// = 2
    ///\image html nodeshape_2.png
    ///\image latex nodeshape_2.eps "DIAMOND shape (2)" width=2cm
    ///
    DIAMOND=2
  };

private:
  class edgeLess {
    const Graph &g;
  public:
    edgeLess(const Graph &_g) : g(_g) {}
    bool operator()(Edge a,Edge b) const 
    {
      Node ai=min(g.source(a),g.target(a));
      Node aa=max(g.source(a),g.target(a));
      Node bi=min(g.source(b),g.target(b));
      Node ba=max(g.source(b),g.target(b));
      return ai<bi ||
	(ai==bi && (aa < ba || 
		    (aa==ba && ai==g.source(a) && bi==g.target(b))));
    }
  };
  bool isParallel(Edge e,Edge f) const
  {
    return (g.source(e)==g.source(f)&&g.target(e)==g.target(f))||
      (g.source(e)==g.target(f)&&g.target(e)==g.source(f));
  }
  static xy<double> rot(xy<double> v) 
  {
    return xy<double>(v.y,-v.x);
  }
  template<class TT>
  static std::string psOut(const xy<TT> &p) 
    {
      std::ostringstream os;	
      os << p.x << ' ' << p.y;
      return os.str();
    }
  static std::string psOut(const Color &c) 
    {
      std::ostringstream os;	
      os << c.getR() << ' ' << c.getG() << ' ' << c.getB();
      return os.str();
    }
  
public:
  GraphToEps(const T &t) : T(t), dontPrint(false) {};
  
  template<class X> struct CoordsTraits : public T {
    const X &_coords;
    CoordsTraits(const T &t,const X &x) : T(t), _coords(x) {}
  };
  ///Sets the map of the node coordinates

  ///Sets the map of the node coordinates.
  ///\param x must be a node map with xy<double> or \ref xy "xy<int>" values. 
  template<class X> GraphToEps<CoordsTraits<X> > coords(const X &x) {
    dontPrint=true;
    return GraphToEps<CoordsTraits<X> >(CoordsTraits<X>(*this,x));
  }
  template<class X> struct NodeSizesTraits : public T {
    const X &_nodeSizes;
    NodeSizesTraits(const T &t,const X &x) : T(t), _nodeSizes(x) {}
  };
  ///Sets the map of the node sizes

  ///Sets the map of the node sizes
  ///\param x must be a node map with \c double (or convertible) values. 
  template<class X> GraphToEps<NodeSizesTraits<X> > nodeSizes(const X &x)
  {
    dontPrint=true;
    return GraphToEps<NodeSizesTraits<X> >(NodeSizesTraits<X>(*this,x));
  }
  template<class X> struct NodeShapesTraits : public T {
    const X &_nodeShapes;
    NodeShapesTraits(const T &t,const X &x) : T(t), _nodeShapes(x) {}
  };
  ///Sets the map of the node shapes

  ///Sets the map of the node shapes.
  ///The availabe shape values
  ///can be found in \ref NodeShapes "enum NodeShapes".
  ///\param x must be a node map with \c int (or convertible) values. 
  ///\sa NodeShapes
  template<class X> GraphToEps<NodeShapesTraits<X> > nodeShapes(const X &x)
  {
    dontPrint=true;
    return GraphToEps<NodeShapesTraits<X> >(NodeShapesTraits<X>(*this,x));
  }
  template<class X> struct NodeTextsTraits : public T {
    const X &_nodeTexts;
    NodeTextsTraits(const T &t,const X &x) : T(t), _nodeTexts(x) {}
  };
  ///Sets the text printed on the nodes

  ///Sets the text printed on the nodes
  ///\param x must be a node map with type that can be pushed to a standard
  ///ostream. 
  template<class X> GraphToEps<NodeTextsTraits<X> > nodeTexts(const X &x)
  {
    dontPrint=true;
    _showNodeText=true;
    return GraphToEps<NodeTextsTraits<X> >(NodeTextsTraits<X>(*this,x));
  }
  template<class X> struct NodePsTextsTraits : public T {
    const X &_nodePsTexts;
    NodePsTextsTraits(const T &t,const X &x) : T(t), _nodePsTexts(x) {}
  };
  ///Inserts a PostScript block to the nodes

  ///With this command it is possible to insert a verbatim PostScript
  ///block to the nodes.
  ///The PS current point will be moved to the centre of the node before
  ///the PostScript block inserted.
  ///
  ///Before and after the block a newline character is inserted to you
  ///don't have to bother with the separators.
  ///
  ///\param x must be a node map with type that can be pushed to a standard
  ///ostream.
  ///
  ///\sa nodePsTextsPreamble()
  ///\todo Offer the choise not to move to the centre but pass the coordinates
  ///to the Postscript block inserted.
  template<class X> GraphToEps<NodePsTextsTraits<X> > nodePsTexts(const X &x)
  {
    dontPrint=true;
    _showNodePsText=true;
    return GraphToEps<NodePsTextsTraits<X> >(NodePsTextsTraits<X>(*this,x));
  }
  template<class X> struct EdgeWidthsTraits : public T {
    const X &_edgeWidths;
    EdgeWidthsTraits(const T &t,const X &x) : T(t), _edgeWidths(x) {}
  };
  ///Sets the map of the edge widths

  ///Sets the map of the edge widths
  ///\param x must be a edge map with \c double (or convertible) values. 
  template<class X> GraphToEps<EdgeWidthsTraits<X> > edgeWidths(const X &x)
  {
    dontPrint=true;
    return GraphToEps<EdgeWidthsTraits<X> >(EdgeWidthsTraits<X>(*this,x));
  }

  template<class X> struct NodeColorsTraits : public T {
    const X &_nodeColors;
    NodeColorsTraits(const T &t,const X &x) : T(t), _nodeColors(x) {}
  };
  ///Sets the map of the node colors

  ///Sets the map of the node colors
  ///\param x must be a node map with \ref Color values. 
  template<class X> GraphToEps<NodeColorsTraits<X> >
  nodeColors(const X &x)
  {
    dontPrint=true;
    return GraphToEps<NodeColorsTraits<X> >(NodeColorsTraits<X>(*this,x));
  }
  template<class X> struct NodeTextColorsTraits : public T {
    const X &_nodeTextColors;
    NodeTextColorsTraits(const T &t,const X &x) : T(t), _nodeTextColors(x) {}
  };
  ///Sets the map of the node text colors

  ///Sets the map of the node text colors
  ///\param x must be a node map with \ref Color values. 
  template<class X> GraphToEps<NodeTextColorsTraits<X> >
  nodeTextColors(const X &x)
  {
    dontPrint=true;
    _nodeTextColorType=CUST_COL;
    return GraphToEps<NodeTextColorsTraits<X> >
      (NodeTextColorsTraits<X>(*this,x));
  }
  template<class X> struct EdgeColorsTraits : public T {
    const X &_edgeColors;
    EdgeColorsTraits(const T &t,const X &x) : T(t), _edgeColors(x) {}
  };
  ///Sets the map of the edge colors

  ///Sets the map of the edge colors
  ///\param x must be a edge map with \ref Color values. 
  template<class X> GraphToEps<EdgeColorsTraits<X> >
  edgeColors(const X &x)
  {
    dontPrint=true;
    return GraphToEps<EdgeColorsTraits<X> >(EdgeColorsTraits<X>(*this,x));
  }
  ///Sets a global scale factor for node sizes

  ///Sets a global scale factor for node sizes
  ///
  GraphToEps<T> &nodeScale(double d) {_nodeScale=d;return *this;}
  ///Sets a global scale factor for edge widths

  ///Sets a global scale factor for edge widths
  ///
  GraphToEps<T> &edgeWidthScale(double d) {_edgeWidthScale=d;return *this;}
  ///Sets a global scale factor for the whole picture

  ///Sets a global scale factor for the whole picture
  ///
  GraphToEps<T> &scale(double d) {_scale=d;return *this;}
  ///Sets the width of the border around the picture

  ///Sets the width of the border around the picture
  ///
  GraphToEps<T> &border(double b) {_xBorder=_yBorder=b;return *this;}
  ///Sets the width of the border around the picture

  ///Sets the width of the border around the picture
  ///
  GraphToEps<T> &border(double x, double y) {
    _xBorder=x;_yBorder=y;return *this;
  }
  ///Sets whether to draw arrows

  ///Sets whether to draw arrows
  ///
  GraphToEps<T> &drawArrows(bool b=true) {_drawArrows=b;return *this;}
  ///Sets the length of the arrowheads

  ///Sets the length of the arrowheads
  ///
  GraphToEps<T> &arrowLength(double d) {_arrowLength*=d;return *this;}
  ///Sets the width of the arrowheads

  ///Sets the width of the arrowheads
  ///
  GraphToEps<T> &arrowWidth(double d) {_arrowWidth*=d;return *this;}
  
  ///Scales the drawing to fit to A4 page

  ///Scales the drawing to fit to A4 page
  ///
  GraphToEps<T> &scaleToA4() {_scaleToA4=true;return *this;}
  
  ///Enables parallel edges

  ///Enables parallel edges
  ///\todo Partially implemented
  GraphToEps<T> &enableParallel(bool b=true) {_enableParallel=b;return *this;}
  
  ///Sets the distance 
  
  ///Sets the distance 
  ///
  GraphToEps<T> &parEdgeDist(double d) {_parEdgeDist*=d;return *this;}
  
  ///Hides the edges
  
  ///Hides the edges
  ///
  GraphToEps<T> &hideEdges(bool b=true) {_showEdges=!b;return *this;}
  ///Hides the nodes
  
  ///Hides the nodes
  ///
  GraphToEps<T> &hideNodes(bool b=true) {_showNodes=!b;return *this;}
  
  ///Sets the size of the node texts
  
  ///Sets the size of the node texts
  ///
  GraphToEps<T> &nodeTextSize(double d) {_nodeTextSize=d;return *this;}

  ///Sets the color of the node texts to be different from the node color

  ///Sets the color of the node texts to be as different from the node color
  ///as it is possible
    ///
  GraphToEps<T> &distantColorNodeTexts()
  {_nodeTextColorType=DIST_COL;return *this;}
  ///Sets the color of the node texts to be black or white and always visible.

  ///Sets the color of the node texts to be black or white according to
  ///which is more 
  ///different from the node color
  ///
  GraphToEps<T> &distantBWNodeTexts()
  {_nodeTextColorType=DIST_BW;return *this;}

  ///Gives a preamble block for node Postscript block.
  
  ///Gives a preamble block for node Postscript block.
  ///
  ///\sa nodePsTexts()
  GraphToEps<T> & nodePsTextsPreamble(const char *str) {
    _nodePsTextsPreamble=s ;return *this;
  }
  ///Sets whether the the graph is undirected

  ///Sets whether the the graph is undirected
  ///
  GraphToEps<T> &undir(bool b=true) {_undir=b;return *this;}
  ///Sets whether the the graph is directed

  ///Sets whether the the graph is directed.
  ///Use it to show the undirected edges as a pair of directed ones.
  GraphToEps<T> &bidir(bool b=true) {_undir=!b;return *this;}

  ///Sets the title.

  ///Sets the title of the generated image,
  ///namely it inserts a <tt>%%Title:</tt> DSC field to the header of
  ///the EPS file.
  GraphToEps<T> &title(const std::string &t) {_title=t;return *this;}
  ///Sets the copyright statement.

  ///Sets the copyright statement of the generated image,
  ///namely it inserts a <tt>%%Copyright:</tt> DSC field to the header of
  ///the EPS file.
  ///\todo Multiline copyright notice could be supported.
  GraphToEps<T> &copyright(const std::string &t) {_copyright=t;return *this;}

protected:
  bool isInsideNode(xy<double> p, double r,int t) 
  {
    switch(t) {
    case CIRCLE:
      return p.normSquare()<=r*r;
    case SQUARE:
      return p.x<=r&&p.x>=-r&&p.y<=r&&p.y>=-r;
    case DIAMOND:
      return p.x+p.y<=r && p.x-p.y<=r && -p.x+p.y<=r && -p.x-p.y<=r;
    }
    return false;
  }

public:
  ~GraphToEps() { }
  
  ///Draws the graph.

  ///Like other functions using
  ///\ref named-templ-func-param "named template parameters",
  ///this function calles the algorithm itself, i.e. in this case
  ///it draws the graph.
  void run() {
    if(dontPrint) return;
    
    os << "%!PS-Adobe-2.0 EPSF-2.0\n";
    if(_title.size()>0) os << "%%Title: " << _title << '\n';
     if(_copyright.size()>0) os << "%%Copyright: " << _copyright << '\n';
//        << "%%Copyright: XXXX\n"
    os << "%%Creator: LEMON GraphToEps function\n";
    
    {
      char cbuf[50];
      timeval tv;
      gettimeofday(&tv, 0);
      ctime_r(&tv.tv_sec,cbuf);
      os << "%%CreationDate: " << cbuf;
    }
    ///\todo: Chech whether the graph is empty.
    BoundingBox<double> bb;
    for(NodeIt n(g);n!=INVALID;++n) {
      double ns=_nodeSizes[n]*_nodeScale;
      xy<double> p(ns,ns);
      bb+=p+_coords[n];
      bb+=-p+_coords[n];
      }
    if(_scaleToA4)
      os <<"%%BoundingBox: 0 0 596 842\n%%DocumentPaperSizes: a4\n";
    else os << "%%BoundingBox: "
	    << bb.left()*  _scale-_xBorder << ' '
	    << bb.bottom()*_scale-_yBorder << ' '
	    << bb.right()* _scale+_xBorder << ' '
	    << bb.top()*   _scale+_yBorder << '\n';
    
    os << "%%EndComments\n";
    
    //x1 y1 x2 y2 x3 y3 cr cg cb w
    os << "/lb { setlinewidth setrgbcolor newpath moveto\n"
       << "      4 2 roll 1 index 1 index curveto stroke } bind def\n";
    os << "/l { setlinewidth setrgbcolor newpath moveto lineto stroke } bind def\n";
    //x y r
    os << "/c { newpath dup 3 index add 2 index moveto 0 360 arc closepath } bind def\n";
    //x y r
    os << "/sq { newpath 2 index 1 index add 2 index 2 index add moveto\n"
       << "      2 index 1 index sub 2 index 2 index add lineto\n"
       << "      2 index 1 index sub 2 index 2 index sub lineto\n"
       << "      2 index 1 index add 2 index 2 index sub lineto\n"
       << "      closepath pop pop pop} bind def\n";
    //x y r
    os << "/di { newpath 2 index 1 index add 2 index moveto\n"
       << "      2 index             2 index 2 index add lineto\n"
       << "      2 index 1 index sub 2 index             lineto\n"
       << "      2 index             2 index 2 index sub lineto\n"
       << "      closepath pop pop pop} bind def\n";
    // x y r cr cg cb
    os << "/nc { 0 0 0 setrgbcolor 5 index 5 index 5 index c fill\n"
       << "     setrgbcolor " << 1+_nodeBorderQuotient << " div c fill\n"
       << "   } bind def\n";
    os << "/nsq { 0 0 0 setrgbcolor 5 index 5 index 5 index sq fill\n"
       << "     setrgbcolor " << 1+_nodeBorderQuotient << " div sq fill\n"
       << "   } bind def\n";
    os << "/ndi { 0 0 0 setrgbcolor 5 index 5 index 5 index di fill\n"
       << "     setrgbcolor " << 1+_nodeBorderQuotient << " div di fill\n"
       << "   } bind def\n";
    os << "/arrl " << _arrowLength << " def\n";
    os << "/arrw " << _arrowWidth << " def\n";
    // l dx_norm dy_norm
    os << "/lrl { 2 index mul exch 2 index mul exch rlineto pop} bind def\n";
    //len w dx_norm dy_norm x1 y1 cr cg cb
    os << "/arr { setrgbcolor /y1 exch def /x1 exch def /dy exch def /dx exch def\n"
       << "       /w exch def /len exch def\n"
      //	 << "       0.1 setlinewidth x1 y1 moveto dx len mul dy len mul rlineto stroke"
       << "       newpath x1 dy w 2 div mul add y1 dx w 2 div mul sub moveto\n"
       << "       len w sub arrl sub dx dy lrl\n"
       << "       arrw dy dx neg lrl\n"
       << "       dx arrl w add mul dy w 2 div arrw add mul sub\n"
       << "       dy arrl w add mul dx w 2 div arrw add mul add rlineto\n"
       << "       dx arrl w add mul neg dy w 2 div arrw add mul sub\n"
       << "       dy arrl w add mul neg dx w 2 div arrw add mul add rlineto\n"
       << "       arrw dy dx neg lrl\n"
       << "       len w sub arrl sub neg dx dy lrl\n"
       << "       closepath fill } bind def\n";
    os << "/cshow { 2 index 2 index moveto dup stringwidth pop\n"
       << "         neg 2 div fosi .35 mul neg rmoveto show pop pop} def\n";

    os << "\ngsave\n";
    if(_scaleToA4)
      if(bb.height()>bb.width()) {
	double sc= min((A4HEIGHT-2*A4BORDER)/bb.height(),
		  (A4WIDTH-2*A4BORDER)/bb.width());
	os << ((A4WIDTH -2*A4BORDER)-sc*bb.width())/2 + A4BORDER << ' '
	   << ((A4HEIGHT-2*A4BORDER)-sc*bb.height())/2 + A4BORDER << " translate\n"
	   << sc << " dup scale\n"
	   << -bb.left() << ' ' << -bb.bottom() << " translate\n";
      }
      else {
	//\todo Verify centering
	double sc= min((A4HEIGHT-2*A4BORDER)/bb.width(),
		  (A4WIDTH-2*A4BORDER)/bb.height());
	os << ((A4WIDTH -2*A4BORDER)-sc*bb.height())/2 + A4BORDER << ' '
	   << ((A4HEIGHT-2*A4BORDER)-sc*bb.width())/2 + A4BORDER  << " translate\n"
	   << sc << " dup scale\n90 rotate\n"
	   << -bb.left() << ' ' << -bb.top() << " translate\n";	
	}
    else if(_scale!=1.0) os << _scale << " dup scale\n";
    
    if(_showEdges) {
      os << "%Edges:\ngsave\n";      
      if(_enableParallel) {
	std::vector<Edge> el;
	for(EdgeIt e(g);e!=INVALID;++e)
	  if((!_undir||g.source(e)<g.target(e))&&_edgeWidths[e]>0)
	    el.push_back(e);
	sort(el.begin(),el.end(),edgeLess(g));
	
	typename std::vector<Edge>::iterator j;
	for(typename std::vector<Edge>::iterator i=el.begin();i!=el.end();i=j) {
	  for(j=i+1;j!=el.end()&&isParallel(*i,*j);++j) ;

	  double sw=0;
	  for(typename std::vector<Edge>::iterator e=i;e!=j;++e)
	    sw+=_edgeWidths[*e]*_edgeWidthScale+_parEdgeDist;
	  sw-=_parEdgeDist;
	  sw/=-2.0;
	  xy<double> dvec(_coords[g.target(*i)]-_coords[g.source(*i)]);
	  double l=sqrt(dvec.normSquare());
	  xy<double> d(dvec/l);
 	  xy<double> m;
// 	  m=xy<double>(_coords[g.target(*i)]+_coords[g.source(*i)])/2.0;

//  	  m=xy<double>(_coords[g.source(*i)])+
// 	    dvec*(double(_nodeSizes[g.source(*i)])/
// 	       (_nodeSizes[g.source(*i)]+_nodeSizes[g.target(*i)]));

 	  m=xy<double>(_coords[g.source(*i)])+
	    d*(l+_nodeSizes[g.source(*i)]-_nodeSizes[g.target(*i)])/2.0;

	  for(typename std::vector<Edge>::iterator e=i;e!=j;++e) {
	    sw+=_edgeWidths[*e]*_edgeWidthScale/2.0;
	    xy<double> mm=m+rot(d)*sw/.75;
	    if(_drawArrows) {
	      int node_shape;
	      xy<double> s=_coords[g.source(*e)];
	      xy<double> t=_coords[g.target(*e)];
	      double rn=_nodeSizes[g.target(*e)]*_nodeScale;
	      node_shape=_nodeShapes[g.target(*e)];
	      Bezier3 bez(s,mm,mm,t);
	      double t1=0,t2=1;
	      for(int i=0;i<INTERPOL_PREC;++i)
		if(isInsideNode(bez((t1+t2)/2)-t,rn,node_shape)) t2=(t1+t2)/2;
		else t1=(t1+t2)/2;
	      xy<double> apoint=bez((t1+t2)/2);
	      rn = _arrowLength+_edgeWidths[*e]*_edgeWidthScale;
	      rn*=rn;
	      t2=(t1+t2)/2;t1=0;
	      for(int i=0;i<INTERPOL_PREC;++i)
		if((bez((t1+t2)/2)-apoint).normSquare()>rn) t1=(t1+t2)/2;
		else t2=(t1+t2)/2;
	      xy<double> linend=bez((t1+t2)/2);	      
	      bez=bez.before((t1+t2)/2);
// 	      rn=_nodeSizes[g.source(*e)]*_nodeScale;
// 	      node_shape=_nodeShapes[g.source(*e)];
// 	      t1=0;t2=1;
// 	      for(int i=0;i<INTERPOL_PREC;++i)
// 		if(isInsideNode(bez((t1+t2)/2)-t,rn,node_shape)) t1=(t1+t2)/2;
// 		else t2=(t1+t2)/2;
// 	      bez=bez.after((t1+t2)/2);
	      os << _edgeWidths[*e]*_edgeWidthScale << " setlinewidth "
		 << _edgeColors[*e].getR() << ' '
		 << _edgeColors[*e].getG() << ' '
		 << _edgeColors[*e].getB() << " setrgbcolor newpath\n"
		 << bez.p1.x << ' ' <<  bez.p1.y << " moveto\n"
		 << bez.p2.x << ' ' << bez.p2.y << ' '
		 << bez.p3.x << ' ' << bez.p3.y << ' '
		 << bez.p4.x << ' ' << bez.p4.y << " curveto stroke\n";
	      xy<double> dd(rot(linend-apoint));
	      dd*=(.5*_edgeWidths[*e]*_edgeWidthScale+_arrowWidth)/
		sqrt(dd.normSquare());
	      os << "newpath " << psOut(apoint) << " moveto "
		 << psOut(linend+dd) << " lineto "
		 << psOut(linend-dd) << " lineto closepath fill\n";
	    }
	    else {
	      os << _coords[g.source(*e)].x << ' '
		 << _coords[g.source(*e)].y << ' '
		 << mm.x << ' ' << mm.y << ' '
		 << _coords[g.target(*e)].x << ' '
		 << _coords[g.target(*e)].y << ' '
		 << _edgeColors[*e].getR() << ' '
		 << _edgeColors[*e].getG() << ' '
		 << _edgeColors[*e].getB() << ' '
		 << _edgeWidths[*e]*_edgeWidthScale << " lb\n";
	    }
	    sw+=_edgeWidths[*e]*_edgeWidthScale/2.0+_parEdgeDist;
	  }
	}
      }
      else for(EdgeIt e(g);e!=INVALID;++e)
	if((!_undir||g.source(e)<g.target(e))&&_edgeWidths[e]>0)
	  if(_drawArrows) {
	    xy<double> d(_coords[g.target(e)]-_coords[g.source(e)]);
	    double rn=_nodeSizes[g.target(e)]*_nodeScale;
	    int node_shape=_nodeShapes[g.target(e)];
	    double t1=0,t2=1;
	    for(int i=0;i<INTERPOL_PREC;++i)
	      if(isInsideNode((-(t1+t2)/2)*d,rn,node_shape)) t1=(t1+t2)/2;
	      else t2=(t1+t2)/2;
	    double l=sqrt(d.normSquare());
	    d/=l;
	    
	    os << l*(1-(t1+t2)/2) << ' '
	       << _edgeWidths[e]*_edgeWidthScale << ' '
	       << d.x << ' ' << d.y << ' '
	       << _coords[g.source(e)].x << ' '
	       << _coords[g.source(e)].y << ' '
	       << _edgeColors[e].getR() << ' '
	       << _edgeColors[e].getG() << ' '
	       << _edgeColors[e].getB() << " arr\n";
	  }
	  else os << _coords[g.source(e)].x << ' '
		  << _coords[g.source(e)].y << ' '
		  << _coords[g.target(e)].x << ' '
		  << _coords[g.target(e)].y << ' '
		  << _edgeColors[e].getR() << ' '
		  << _edgeColors[e].getG() << ' '
		  << _edgeColors[e].getB() << ' '
		  << _edgeWidths[e]*_edgeWidthScale << " l\n";
      os << "grestore\n";
    }
    if(_showNodes) {
      os << "%Nodes:\ngsave\n";
      for(NodeIt n(g);n!=INVALID;++n) {
	os << _coords[n].x << ' ' << _coords[n].y << ' '
	   << _nodeSizes[n]*_nodeScale << ' '
	   << _nodeColors[n].getR() << ' '
	   << _nodeColors[n].getG() << ' '
	   << _nodeColors[n].getB() << ' ';
	switch(_nodeShapes[n]) {
	case CIRCLE:
	  os<< "nc";break;
	case SQUARE:
	  os<< "nsq";break;
	case DIAMOND:
	  os<< "ndi";break;
	}
	os<<'\n';
      }
      os << "grestore\n";
    }
    if(_showNodeText) {
      os << "%Node texts:\ngsave\n";
      os << "/fosi " << _nodeTextSize << " def\n";
      os << "(Helvetica) findfont fosi scalefont setfont\n";
      for(NodeIt n(g);n!=INVALID;++n) {
	switch(_nodeTextColorType) {
	case DIST_COL:
	  os << psOut(distantColor(_nodeColors[n])) << " setrgbcolor\n";
	  break;
	case DIST_BW:
	  os << psOut(distantBW(_nodeColors[n])) << " setrgbcolor\n";
	  break;
	case CUST_COL:
	  os << psOut(distantColor(_nodeTextColors[n])) << " setrgbcolor\n";
	  break;
	default:
	  os << "0 0 0 setrgbcolor\n";
	}
	os << _coords[n].x << ' ' << _coords[n].y
	   << " (" << _nodeTexts[n] << ") cshow\n";
      }
      os << "grestore\n";
    }
    if(_showNodePsText) {
      os << "%Node PS blocks:\ngsave\n";
      for(NodeIt n(g);n!=INVALID;++n)
	os << _coords[n].x << ' ' << _coords[n].y
	   << " moveto\n" << _nodePsTexts[n] << "\n";
      os << "grestore\n";
    }
    
    os << "grestore\nshowpage\n";

    //CleanUp:
    if(_pleaseRemoveOsStream) {delete &os;}
  } 
};


///Generates an EPS file from a graph

///\ingroup misc
///Generates an EPS file from a graph.
///\param g is a reference to the graph to be printed
///\param os is a reference to the output stream.
///By default it is <tt>std::cout</tt>
///
///This function also has a lot of
///\ref named-templ-func-param "named parameters",
///they are declared as the members of class \ref GraphToEps. The following
///example shows how to use these parameters.
///\code
/// graphToEps(g,os).scale(10).coords(coords)
///              .nodeScale(2).nodeSizes(sizes)
///              .edgeWidthScale(.4).run();
///\endcode
///\warning Don't forget to put the \ref GraphToEps::run() "run()"
///to the end of the parameter list.
///\sa GraphToEps
///\sa graphToEps(G &g, char *file_name)
template<class G>
GraphToEps<DefaultGraphToEpsTraits<G> > 
graphToEps(G &g, std::ostream& os=std::cout)
{
  return 
    GraphToEps<DefaultGraphToEpsTraits<G> >(DefaultGraphToEpsTraits<G>(g,os));
}
 
///Generates an EPS file from a graph

///\ingroup misc
///This function does the same as
///\ref graphToEps(G &g,std::ostream& os)
///but it writes its output into the file \c file_name
///instead of a stream.
///\sa graphToEps(G &g, std::ostream& os)
template<class G>
GraphToEps<DefaultGraphToEpsTraits<G> > 
graphToEps(G &g,const char *file_name)
{
  return GraphToEps<DefaultGraphToEpsTraits<G> >
    (DefaultGraphToEpsTraits<G>(g,*new std::ofstream(file_name),true));
}

} //END OF NAMESPACE LEMON

#endif // LEMON_GRAPH_TO_EPS_H
