// -*- mode:C++ -*-

#ifndef HUGO_LIST_GRAPH_H
#define HUGO_LIST_GRAPH_H

///\ingroup graphs
///\file
///\brief ListGraph, SymListGraph, NodeSet and EdgeSet classes.

#include <vector>
#include <climits>

#include <hugo/invalid.h>

#include <hugo/map_registry.h>
#include <hugo/default_map_factory.h>

#include <hugo/sym_map_factory.h>

#include <hugo/map_defines.h>


namespace hugo {

/// \addtogroup graphs
/// @{

//  class SymListGraph;

  ///A list graph class.

  ///This is a simple and fast erasable graph implementation.
  ///
  ///It conforms to the graph interface documented under
  ///the description of \ref GraphSkeleton.
  ///\sa \ref GraphSkeleton.
  class ListGraph {

    //Nodes are double linked.
    //The free nodes are only single linked using the "next" field.
    struct NodeT 
    {
      int first_in,first_out;
      int prev, next;
      //      NodeT() {}
    };
    //Edges are double linked.
    //The free edges are only single linked using the "next_in" field.
    struct EdgeT 
    {
      int head, tail;
      int prev_in, prev_out;
      int next_in, next_out;
      //FIXME: is this necessary?
      //      EdgeT() : next_in(-1), next_out(-1) prev_in(-1), prev_out(-1) {}  
    };

    std::vector<NodeT> nodes;
    //The first node
    int first_node;
    //The first free node
    int first_free_node;
    std::vector<EdgeT> edges;
    //The first free edge
    int first_free_edge;
    
  public:
    
    typedef ListGraph Graph;
    
    class Node;
    class Edge;

    
  public:

    class NodeIt;
    class EdgeIt;
    class OutEdgeIt;
    class InEdgeIt;

    CREATE_MAP_REGISTRIES;
    CREATE_MAPS(DefaultMapFactory);

  public:

    ListGraph() 
      : nodes(), first_node(-1),
	first_free_node(-1), edges(), first_free_edge(-1) {}

    ListGraph(const ListGraph &_g) 
      : nodes(_g.nodes), first_node(_g.first_node),
	first_free_node(_g.first_free_node), edges(_g.edges),
	first_free_edge(_g.first_free_edge) {}
    
    int nodeNum() const { return nodes.size(); }  //FIXME: What is this?
    int edgeNum() const { return edges.size(); }  //FIXME: What is this?

    ///Set the expected number of edges

    ///With this function, it is possible to set the expected number of edges.
    ///The use of this fasten the building of the graph and makes
    ///it possible to avoid the superfluous memory allocation.
    void reserveEdge(int n) { edges.reserve(n); };
    
    ///\bug This function does something different than
    ///its name would suggests...
    int maxNodeId() const { return nodes.size(); }  //FIXME: What is this?
    ///\bug This function does something different than
    ///its name would suggests...
    int maxEdgeId() const { return edges.size(); }  //FIXME: What is this?

    Node tail(Edge e) const { return edges[e.n].tail; }
    Node head(Edge e) const { return edges[e.n].head; }

    NodeIt& first(NodeIt& v) const { 
      v=NodeIt(*this); return v; }
    EdgeIt& first(EdgeIt& e) const { 
      e=EdgeIt(*this); return e; }
    OutEdgeIt& first(OutEdgeIt& e, const Node v) const { 
      e=OutEdgeIt(*this,v); return e; }
    InEdgeIt& first(InEdgeIt& e, const Node v) const { 
      e=InEdgeIt(*this,v); return e; }

    static int id(Node v) { return v.n; }
    static int id(Edge e) { return e.n; }

    /// Adds a new node to the graph.

    /// \todo It adds the nodes in a reversed order.
    /// (i.e. the lastly added node becomes the first.)
    Node addNode() {
      int n;
      
      if(first_free_node==-1)
	{
	  n = nodes.size();
	  nodes.push_back(NodeT());
	}
      else {
	n = first_free_node;
	first_free_node = nodes[n].next;
      }
      
      nodes[n].next = first_node;
      if(first_node != -1) nodes[first_node].prev = n;
      first_node = n;
      nodes[n].prev = -1;
      
      nodes[n].first_in = nodes[n].first_out = -1;
      
      Node nn; nn.n=n;

      //Update dynamic maps
      node_maps.add(nn);

      return nn;
    }
    
    Edge addEdge(Node u, Node v) {
      int n;
      
      if(first_free_edge==-1)
	{
	  n = edges.size();
	  edges.push_back(EdgeT());
	}
      else {
	n = first_free_edge;
	first_free_edge = edges[n].next_in;
      }
      
      edges[n].tail = u.n; edges[n].head = v.n;

      edges[n].next_out = nodes[u.n].first_out;
      if(nodes[u.n].first_out != -1) edges[nodes[u.n].first_out].prev_out = n;
      edges[n].next_in = nodes[v.n].first_in;
      if(nodes[v.n].first_in != -1) edges[nodes[v.n].first_in].prev_in = n;
      edges[n].prev_in = edges[n].prev_out = -1;
	
      nodes[u.n].first_out = nodes[v.n].first_in = n;

      Edge e; e.n=n;

      //Update dynamic maps
      edge_maps.add(e);

      return e;
    }
    
    /// Finds an edge between two nodes.

    /// Finds an edge from node \c u to node \c v.
    ///
    /// If \c prev is \ref INVALID (this is the default value), then
    /// It finds the first edge from \c u to \c v. Otherwise it looks for
    /// the next edge from \c u to \c v after \c prev.
    /// \return The found edge or INVALID if there is no such an edge.
    Edge findEdge(Node u,Node v, Edge prev = INVALID) 
    {
      int e = (prev.n==-1)? nodes[u.n].first_out : edges[prev.n].next_out;
      while(e!=-1 && edges[e].tail!=v.n) e = edges[e].next_out;
      prev.n=e;
      return prev;
    }
    
  private:
    void eraseEdge(int n) {
      
      if(edges[n].next_in!=-1)
	edges[edges[n].next_in].prev_in = edges[n].prev_in;
      if(edges[n].prev_in!=-1)
	edges[edges[n].prev_in].next_in = edges[n].next_in;
      else nodes[edges[n].head].first_in = edges[n].next_in;
      
      if(edges[n].next_out!=-1)
	edges[edges[n].next_out].prev_out = edges[n].prev_out;
      if(edges[n].prev_out!=-1)
	edges[edges[n].prev_out].next_out = edges[n].next_out;
      else nodes[edges[n].tail].first_out = edges[n].next_out;
      
      edges[n].next_in = first_free_edge;
      first_free_edge = n;      

      //Update dynamic maps
      Edge e; e.n=n;
      edge_maps.erase(e);

    }
      
  public:

    void erase(Node nn) {
      int n=nn.n;
      
      int m;
      while((m=nodes[n].first_in)!=-1) eraseEdge(m);
      while((m=nodes[n].first_out)!=-1) eraseEdge(m);

      if(nodes[n].next != -1) nodes[nodes[n].next].prev = nodes[n].prev;
      if(nodes[n].prev != -1) nodes[nodes[n].prev].next = nodes[n].next;
      else first_node = nodes[n].next;
      
      nodes[n].next = first_free_node;
      first_free_node = n;

      //Update dynamic maps
      node_maps.erase(nn);

    }
    
    void erase(Edge e) { eraseEdge(e.n); }

    void clear() {
      edge_maps.clear();
      edges.clear();
      node_maps.clear();
      nodes.clear();
      first_node=first_free_node=first_free_edge=-1;
    }

    class Node {
      friend class ListGraph;
      template <typename T> friend class NodeMap;
       
      friend class Edge;
      friend class OutEdgeIt;
      friend class InEdgeIt;
      friend class SymEdge;

    protected:
      int n;
      friend int ListGraph::id(Node v); 
      Node(int nn) {n=nn;}
    public:
      Node() {}
      Node (Invalid) { n=-1; }
      bool operator==(const Node i) const {return n==i.n;}
      bool operator!=(const Node i) const {return n!=i.n;}
      bool operator<(const Node i) const {return n<i.n;}
      //      ///Validity check
      //      operator bool() { return n!=-1; }
    };
    
    class NodeIt : public Node {
      const ListGraph *G;
      friend class ListGraph;
    public:
      NodeIt() : Node() { }
      NodeIt(Invalid i) : Node(i) { }
      NodeIt(const ListGraph& _G) : Node(_G.first_node), G(&_G) { }
      ///\todo Undocumented conversion Node -\> NodeIt.
      NodeIt(const ListGraph& _G,Node n) : Node(n), G(&_G) { }
      NodeIt &operator++() {
	n=G->nodes[n].next; 
	return *this; 
      }
      //      ///Validity check
      //      operator bool() { return Node::operator bool(); }      
    };

    class Edge {
      friend class ListGraph;
      template <typename T> friend class EdgeMap;

      //template <typename T> friend class SymListGraph::SymEdgeMap;      
      //friend Edge SymListGraph::opposite(Edge) const;
      
      friend class Node;
      friend class NodeIt;
    protected:
      int n;
      friend int ListGraph::id(Edge e);

    public:
      /// An Edge with id \c n.

      /// \bug It should be
      /// obtained by a member function of the Graph.
      Edge(int nn) {n=nn;}

      Edge() { }
      Edge (Invalid) { n=-1; }
      bool operator==(const Edge i) const {return n==i.n;}
      bool operator!=(const Edge i) const {return n!=i.n;}
      bool operator<(const Edge i) const {return n<i.n;}
      ///\bug This is a workaround until somebody tells me how to
      ///make class \c SymListGraph::SymEdgeMap friend of Edge
      int &idref() {return n;}
      const int &idref() const {return n;} 
      //      ///Validity check
      //      operator bool() { return n!=-1; }
   };
    
    class EdgeIt : public Edge {
      const ListGraph *G;
      friend class ListGraph;
    public:
      EdgeIt(const ListGraph& _G) : Edge(), G(&_G) {
      	int m;
	for(m=_G.first_node;
	    m!=-1 && _G.nodes[m].first_in == -1; m = _G.nodes[m].next);
	n = (m==-1)?-1:_G.nodes[m].first_in;
      }
      EdgeIt (Invalid i) : Edge(i) { }
      EdgeIt(const ListGraph& _G, Edge e) : Edge(e), G(&_G) { }
      EdgeIt() : Edge() { }
      ///\bug This is a workaround until somebody tells me how to
      ///make class \c SymListGraph::SymEdgeMap friend of Edge
      int &idref() {return n;}
      EdgeIt &operator++() {
	if(G->edges[n].next_in!=-1) n=G->edges[n].next_in;
	else {
	  int nn;
	  for(nn=G->nodes[G->edges[n].head].next;
	      nn!=-1 && G->nodes[nn].first_in == -1;
	      nn = G->nodes[nn].next) ;
	  n = (nn==-1)?-1:G->nodes[nn].first_in;
	}
	return *this;
      }
      //      ///Validity check
      //      operator bool() { return Edge::operator bool(); }      
    };
    
    class OutEdgeIt : public Edge {
      const ListGraph *G;
      friend class ListGraph;
    public: 
      OutEdgeIt() : Edge() { }
      OutEdgeIt(const ListGraph& _G, Edge e) : Edge(e), G(&_G) { }
      OutEdgeIt (Invalid i) : Edge(i) { }

      OutEdgeIt(const ListGraph& _G,const Node v)
	: Edge(_G.nodes[v.n].first_out), G(&_G) {}
      OutEdgeIt &operator++() { n=G->edges[n].next_out; return *this; }
      //      ///Validity check
      //      operator bool() { return Edge::operator bool(); }      
    };
    
    class InEdgeIt : public Edge {
      const ListGraph *G;
      friend class ListGraph;
    public: 
      InEdgeIt() : Edge() { }
      InEdgeIt(const ListGraph& _G, Edge e) : Edge(e), G(&_G) { }
      InEdgeIt (Invalid i) : Edge(i) { }
      InEdgeIt(const ListGraph& _G,Node v)
	: Edge(_G.nodes[v.n].first_in), G(&_G) { }
      InEdgeIt &operator++() { n=G->edges[n].next_in; return *this; }
      //      ///Validity check
      //      operator bool() { return Edge::operator bool(); }      
    };
  };

  ///Graph for bidirectional edges.

  ///The purpose of this graph structure is to handle graphs
  ///having bidirectional edges. Here the function \c addEdge(u,v) adds a pair
  ///of oppositely directed edges.
  ///There is a new edge map type called
  ///\ref SymListGraph::SymEdgeMap "SymEdgeMap"
  ///that complements this
  ///feature by
  ///storing shared values for the edge pairs. The usual
  ///\ref GraphSkeleton::EdgeMap "EdgeMap"
  ///can be used
  ///as well.
  ///
  ///The oppositely directed edge can also be obtained easily
  ///using \ref opposite.
  ///
  ///Here erase(Edge) deletes a pair of edges.
  ///
  ///\todo this date structure need some reconsiderations. Maybe it
  ///should be implemented independently from ListGraph.
  
  class SymListGraph : public ListGraph
  {
  public:

    typedef SymListGraph Graph;

    KEEP_NODE_MAP(ListGraph);
    KEEP_EDGE_MAP(ListGraph);

    CREATE_SYM_EDGE_MAP_REGISTRY;
    CREATE_SYM_EDGE_MAP_FACTORY(DefaultMapFactory);
    IMPORT_SYM_EDGE_MAP(SymEdgeMapFactory);

    SymListGraph() : ListGraph() { }
    SymListGraph(const ListGraph &_g) : ListGraph(_g) { }
    ///Adds a pair of oppositely directed edges to the graph.
    Edge addEdge(Node u, Node v)
    {
      Edge e = ListGraph::addEdge(u,v);
      Edge f = ListGraph::addEdge(v,u);
      sym_edge_maps.add(e);
      sym_edge_maps.add(f);
      
      return e;
    }

    void erase(Node n) { ListGraph::erase(n);}
    ///The oppositely directed edge.

    ///Returns the oppositely directed
    ///pair of the edge \c e.
    static Edge opposite(Edge e)
    {
      Edge f;
      f.idref() = e.idref() - 2*(e.idref()%2) + 1;
      return f;
    }
    
    ///Removes a pair of oppositely directed edges to the graph.
    void erase(Edge e) {
      Edge f = opposite(e);
      sym_edge_maps.erase(e);
      sym_edge_maps.erase(f);
      ListGraph::erase(f);
      ListGraph::erase(e);
    }    
  };


  ///A graph class containing only nodes.

  ///This class implements a graph structure without edges.
  ///The most useful application of this class is to be the node set of an
  ///\ref EdgeSet class.
  ///
  ///It conforms to the graph interface documented under
  ///the description of \ref GraphSkeleton with the exception that you cannot
  ///add (or delete) edges. The usual edge iterators are exists, but they are
  ///always \ref INVALID.
  ///\sa \ref GraphSkeleton
  ///\sa \ref EdgeSet
  class NodeSet {

    //Nodes are double linked.
    //The free nodes are only single linked using the "next" field.
    struct NodeT 
    {
      int first_in,first_out;
      int prev, next;
      //      NodeT() {}
    };

    std::vector<NodeT> nodes;
    //The first node
    int first_node;
    //The first free node
    int first_free_node;
    
  public:

    typedef NodeSet Graph;
    
    class Node;
    class Edge;

  public:

    class NodeIt;
    class EdgeIt;
    class OutEdgeIt;
    class InEdgeIt;
    
    CREATE_MAP_REGISTRIES;
    CREATE_MAPS(DefaultMapFactory);
    
  public:

    ///Default constructor
    NodeSet() 
      : nodes(), first_node(-1), first_free_node(-1) {}
    ///Copy constructor
    NodeSet(const NodeSet &_g) 
      : nodes(_g.nodes), first_node(_g.first_node),
	first_free_node(_g.first_free_node) {}
    
    int nodeNum() const { return nodes.size(); }  //FIXME: What is this?
    int edgeNum() const { return 0; }  //FIXME: What is this?

    ///\bug This function does something different than
    ///its name would suggests...
    int maxNodeId() const { return nodes.size(); }  //FIXME: What is this?
    ///\bug This function does something different than
    ///its name would suggests...
    int maxEdgeId() const { return 0; }  //FIXME: What is this?

    Node tail(Edge e) const { return INVALID; }
    Node head(Edge e) const { return INVALID; }

    NodeIt& first(NodeIt& v) const { 
      v=NodeIt(*this); return v; }
    EdgeIt& first(EdgeIt& e) const { 
      e=EdgeIt(*this); return e; }
    OutEdgeIt& first(OutEdgeIt& e, const Node v) const { 
      e=OutEdgeIt(*this,v); return e; }
    InEdgeIt& first(InEdgeIt& e, const Node v) const { 
      e=InEdgeIt(*this,v); return e; }

    int id(Node v) const { return v.n; }
    int id(Edge e) const { return -1; }

    /// Adds a new node to the graph.

    /// \todo It adds the nodes in a reversed order.
    /// (i.e. the lastly added node becomes the first.)
    Node addNode() {
      int n;
      
      if(first_free_node==-1)
	{
	  n = nodes.size();
	  nodes.push_back(NodeT());
	}
      else {
	n = first_free_node;
	first_free_node = nodes[n].next;
      }
      
      nodes[n].next = first_node;
      if(first_node != -1) nodes[first_node].prev = n;
      first_node = n;
      nodes[n].prev = -1;
      
      nodes[n].first_in = nodes[n].first_out = -1;
      
      Node nn; nn.n=n;

      //Update dynamic maps
      node_maps.add(nn);

      return nn;
    }
    
    void erase(Node nn) {
      int n=nn.n;
      
      if(nodes[n].next != -1) nodes[nodes[n].next].prev = nodes[n].prev;
      if(nodes[n].prev != -1) nodes[nodes[n].prev].next = nodes[n].next;
      else first_node = nodes[n].next;
      
      nodes[n].next = first_free_node;
      first_free_node = n;

      //Update dynamic maps
      node_maps.erase(nn);
    }
    
        
    Edge findEdge(Node u,Node v, Edge prev = INVALID) 
    {
      return INVALID;
    }
    
    void clear() {
      node_maps.clear();
      nodes.clear();
      first_node = first_free_node = -1;
    }

    class Node {
      friend class NodeSet;
      template <typename T> friend class NodeMap;
      
      friend class Edge;
      friend class OutEdgeIt;
      friend class InEdgeIt;

    protected:
      int n;
      friend int NodeSet::id(Node v) const; 
      Node(int nn) {n=nn;}
    public:
      Node() {}
      Node (Invalid i) { n=-1; }
      bool operator==(const Node i) const {return n==i.n;}
      bool operator!=(const Node i) const {return n!=i.n;}
      bool operator<(const Node i) const {return n<i.n;}
    };
    
    class NodeIt : public Node {
      const NodeSet *G;
      friend class NodeSet;
    public:
      NodeIt() : Node() { }
      NodeIt(const NodeSet& _G,Node n) : Node(n), G(&_G) { }
      NodeIt(Invalid i) : Node(i) { }
      NodeIt(const NodeSet& _G) : Node(_G.first_node), G(&_G) { }
      NodeIt &operator++() {
	n=G->nodes[n].next; 
	return *this; 
      }
    };

    class Edge {
      //friend class NodeSet;
      //template <typename T> friend class EdgeMap;

      //template <typename T> friend class SymNodeSet::SymEdgeMap;      
      //friend Edge SymNodeSet::opposite(Edge) const;
      
      //      friend class Node;
      //      friend class NodeIt;
    protected:
      //friend int NodeSet::id(Edge e) const;
      //      Edge(int nn) {}
    public:
      Edge() { }
      Edge (Invalid) { }
      bool operator==(const Edge i) const {return true;}
      bool operator!=(const Edge i) const {return false;}
      bool operator<(const Edge i) const {return false;}
      ///\bug This is a workaround until somebody tells me how to
      ///make class \c SymNodeSet::SymEdgeMap friend of Edge
      //      int idref() {return -1;}
      //      int idref() const {return -1;}
    };
    
    class EdgeIt : public Edge {
      //friend class NodeSet;
    public:
      EdgeIt(const NodeSet& G) : Edge() { }
      EdgeIt(const NodeSet&, Edge) : Edge() { }
      EdgeIt (Invalid i) : Edge(i) { }
      EdgeIt() : Edge() { }
      ///\bug This is a workaround until somebody tells me how to
      ///make class \c SymNodeSet::SymEdgeMap friend of Edge
      //      int idref() {return -1;}
      EdgeIt operator++() { return INVALID; }
    };
    
    class OutEdgeIt : public Edge {
      friend class NodeSet;
    public: 
      OutEdgeIt() : Edge() { }
      OutEdgeIt(const NodeSet&, Edge) : Edge() { }
      OutEdgeIt (Invalid i) : Edge(i) { }
      OutEdgeIt(const NodeSet& G,const Node v)	: Edge() {}
      OutEdgeIt operator++() { return INVALID; }
    };
    
    class InEdgeIt : public Edge {
      friend class NodeSet;
    public: 
      InEdgeIt() : Edge() { }
      InEdgeIt(const NodeSet&, Edge) : Edge() { }
      InEdgeIt (Invalid i) : Edge(i) { }
      InEdgeIt(const NodeSet& G,Node v) :Edge() {}
      InEdgeIt operator++() { return INVALID; }
    };

  };



  ///Graph structure using a node set of another graph.

  ///This structure can be used to establish another graph over a node set
  /// of an existing one. The node iterator will go through the nodes of the
  /// original graph, and the NodeMap's of both graphs will convert to
  /// each other.
  ///
  ///\warning Adding or deleting nodes from the graph is not safe if an
  ///\ref EdgeSet is currently attached to it!
  ///
  ///\todo Make it possible to add/delete edges from the base graph
  ///(and from \ref EdgeSet, as well)
  ///
  ///\param GG The type of the graph which shares its node set with this class.
  ///Its interface must conform with \ref GraphSkeleton.
  ///
  ///It conforms to the graph interface documented under
  ///the description of \ref GraphSkeleton.
  ///\sa \ref GraphSkeleton.
  ///\sa \ref NodeSet.
  template<typename GG>
  class EdgeSet {

    typedef GG NodeGraphType;

    NodeGraphType &G;

  public:

    class Node;
    class Edge;
    class OutEdgeIt;
    class InEdgeIt;
    class SymEdge;

    typedef EdgeSet Graph;

    int id(Node v) const; 

    class Node : public NodeGraphType::Node {
      friend class EdgeSet;
      //      template <typename T> friend class NodeMap;
      
      friend class Edge;
      friend class OutEdgeIt;
      friend class InEdgeIt;
      friend class SymEdge;

    public:
      friend int EdgeSet::id(Node v) const; 
      //      Node(int nn) {n=nn;}
    public:
      Node() : NodeGraphType::Node() {}
      Node (Invalid i) : NodeGraphType::Node(i) {}
      Node(const typename NodeGraphType::Node &n) : NodeGraphType::Node(n) {}
    };
    
    class NodeIt : public NodeGraphType::NodeIt {
      friend class EdgeSet;
    public:
      NodeIt() : NodeGraphType::NodeIt() { }
      NodeIt(const EdgeSet& _G,Node n) : NodeGraphType::NodeIt(_G.G,n) { }
      NodeIt (Invalid i) : NodeGraphType::NodeIt(i) {}
      NodeIt(const EdgeSet& _G) : NodeGraphType::NodeIt(_G.G) { }
      NodeIt(const typename NodeGraphType::NodeIt &n)
	: NodeGraphType::NodeIt(n) {}

      operator Node() { return Node(*this);}
      NodeIt &operator++()
      { this->NodeGraphType::NodeIt::operator++(); return *this;} 
    };

  private:
    //Edges are double linked.
    //The free edges are only single linked using the "next_in" field.
    struct NodeT 
    {
      int first_in,first_out;
      NodeT() : first_in(-1), first_out(-1) { }
    };

    struct EdgeT 
    {
      Node head, tail;
      int prev_in, prev_out;
      int next_in, next_out;
    };

    
    typename NodeGraphType::template NodeMap<NodeT> nodes;
    
    std::vector<EdgeT> edges;
    //The first free edge
    int first_free_edge;
    
  public:
    
    class Node;
    class Edge;

    class NodeIt;
    class EdgeIt;
    class OutEdgeIt;
    class InEdgeIt;


    CREATE_EDGE_MAP_REGISTRY;
    CREATE_EDGE_MAP_FACTORY(DefaultMapFactory);
    IMPORT_EDGE_MAP(EdgeMapFactory);
    
    
  public:

    ///Constructor
    
    ///Construates a new graph based on the nodeset of an existing one.
    ///\param _G the base graph.
    ///\todo It looks like a copy constructor, but it isn't.
    EdgeSet(NodeGraphType &_G) 
      : G(_G), nodes(_G), edges(),
	first_free_edge(-1) {}
    ///Copy constructor

    ///Makes a copy of an EdgeSet.
    ///It will be based on the same graph.
    EdgeSet(const EdgeSet &_g) 
      : G(_g.G), nodes(_g.G), edges(_g.edges),
	first_free_edge(_g.first_free_edge) {}
    
    int nodeNum() const { return G.nodeNum(); }  //FIXME: What is this?
    int edgeNum() const { return edges.size(); }  //FIXME: What is this?

    ///\bug This function does something different than
    ///its name would suggests...
    int maxNodeId() const { return G.maxNodeId(); }  //FIXME: What is this?
    ///\bug This function does something different than
    ///its name would suggests...
    int maxEdgeId() const { return edges.size(); }  //FIXME: What is this?

    Node tail(Edge e) const { return edges[e.n].tail; }
    Node head(Edge e) const { return edges[e.n].head; }

    NodeIt& first(NodeIt& v) const { 
      v=NodeIt(*this); return v; }
    EdgeIt& first(EdgeIt& e) const { 
      e=EdgeIt(*this); return e; }
    OutEdgeIt& first(OutEdgeIt& e, const Node v) const { 
      e=OutEdgeIt(*this,v); return e; }
    InEdgeIt& first(InEdgeIt& e, const Node v) const { 
      e=InEdgeIt(*this,v); return e; }

    int id(Edge e) const { return e.n; }

    /// Adds a new node to the graph.
    Node addNode() { return G.addNode(); }
    
    Edge addEdge(Node u, Node v) {
      int n;
      
      if(first_free_edge==-1)
	{
	  n = edges.size();
	  edges.push_back(EdgeT());
	}
      else {
	n = first_free_edge;
	first_free_edge = edges[n].next_in;
      }
      
      edges[n].tail = u; edges[n].head = v;

      edges[n].next_out = nodes[u].first_out;
      if(nodes[u].first_out != -1) edges[nodes[u].first_out].prev_out = n;
      edges[n].next_in = nodes[v].first_in;
      if(nodes[v].first_in != -1) edges[nodes[v].first_in].prev_in = n;
      edges[n].prev_in = edges[n].prev_out = -1;
	
      nodes[u].first_out = nodes[v].first_in = n;

      Edge e; e.n=n;

      //Update dynamic maps
      edge_maps.add(e);

      return e;
    }

    /// Finds an edge between two nodes.

    /// Finds an edge from node \c u to node \c v.
    ///
    /// If \c prev is \ref INVALID (this is the default value), then
    /// It finds the first edge from \c u to \c v. Otherwise it looks for
    /// the next edge from \c u to \c v after \c prev.
    /// \return The found edge or INVALID if there is no such an edge.
    Edge findEdge(Node u,Node v, Edge prev = INVALID) 
    {
      int e = (prev.n==-1)? nodes[u].first_out : edges[prev.n].next_out;
      while(e!=-1 && edges[e].tail!=v) e = edges[e].next_out;
      prev.n=e;
      return prev;
    }
    
  private:
    void eraseEdge(int n) {
      
      if(edges[n].next_in!=-1)
	edges[edges[n].next_in].prev_in = edges[n].prev_in;
      if(edges[n].prev_in!=-1)
	edges[edges[n].prev_in].next_in = edges[n].next_in;
      else nodes[edges[n].head].first_in = edges[n].next_in;
      
      if(edges[n].next_out!=-1)
	edges[edges[n].next_out].prev_out = edges[n].prev_out;
      if(edges[n].prev_out!=-1)
	edges[edges[n].prev_out].next_out = edges[n].next_out;
      else nodes[edges[n].tail].first_out = edges[n].next_out;
      
      edges[n].next_in = first_free_edge;
      first_free_edge = -1;      

      //Update dynamic maps
      Edge e; e.n = n;
      edge_maps.erase(e);
    }
      
  public:

//     void erase(Node nn) {
//       int n=nn.n;
//       int m;
//       while((m=nodes[n].first_in)!=-1) eraseEdge(m);
//       while((m=nodes[n].first_out)!=-1) eraseEdge(m);
//     }
    
    void erase(Edge e) { eraseEdge(e.n); }

    ///Clear all edges. (Doesn't clear the nodes!)
    void clear() {
      edge_maps.clear();
      edges.clear();
      first_free_edge=-1;
    }


    class Edge {
    public:
      friend class EdgeSet;
      template <typename T> friend class EdgeMap;

      friend class Node;
      friend class NodeIt;
    public:
      ///\bug It should be at least protected
      ///
      int n;
    protected:
      friend int EdgeSet::id(Edge e) const;

      Edge(int nn) {n=nn;}
    public:
      Edge() { }
      Edge (Invalid) { n=-1; }
      bool operator==(const Edge i) const {return n==i.n;}
      bool operator!=(const Edge i) const {return n!=i.n;}
      bool operator<(const Edge i) const {return n<i.n;}
      ///\bug This is a workaround until somebody tells me how to
      ///make class \c SymEdgeSet::SymEdgeMap friend of Edge
      int &idref() {return n;}
      const int &idref() const {return n;}
    };
    
    class EdgeIt : public Edge {
      friend class EdgeSet;
      template <typename T> friend class EdgeMap;
    
      const EdgeSet *G;
    public:
      EdgeIt(const EdgeSet& _G) : Edge(), G(&_G) {
	//      	typename NodeGraphType::Node m;
        NodeIt m;
	for(G->first(m);
	    m!=INVALID && G->nodes[m].first_in == -1;  ++m);
	///\bug AJJAJ! This is a non sense!!!!!!!
	this->n = m!=INVALID?-1:G->nodes[m].first_in;
      }
      EdgeIt(const EdgeSet& _G, Edge e) : Edge(e), G(&_G) { }
      EdgeIt (Invalid i) : Edge(i) { }
      EdgeIt() : Edge() { }
      ///.
      
      ///\bug UNIMPLEMENTED!!!!!
      //
      EdgeIt &operator++() {
	return *this;
      }
       ///\bug This is a workaround until somebody tells me how to
      ///make class \c SymEdgeSet::SymEdgeMap friend of Edge
      int &idref() {return this->n;}
    };
    
    class OutEdgeIt : public Edge {
      const EdgeSet *G;
      friend class EdgeSet;
    public: 
      OutEdgeIt() : Edge() { }
      OutEdgeIt (Invalid i) : Edge(i) { }
      OutEdgeIt(const EdgeSet& _G, Edge e) : Edge(e), G(&_G) { }

      OutEdgeIt(const EdgeSet& _G,const Node v) :
	Edge(_G.nodes[v].first_out), G(&_G) { }
      OutEdgeIt &operator++() { n = G->edges[n].next_out; return *this; }
    };
    
    class InEdgeIt : public Edge {
      const EdgeSet *G;
      friend class EdgeSet;
    public: 
      InEdgeIt() : Edge() { }
      InEdgeIt (Invalid i) : Edge(i) { }
      InEdgeIt(const EdgeSet& _G, Edge e) : Edge(e), G(&_G) { }
      InEdgeIt(const EdgeSet& _G,Node v)
	: Edge(_G.nodes[v].first_in), G(&_G) { }
      InEdgeIt &operator++() { n=G->edges[n].next_in; return *this; }
    };

    
    template <typename V> class NodeMap 
      : public NodeGraphType::template NodeMap<V>
    {
      //This is a must, the constructors need it.
      typedef typename NodeGraphType::template NodeMap<V> MapImpl;
      typedef V Value;
    public:
      NodeMap() : MapImpl() {}
      
      NodeMap(const EdgeSet& graph) 
	: MapImpl(graph.G) { }

      NodeMap(const EdgeSet& graph, const Value& value) 
	: MapImpl(graph.G, value) { }

      NodeMap(const NodeMap& copy) 
	: MapImpl(static_cast<const MapImpl&>(copy)) {}

      template<typename CMap>
      NodeMap(const CMap& copy)
	: MapImpl(copy) { }

      NodeMap& operator=(const NodeMap& copy) {
	MapImpl::operator=(static_cast<const MapImpl&>(copy));
	return *this;
      }

      template <typename CMap>
      NodeMap& operator=(const CMap& copy) {
	MapImpl::operator=(copy);
	return *this;
      }

    };
  };

  template<typename GG>
  inline int EdgeSet<GG>::id(Node v) const { return G.id(v); }

/// @}  

} //namespace hugo

#endif //HUGO_LIST_GRAPH_H
