-fix time assertion introduce in last patch
[oweals/gnunet.git] / src / dht / gnunet-service-xdht_neighbours.c
index 733d3daa3b3d002fe5a6e5571be385b31ef552db..a0b1c378fd2c539fcc6e9a8f1a163be2ae76dd2b 100644 (file)
 #include <fenv.h>
 #include "dht.h"
 
-/* TODO:
- 1. to randomly choose one of the routes in case there are multiple
-    routes to reach to the finger. 
- 2. Structure alignment.
- 3. In put, we don't have anything like put result. so we are not adding anything
-    in the routing table.
- 4. Maintain a list of trails --> struct Trail *all_trails_head
- * struct Trail *all_trails_tail. How do I keep it as an array and not as a list?? 
- * First will complete the logic everywhere and then make this change.   
- 5. At some places you use memcpy and at some places =, use uniformly.
- 6. I have removed compare_and_update_predecessor from handle_dht_p2p_Trail_setup
- * (refer to google docs for reason). 
-*/
+/**
+ * FIXME: 
+ * 1. In X-Vine paper, there is no policy defined for replicating the data to
+ * recover in case of peer failure. We can do it in Chord way. In R5N, the key
+ * is hashed and then data is stored according to the key value generated after
+ * hashing.
+ * 2. We will keep an entry in routing table even if its a friend for the moment.
+ * Because I am not sure if there is a case where it will not work. 
+ * Trail id we can keep but actually there is no trail.
+ */
 
 /**
- * Maximum possible fingers of a peer.
+ * Maximum possible fingers (including predecessor) of a peer 
  */
-#define MAX_FINGERS 66
+#define MAX_FINGERS 65
 
 /**
  * Maximum allowed number of pending messages per friend peer.
 #define DHT_FIND_FINGER_TRAIL_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
 
 /**
- * How long at most to wait for transmission of a request to another peer?
+ * How long at most to wait for transmission of a request to a friend ?
+ */
+#define GET_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2)
+
+/**
+ * Duration for which I may remain congested. 
+ * Note: Its a static value. In future, a peer may do some analysis and calculate 
+ * congestion_timeout based on 'some' parameters. 
+ */
+#define CONGESTION_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2)
+
+/**
+ * Maximum number of trails allowed to go through a friend.
  */
-#define GET_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
+#define TRAILS_THROUGH_FRIEND_THRESHOLD 64
 
 /**
  * Maximum number of trails stored per finger.
  */
-#define TRAILS_COUNT 2
+#define MAXIMUM_TRAILS_PER_FINGER 1
+
+/**
+ * Finger map index for predecessor entry in finger table.
+ */
+#define PREDECESSOR_FINGER_ID 64
+
+/**
+ * Wrap around in peer identity circle. 
+ */
+#define PEER_IDENTITES_WRAP_AROUND pow(2, 64) - 1
 
 /**
- * Used to distinguish put/get request use of find_successor() from others 
+ * FIXME: Its use only at 3 places check if you can remove it.
+ * To check if a finger is predecessor or not. 
  */
-#define PUT_GET_REQUEST 68
+enum GDS_NEIGHBOURS_finger_type
+{
+  GDS_FINGER_TYPE_PREDECESSOR = 0,
+  GDS_FINGER_TYPE_NON_PREDECESSOR = 1
+};
 
 GNUNET_NETWORK_STRUCT_BEGIN
-  
+
 /**
  * P2P PUT message
  */
@@ -127,14 +151,16 @@ struct PeerPutMessage
   uint32_t put_path_length GNUNET_PACKED;
   
   /** 
-   * Current destination to which this message is forwarded.
+   * Best known destination (could be my friend or finger) which should
+   * get this message next. 
    */
-  struct GNUNET_PeerIdentity current_destination;
+  struct GNUNET_PeerIdentity best_known_destination;
   
   /**
-   * Peer whose finger is current_destination. 
+   * In case best_known_destination is a finger, then trail to reach
+   * to that finger. Else its default value is 0. 
    */
-  struct GNUNET_PeerIdentity current_source;
+  struct GNUNET_HashCode intermediate_trail_id;
   
   /**
    * When does the content expire?
@@ -152,57 +178,6 @@ struct PeerPutMessage
  
 };
 
-
-/**
- * P2P Result message
- */
-struct PeerGetResultMessage
-{
-  /**
-   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_GET_RESULT
-   */
-  struct GNUNET_MessageHeader header;
-
-  /**
-   * The type for the data.
-   */
-  uint32_t type GNUNET_PACKED;
-  
-  /**
-   * Peer which will receive the get result message. 
-   */
-  struct GNUNET_PeerIdentity source_peer;
-
-  /**
-   * Number of peers recorded in the outgoing path from source to the
-   * stored location of this message.
-   */
-  uint32_t put_path_length GNUNET_PACKED;
-  
-  /**
-   * Length of the GET path that follows (if tracked).
-   */
-  uint32_t get_path_length GNUNET_PACKED;
-
-  /**
-   * When does the content expire?
-   */
-  struct GNUNET_TIME_Absolute expiration_time;
-
-  /**
-   * The key of the corresponding GET request.
-   */
-  struct GNUNET_HashCode key;
-  /* put path (if tracked) */
-
-  /* get path (if tracked) */
-
-  /* Payload */
-
-};
-
-
 /**
  * P2P GET message
  */
@@ -240,14 +215,16 @@ struct PeerGetMessage
   unsigned int get_path_length;
   
   /**
-   * Peer which is an intermediate destination. 
+   * Best known destination (could be my friend or finger) which should
+   * get this message next. 
    */
-  struct GNUNET_PeerIdentity current_destination;
+  struct GNUNET_PeerIdentity best_known_destination;
   
   /**
-   * Source for which current_destination is the finger. 
+   * In case best_known_destination is a finger, then trail to reach
+   * to that finger. Else its default value is 0. 
    */
-  struct GNUNET_PeerIdentity current_source;
+  struct GNUNET_HashCode intermediate_trail_id;
  
   /**
    * The key we are looking for.
@@ -258,203 +235,223 @@ struct PeerGetMessage
 
 };
 
-
 /**
- * P2P Trail setup message
+ * P2P Result message
  */
-struct PeerTrailSetupMessage
+struct PeerGetResultMessage
 {
-  
   /**
-   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP
+   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_GET_RESULT
    */
   struct GNUNET_MessageHeader header;
-  
-  /**
-   * Successor of this finger value will be our finger peer.
-   */
-  uint64_t destination_finger;
 
   /**
-   * Source peer which wants to setup the trail to one of its finger. 
+   * The type for the data.
    */
-  struct GNUNET_PeerIdentity source_peer;
+  uint32_t type GNUNET_PACKED;
   
   /**
-   * Peer to which this packet is forwarded.
+   * Number of peers recorded in the outgoing path from source to the
+   * stored location of this message.
    */
-  struct GNUNET_PeerIdentity current_destination;
+  uint32_t put_path_length GNUNET_PACKED;
   
   /**
-   * In case the packet is forwarded to an intermediate finger, then 
-   * current_source contains the peer id whose finger is the intermediate
-   * finger. In case the packet is forwarded to a friend, then it is NULL.
-   * FIXME: check the usage of current_source and fix this comment. 
+   * Length of the GET path that follows (if tracked).
    */
-  struct GNUNET_PeerIdentity current_source;
+  uint32_t get_path_length GNUNET_PACKED;
   
   /**
-   * Index into finger peer map, in Network Byte Order
+   * Peer which queried for get and should get the result
    */
-  uint32_t finger_map_index;
+  struct GNUNET_PeerIdentity querying_peer;
   
   /**
-   * Number of entries in trail list, in Network Byte Order.
+   * When does the content expire?
    */
-  uint32_t trail_length GNUNET_PACKED;
-  
-  /* Trail formed in the process. */
-};
+  struct GNUNET_TIME_Absolute expiration_time;
+
+  /**
+   * The key of the corresponding GET request.
+   */
+  struct GNUNET_HashCode key;
+  /* put path (if tracked) */
+
+  /* get path (if tracked) */
+
+  /* Payload */
 
+};
 
 /**
- * P2P Trail Setup Result message
+ * P2P Trail setup message
  */
-struct PeerTrailSetupResultMessage
+struct PeerTrailSetupMessage
 {
-  
   /**
-   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP_RESULT
+   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP
    */
   struct GNUNET_MessageHeader header;
   
   /**
-   * Finger to which we have found the path. 
+   * Is source_peer trying to setup the trail to a predecessor or any finger.
    */
-  struct GNUNET_PeerIdentity finger_identity;
+  uint32_t is_predecessor; 
+  
+  /**
+   * Peer closest to this value will be our finger.
+   */
+  uint64_t final_destination_finger_value;
 
   /**
-   * Peer which was looking for the trail to finger. 
+   * Source peer which wants to setup the trail to one of its finger.
    */
-  struct GNUNET_PeerIdentity destination_peer;
-  
+  struct GNUNET_PeerIdentity source_peer;
+
   /**
-   * Index into finger peer map in NBO.
+   * Best known destination (could be my friend or finger) which should
+   * get this message next. 
    */
-  uint32_t finger_map_index;
-  
+  struct GNUNET_PeerIdentity best_known_destination; 
+
   /**
-   * Number of entries in trail list in NBO.
+   * In case best_known_destination is a finger, then trail id of trail to
+   * reach to this finger.
    */
-  uint32_t trail_length GNUNET_PACKED;
+  struct GNUNET_HashCode intermediate_trail_id;
   
-  /* Trail from destination_peer to finger_identity */
-  
-};
+  /**
+   * Trail id for trail which we are trying to setup.
+   */
+  struct GNUNET_HashCode trail_id; 
 
+  /* List of peers which are part of trail setup so far.
+   * Trail does NOT include source_peer and peer which will be closest to
+   * ultimate_destination_finger_value.
+   * struct GNUNET_PeerIdentity trail[]
+   */
+};
 
 /**
- * P2P Trail Rejection Message. 
+  * P2P Trail Setup Result message
  */
-struct PeerTrailRejectionMessage
+struct PeerTrailSetupResultMessage
 {
+
   /**
-   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_REJECTION
+   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP_RESULT
    */
   struct GNUNET_MessageHeader header;
-  
+
   /**
-   * Source peer which wants to set up the trail. 
+   * Finger to which we have found the path.
    */
-  struct GNUNET_PeerIdentity source_peer;
-  
+  struct GNUNET_PeerIdentity finger_identity;
+
   /**
-   * Peer which sent trail rejection message. 
+   * Peer which started trail_setup to find trail to finger_identity
    */
-  struct GNUNET_PeerIdentity congested_peer;
-  
+  struct GNUNET_PeerIdentity querying_peer; 
+
   /**
-   * Peer identity which will be successor to this value will be finger of
-   * source_peer. 
+   * Is the trail setup to querying_peer's predecessor or finger?
    */
-  uint64_t finger_identity_value;
-  
+  uint32_t is_predecessor; 
+
   /**
-   * Index in finger peer map of source peer.
+   * Value to which finger_identity is the closest peer. 
    */
-  uint32_t finger_map_index;
+  uint64_t ulitmate_destination_finger_value;
   
   /**
-   * Total number of peers in the trail.
+   * Identifier of the trail from querying peer to finger_identity, NOT
+   * including both endpoints. 
    */
-  uint32_t trail_length;
-  
-  /* Trail_list from source_peer to peer which sent the message for trail setup
-   * to congested peer.*/
-};
+  struct GNUNET_HashCode trail_id;
 
+  /* List of peers which are part of the trail from querying peer to 
+   * finger_identity, NOT including both endpoints.
+   * struct GNUNET_PeerIdentity trail[] 
+   */
+};
 
 /**
- * P2P Verify Successor message. 
+ * P2P Verify Successor Message.
  */
 struct PeerVerifySuccessorMessage
 {
-  
   /**
    * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_VERIFY_SUCCESSOR
    */
   struct GNUNET_MessageHeader header;
-  
+
   /**
-   * Source peer which wants to verify its successor. 
+   * Peer which wants to verify its successor.
    */
   struct GNUNET_PeerIdentity source_peer;
-  
+
   /**
-   * My current successor.
+   * Source Peer's current successor.
    */
   struct GNUNET_PeerIdentity successor;
-  
+
   /**
-   * Total number of peers in trail to current successor.
+   * Identifier of trail to reach from source_peer to successor.
    */
-  uint32_t trail_length;
-  
-  /* Trail to reach to from source_peer to successor. */
-};
+  struct GNUNET_HashCode trail_id;
 
+  /* List of the peers which are part of trail to reach  from source_peer 
+   * to successor, NOT including them
+   * struct GNUNET_PeerIdentity trail[] 
+   */
+};
 
 /**
- * P2P Verify Successor Result message. 
+ * P2P Verify Successor Result Message
  */
 struct PeerVerifySuccessorResultMessage
 {
-  
   /**
    * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_VERIFY_SUCCESSOR_RESULT
    */
   struct GNUNET_MessageHeader header;
-  
+
   /**
-   * Destination peer which sent the request to verify its successor. 
+   * Peer which sent the request to verify its successor.
    */
-  struct GNUNET_PeerIdentity destination_peer;
-  
+  struct GNUNET_PeerIdentity querying_peer;
+
   /**
    * Successor to which PeerVerifySuccessorMessage was sent.
    */
-  struct GNUNET_PeerIdentity source_successor;
-  
+  struct GNUNET_PeerIdentity current_successor;
+
   /**
-   * source_successor's predecessor
+   * Current Predecessor of source_successor. It can be same as querying peer
+   * or different. In case it is different then it can be querying_peer's
+   * probable successor. 
    */
-  struct GNUNET_PeerIdentity my_predecessor;
-  
+  struct GNUNET_PeerIdentity probable_successor;
+
   /**
-   * Total number of peers in trail.
+   * Trail identifier of trail from querying_peer to current_successor.
    */
-  uint32_t trail_length; 
-  
-  /* Trail to reach from destination_peer to its correct successor.
-   * If source_successor is not destination peer, then trail is from destination_peer
-   * to my_predecessor.
-   * If source_successor is destination peer, then trail is from destination_peer
-   * to source_successor. */
-};
+  struct GNUNET_HashCode trail_id;
+
+  /**
+   * Direction in which we are looking at the trail.
+   */
+  uint32_t trail_direction;
 
+  /* In case probable_successor != querying_peer, then trail to reach from
+   * querying_peer to probable_successor, NOT including end points.
+   * struct GNUNET_PeerIdentity trail[]
+   */
+};
 
 /**
- * P2P Notify New Successor message.
+ * P2P Notify New Successor Message.
  */
 struct PeerNotifyNewSuccessorMessage
 {
@@ -462,184 +459,219 @@ struct PeerNotifyNewSuccessorMessage
    * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_NOTIFY_NEW_SUCCESSOR
    */
   struct GNUNET_MessageHeader header;
-  
+
   /**
-   * Source peer which wants to notify its new successor. 
+   * Peer which wants to notify its new successor.
    */
   struct GNUNET_PeerIdentity source_peer;
-  
-  /** 
-   * Old successor of source peer. 
-   */
-  struct GNUNET_PeerIdentity old_successor;
-  
+
   /**
-   * New successor identity.
+   * New successor of source_peer.
    */
-  struct GNUNET_PeerIdentity destination_peer;
-  
+  struct GNUNET_PeerIdentity new_successor;
+
   /**
-   * Number of peers in trail from source_peer to new successor.
+   * Unique identifier of the trail from source_peer to new_successor,
+   * NOT including the endpoints.
+   */
+  struct GNUNET_HashCode trail_id;
+
+  /* List of peers in trail from source_peer to new_successor, 
+   * NOT including the endpoints. 
+   * struct GNUNET_PeerIdentity trail[]
    */
-  uint32_t trail_length;
-  
-  /* Trail to from source_peer to destination_peer. */
 };
 
-struct PeerTrailTearDownMessage
+/**
+ * P2P Trail Compression Message.
+ */
+struct PeerTrailCompressionMessage
 {
   /**
-   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_TEARDOWN
+   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_COMPRESSION
    */
   struct GNUNET_MessageHeader header;
-  
+
   /**
-   * Source peer of this trail.  
+   * Source peer of this trail.
    */
   struct GNUNET_PeerIdentity source_peer;
-  
-  /**
-   * Destination peer of this trail. 
-   */
-  struct GNUNET_PeerIdentity destination_peer;
-  
+
   /**
-   * Trail from source_peer to destination_peer compressed such that 
-   * new_first_friend is the first hop in the trail from source to 
-   * destination. 
+   * Trail from source_peer to destination_peer compressed such that
+   * new_first_friend is the first hop in the trail from source to
+   * destination.
    */
   struct GNUNET_PeerIdentity new_first_friend;
+
   /**
-   * Number of peers in trail from source_peer to new first friend.
+   * Unique identifier of trail.
    */
-  uint32_t trail_length;
-  
-  /* Trail from source_peer to new first friend. */
+  struct GNUNET_HashCode trail_id;
 };
 
 
-struct PeerAddTrailMessage
+/**
+ * P2P Trail Tear Down message.
+ */
+struct PeerTrailTearDownMessage
 {
   /**
-   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_ADD_TRAIL
+   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_TEARDOWN
    */
   struct GNUNET_MessageHeader header;
-  
-  /**
-   * Source peer of the routing trail. 
-   */
-  struct GNUNET_PeerIdentity source_peer;
-  
+
   /**
-   * Destination peer of the routing trail. 
+   * Unique identifier of the trail.
    */
-  struct GNUNET_PeerIdentity destination_peer;
-  
+  struct GNUNET_HashCode trail_id;
+
   /**
-   * Total number of peers from source peer to destination peer. 
+   * Direction of trail.
    */
-  unsigned int trail_length;
-  
-  /* Trail from source peer to destination peer. */
-  
+  uint32_t trail_direction;
 };
 
-GNUNET_NETWORK_STRUCT_END
-
 
 /**
- * Linked list of messages to send to a particular other peer.
+ * P2P Trail Rejection Message.
  */
-struct P2PPendingMessage
+struct PeerTrailRejectionMessage
 {
   /**
-   * Pointer to next item in the list
+   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP_REJECTION
    */
-  struct P2PPendingMessage *next;
+  struct GNUNET_MessageHeader header;
 
   /**
-   * Pointer to previous item in the list
+   * Peer which wants to set up the trail.
    */
-  struct P2PPendingMessage *prev;
+  struct GNUNET_PeerIdentity source_peer;
 
   /**
-   * Message importance level.  FIXME: used? useful?
+   * Peer which sent trail rejection message as it it congested. 
    */
-  unsigned int importance;
-  
+  struct GNUNET_PeerIdentity congested_peer;
+
   /**
-   * When does this message time out?
+   * Peer identity closest to this value will be finger of
+   * source_peer.
    */
-  struct GNUNET_TIME_Absolute timeout;
+  uint64_t ultimate_destination_finger_value;
+
+  /**
+   * Is source_peer trying to setup the trail to its predecessor or finger.
+   */
+  uint32_t is_predecessor;
+
+  /**
+   * Identifier for the trail that source peer is trying to setup.
+   */
+  struct GNUNET_HashCode trail_id;
   
   /**
-   * Actual message to be sent, allocated at the end of the struct:
-   * // msg = (cast) &pm[1];
-   * // memcpy (&pm[1], data, len);
+   * Relative time for which congested_peer will remain congested.
    */
-  const struct GNUNET_MessageHeader *msg;
+  struct GNUNET_TIME_Relative congestion_time;
 
+  /* Trail_list from source_peer to peer which sent the message for trail setup
+   * to congested peer. This trail does NOT include source_peer.
+   struct GNUNET_PeerIdnetity trail[]*/
 };
 
-
 /**
- * Linked List of peers which are part of trail to reach a particular Finger.
+ * P2P Add Trail Message.
  */
-struct TrailPeerList
+struct PeerAddTrailMessage
 {
-   /**
-    * Pointer to next item in the list
-    */
-   struct TrailPeerList *next;
+  /**
+   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_ADD_TRAIL
+   */
+  struct GNUNET_MessageHeader header;
 
-   /**
-    * Pointer to previous item in the list
-    */
-   struct TrailPeerList *prev;
-   
-   /**
-    * An element in this trail list
-    */
-   struct GNUNET_PeerIdentity peer;
-  
+  /**
+   * Source of the routing trail.
+   */
+  struct GNUNET_PeerIdentity source_peer;
+
+  /**
+   * Destination of the routing trail.
+   */
+  struct GNUNET_PeerIdentity destination_peer;
+
+  /**
+   * Unique identifier of the trail from source_peer to destination_peer,
+   * NOT including the endpoints.
+   */
+  struct GNUNET_HashCode trail_id;
+
+  /* Trail from source peer to destination peer, NOT including them.
+   * struct GNUNET_PeerIdentity trail[]
+   */
 };
 
+GNUNET_NETWORK_STRUCT_END
+
+/**
+ * Linked list of messages to send to a particular other peer.
+ */
+struct P2PPendingMessage
+{
+  /**
+   * Pointer to next item in the list
+   */
+  struct P2PPendingMessage *next;
+
+  /**
+   * Pointer to previous item in the list
+   */
+  struct P2PPendingMessage *prev;
+
+  /**
+   * Message importance level.  FIXME: used? useful?
+   */
+  unsigned int importance;
+
+  /**
+   * When does this message time out?
+   */
+  struct GNUNET_TIME_Absolute timeout;
+
+  /**
+   * Actual message to be sent, allocated at the end of the struct:
+   * // msg = (cast) &pm[1];
+   * // memcpy (&pm[1], data, len);
+   */
+  const struct GNUNET_MessageHeader *msg;
+
+};
 
-/** 
- * FIXME: for congested peer just define a relative time as #define.
+/**
  *  Entry in friend_peermap.
  */
 struct FriendInfo
 {
   /**
-   * Friend Identity 
+   * Friend Identity
    */
   struct GNUNET_PeerIdentity id;
 
   /**
-   * Number of trails for which this friend is the first hop. 
+   * Number of trails for which this friend is the first hop or if the friend
+   * is finger. 
    */
   unsigned int trails_count;
-  
+
   /**
    * Count of outstanding messages for this friend.
    */
   unsigned int pending_count;
-  
+
   /**
-   * FIXME: Refer to time.c and gnunet_time_lib.h for correct functions.
-   * in handle_dht_p2p_trail_rejection, you should update these values
-   * and whenever you are selecting a friend in select_random_friend()
-   * and find_successor(), you should check congestion_duration = 0,
-   * then proceed else if congestion_duration < your current time then also
-   * proceed. 
-   *        struct GNUNET_TIME_Absolute start = GNUNET_TIME_absolute_get();
-   *        struct GNUNET_TIME_Relative congestion_timeout =  
-   * congestion_duration = GNUNET_TIME_absolute_add (start,congestion_timeout);
-   * in select_random_friend, GNUNET_TIME_absolute_get_remaning()
+   * In case not 0, then amount of time for which this friend is congested.
    */
-  struct GNUNET_TIME_Absolute congestion_duration;
-  
+  struct GNUNET_TIME_Absolute congestion_timestamp;
+
   /**
    * Head of pending messages to be sent to this friend.
    */
@@ -649,7 +681,7 @@ struct FriendInfo
    * Tail of pending messages to be sent to this friend.
    */
   struct P2PPendingMessage *tail;
+
   /**
    * Core handle for sending messages to this friend.
    */
@@ -657,108 +689,152 @@ struct FriendInfo
 
 };
 
+/**
+ * An individual element of the trail to reach to a finger.
+ */
+struct Trail_Element 
+{
+  /**
+    * Pointer to next item in the list
+    */
+  struct Trail_Element *next;
+
+  /**
+    * Pointer to prev item in the list
+    */
+  struct Trail_Element *prev;
+
+  /**
+   * An element in this trail.
+   */
+  struct GNUNET_PeerIdentity peer;
+};
 
 /**
- * FIXME: make an array of trails. #define number of entries in the array = 
- * number of trails we want to keep. Remove head, tail of trails.
- * Entry in finger_peermap.
+ * FIXME: removed first_friend_trails_count, need to write a function
+ * to calculate each time we need it. Else, keep a pointer to first
+ * friend of in the trail. 
+ * Information about an individual trail. 
  */
-struct FingerInfo
+struct Trail 
 {
   /**
-   * Finger identity.
+   * Head of trail.
    */
-  struct GNUNET_PeerIdentity finger_identity;
-  
+  struct Trail_Element *trail_head;
+
   /**
-   * Index in finger peer map
+   * Tail of trail.
    */
-  unsigned int finger_map_index;
-  
+  struct Trail_Element *trail_tail;
+
   /**
-   * Number of trails to reach to this finger.
+   * Unique identifier of this trail.
    */
-  unsigned int trail_count;
-  
+  struct GNUNET_HashCode trail_id;
+
   /**
-   * Total number of entries in first trail from (me,finger)
+   * Length of trail pointed
    */
-  unsigned int first_trail_length;
+  unsigned int trail_length;
   
   /**
-   * Total number of entries in second trail from (me,finger)
+   * Is there a valid trail entry. 
    */
-  unsigned int second_trail_length;
-  
-  
+  unsigned int is_present;
+};
+
+/**
+ * An entry in finger_table
+ */
+struct FingerInfo
+{
   /**
-   * Number of trail of which the first element to reach to this finger is
-   * part of. 
+   * Finger identity.
    */
-  unsigned int first_friend_trails_count;
-  
+  struct GNUNET_PeerIdentity finger_identity;
+
   /**
-   * Head of first trail to reach this finger.
+   * Is any finger stored at this finger index. 
    */
-  struct TrailPeerList *first_trail_head;
+  unsigned int is_present;
   
   /**
-   * Tail of first trail to reach this finger.
+   * Index in finger peer map
    */
-  struct TrailPeerList *first_trail_tail;
-  
+  uint32_t finger_table_index;
+
   /**
-   * Head of second trail to reach this finger.
+   * Number of trails setup so far for this finger.
+   * Should not cross MAXIMUM_TRAILS_PER_FINGER.
    */
-  struct TrailPeerList *second_trail_head;
-  
+  uint32_t trails_count;
+
   /**
-   * Tail of second trail to reach this finger.
+   * Array of trails to reach to this finger.
    */
-  struct TrailPeerList *second_trail_tail;
-  
+  struct Trail trail_list[MAXIMUM_TRAILS_PER_FINGER]; 
 };
 
 
 /**
- * FIXME: The name is not correct. 
- * Used to specify the kind of value stored in the array all_known_peers. 
+ * Data structure to keep track of closest peer seen so far in find_successor()
  */
-enum current_destination_type
+struct Closest_Peer
 {
-  FRIEND,
-  FINGER,
-  VALUE,
-  MY_ID
-};
+  /**
+   * Destination finger vaule. 
+   */
+  uint64_t destination_finger_value;
+  
+  /**
+   * Is finger value predecessor or any other finge 
+   */
+  unsigned int is_predecessor;
+  
+  /**
+   * Trail id to reach to peer.
+   */
+  struct GNUNET_HashCode trail_id;
+
+  /**
+   * FIXME: see the usage of this field and write comment. 
+   */
+  struct GNUNET_PeerIdentity next_hop;
 
+  /**
+   * Next destination. In case of friend and my_identity , it is same as next_hop
+   * In case of finger it is finger identity.
+   */
+  struct GNUNET_PeerIdentity best_known_destination;
+};
 
 /**
- * Data structure passed to sorting algorithm in find_successor().
+ * FIXME: now I have removed the first_friend_trail_count,
+ * Need to update the code to find the count.
+ * Data structure to store the trail chosen to reach to finger.
  */
-struct Sorting_List
+struct Selected_Finger_Trail
 {
   /**
-   * 64 bit value of peer identity
+   * First friend in the trail to reach finger.
    */
-  uint64_t peer_id;
-  
+  struct FriendInfo friend;
+
   /**
-   * FIXME: think of a better name for both the struct and destination_type
-   * Type : MY_ID, FINGER, FINGER, Value 
+   * Identifier of this trail.
    */
-  enum current_destination_type type;
-  
+  struct GNUNET_HashCode trail_id;
+
   /**
-   * Pointer to original data structure linked to peer id.
+   * Total number of peers in this trail.
    */
-  void *data;
+  unsigned int trail_length;
 };
 
-
 /**
  * Task that sends FIND FINGER TRAIL requests. This task is started when we have
- * get our first friend. 
+ * get our first friend.
  */
 static GNUNET_SCHEDULER_TaskIdentifier find_finger_trail_task;
 
@@ -768,14 +844,14 @@ static GNUNET_SCHEDULER_TaskIdentifier find_finger_trail_task;
 static struct GNUNET_PeerIdentity my_identity;
 
 /**
- * Hash map of all the friends of a peer
+ * Peer map of all the friends of a peer
  */
 static struct GNUNET_CONTAINER_MultiPeerMap *friend_peermap;
 
 /**
- * Hash map of all the fingers of a peer
+ * Array of all the fingers. 
  */
-static struct GNUNET_CONTAINER_MultiPeerMap *finger_peermap;
+static struct FingerInfo finger_table [MAX_FINGERS];
 
 /**
  * Handle to CORE.
@@ -783,168 +859,14 @@ static struct GNUNET_CONTAINER_MultiPeerMap *finger_peermap;
 static struct GNUNET_CORE_Handle *core_api;
 
 /**
- * Finger map index for predecessor entry in finger peermap. 
- */
-#define PREDECESSOR_FINGER_ID 64
-
-/**
- * Maximum number of trails allowed to go through a friend.
- * FIXME: Better name, Random value at the moment, need to be adjusted to maintain a balance
- * between performance and Sybil tolerance. 
- */
-#define TRAIL_THROUGH_FRIEND_THRESHOLD 64
-
-/**
- * Possible number of different trails to reach to a finger. (Redundant routing) 
- */
-#define TRAIL_COUNT 2
-
-/**
- * The current finger index that we have want to find trail to.
+ * The current finger index that we have want to find trail to. We start the
+ * search with value = 0, i.e. successor  and then go to PREDCESSOR_FINGER_ID
+ * and decrement it. For any index 63 <= index < 0, if finger is same as successor,
+ * we reset this index to 0.
  */
 static unsigned int current_search_finger_index;
 
 
-/**
- * Iterate over trail and search your index location in the array. 
- * @param trail Trail which contains list of peers.
- * @param trail_length Number of peers in the trail.
- * @return Index in the array.
- *         #GNUNET_SYSERR, in case there is no entry which should not be the case ideally. 
- */
-static int
-search_my_index (const struct GNUNET_PeerIdentity *trail,
-                int trail_length)
-{
-  int i = 0;
-  
-  while (i < trail_length)
-  {
-    if (0 == GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &trail[i]))
-    {
-      return i;
-    }
-    i++;
-  }
-  return GNUNET_SYSERR;
-}
-
-/**
- * Compare two peer identities.
- * @param p1 Peer identity
- * @param p2 Peer identity
- * @return 1 if p1 > p2, -1 if p1 < p2 and 0 if p1 == p2. 
- */
-static int
-compare_peer_id (const void *p1, const void *p2)
-{
-  struct Sorting_List *p11;
-  struct Sorting_List *p22;
-  int ret;
-  p11 = GNUNET_malloc (sizeof (struct Sorting_List));
-  p22 = GNUNET_malloc (sizeof (struct Sorting_List));
-  p11 = (struct Sorting_List *)p1;
-  p22 = (struct Sorting_List *)p2;
-  ret = ( (p11->peer_id) > (p22->peer_id) ) ? 1 : 
-          ( (p11->peer_id) == (p22->peer_id) ) ? 0 : -1;
-  return ret;
-}
-
-
-/**
- * Return the predecessor of value in all_known_peers.
- * @param all_known_peers list of all the peers
- * @param value value we have to search in the all_known_peers.
- * @param size Total numbers of elements
- * @return Predecessor
- */
-static struct Sorting_List *
-find_closest_predecessor(struct Sorting_List *all_known_peers, uint64_t value,
-                         unsigned int size)
-{
-  int first;
-  int last;
-  int middle;
-  
-  first = 0;
-  last = size - 1;
-  middle = (first + last)/2;
-  
-  while(first <= last)
-  {
-    if(all_known_peers[middle].peer_id < value)
-    {
-      first = middle + 1; 
-    }
-    else if(all_known_peers[middle].peer_id == value)
-    {
-      if(middle == 0)
-      {
-        return &all_known_peers[size - 1];
-      }
-      else
-      {
-        return &all_known_peers[middle - 1];
-      }
-    }
-    else
-    {
-       last = middle - 1;
-    }
-  
-    middle = (first + last)/2;  
-  }
-  return NULL;
-}
-
-
-/**
- * Return the successor of value in all_known_peers.
- * @param all_known_peers list of all the peers
- * @param value value we have to search in the all_known_peers.
- * @param size Total numbers of elements
- * @return Successor
- */
-static struct Sorting_List *
-find_closest_successor(struct Sorting_List *all_known_peers, uint64_t value,
-                       unsigned int size)
-{
-  int first;
-  int last;
-  int middle;
-  
-  first = 0;
-  last = size - 1;
-  middle = (first + last)/2;
-  
-  while(first <= last)
-  {
-    if(all_known_peers[middle].peer_id < value)
-    {
-      first = middle + 1; 
-    }
-    else if(all_known_peers[middle].peer_id == value)
-    {
-      if(middle == (size -1))
-      {
-        return &all_known_peers[0];
-      }
-      else
-      {
-        return &all_known_peers[middle+1];
-      }
-    }
-    else
-    {
-       last = middle - 1;
-    }
-  
-    middle = (first + last)/2;  
-  }
-  return NULL;
-}
-
-
 /**
  * Called when core is ready to send a message we asked for
  * out to the destination.
@@ -962,13 +884,13 @@ core_transmit_notify (void *cls, size_t size, void *buf)
   struct P2PPendingMessage *pending;
   size_t off;
   size_t msize;
-  
+
   peer->th = NULL;
   while ((NULL != (pending = peer->head)) &&
          (0 == GNUNET_TIME_absolute_get_remaining (pending->timeout).rel_value_us))
   {
     peer->pending_count--;
-    GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);  
+    GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
     GNUNET_free (pending);
   }
   if (NULL == pending)
@@ -1012,7 +934,7 @@ core_transmit_notify (void *cls, size_t size, void *buf)
                                            &core_transmit_notify, peer);
     GNUNET_break (NULL != peer->th);
   }
+
   return off;
 }
 
@@ -1026,18 +948,17 @@ static void
 process_friend_queue (struct FriendInfo *peer)
 {
   struct P2PPendingMessage *pending;
-  
+
   if (NULL == (pending = peer->head))
     return;
   if (NULL != peer->th)
     return;
-  
+
   GNUNET_STATISTICS_update (GDS_stats,
                             gettext_noop
                             ("# Bytes of bandwidth requested from core"),
                             ntohs (pending->msg->size), GNUNET_NO);
-  
-  /* FIXME: Are we correctly initializing importance and pending. */
+
   peer->th =
       GNUNET_CORE_notify_transmit_ready (core_api, GNUNET_NO,
                                          pending->importance,
@@ -1050,60 +971,83 @@ process_friend_queue (struct FriendInfo *peer)
 
 
 /**
- * Construct a trail setup message and forward it to a friend. 
- * @param source_peer Peer which wants to set up the trail to one of its finger.
- * @param destination_finger Peer identity closest to this value will be 
- *                           @a source_peer's finger.
- * @param current_destination next destination corresponding to @a current_source,
- *                            can be either a finger or a friend of @a current_source. 
- * @param current_source Peer for which @a current_destination is its finger/friend.
- * @param target_friend Friend to which this message should be forwarded.
- * @param trail_length Numbers of peers in the trail found so far.
- * @param trail_peer_list Peers this request has traversed so far  
- * @param finger_map_index Index in finger peer map
+ * Return friend corresponding to peer.
+ * @param peer
+ * @return  Friend
+ */
+struct FriendInfo *
+GDS_NEIGHBOURS_get_friend (struct GNUNET_PeerIdentity peer)
+{
+  struct FriendInfo *friend;
+  GNUNET_assert (NULL != (friend = 
+          GNUNET_CONTAINER_multipeermap_get (friend_peermap, &peer)));
+  return friend;
+}
+
+
+/**
+ * Construct a trail setup message and forward it to target_friend
+ * @param source_peer Peer which wants to setup the trail
+ * @param ultimate_destination_finger_value Peer identity closest to this value 
+ *                                          will be finger to @a source_peer
+ * @param best_known_destination Best known destination (could be finger or friend)
+ *                               which should get this message.
+ * @param target_friend Friend to which message is forwarded now.
+ * @param trail_length Total number of peers in trail setup so far.
+ * @param trail_peer_list Trail setup so far
+ * @param is_predecessor Is source_peer looking for trail to a predecessor or not.
+ * @param trail_id Unique identifier for the trail we are trying to setup.
+ * @param intermediate_trail_id Trail id of intermediate trail to reach to 
+ *                              best_known_destination when its a finger. If not 
+ *                              used then set to 0.
  */
 void
-GDS_NEIGHBOURS_send_trail_setup (const struct GNUNET_PeerIdentity *source_peer,
-                                 uint64_t destination_finger,
-                                 struct GNUNET_PeerIdentity *current_destination,
-                                 struct GNUNET_PeerIdentity *current_source,
+GDS_NEIGHBOURS_send_trail_setup (struct GNUNET_PeerIdentity source_peer,
+                                 uint64_t ultimate_destination_finger_value,
+                                 struct GNUNET_PeerIdentity best_known_destination,
                                  struct FriendInfo *target_friend,
                                  unsigned int trail_length,
                                  const struct GNUNET_PeerIdentity *trail_peer_list,
-                                 unsigned int finger_map_index)
+                                 unsigned int is_predecessor,
+                                 struct GNUNET_HashCode trail_id,
+                                 struct GNUNET_HashCode *intermediate_trail_id)
 {
   struct P2PPendingMessage *pending;
   struct PeerTrailSetupMessage *tsm;
   struct GNUNET_PeerIdentity *peer_list;
   size_t msize;
-  
-  msize = sizeof (struct PeerTrailSetupMessage) + 
+
+  msize = sizeof (struct PeerTrailSetupMessage) +
           (trail_length * sizeof (struct GNUNET_PeerIdentity));
-  
+
   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
   {
     GNUNET_break (0);
     return;
   }
-  
+
   if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
-  {  
+  {
     GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
                                1, GNUNET_NO);
   }
-  
-  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize); 
+
+  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
   pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
-  tsm = (struct PeerTrailSetupMessage *) &pending[1]; 
+  tsm = (struct PeerTrailSetupMessage *) &pending[1];
   pending->msg = &tsm->header;
   tsm->header.size = htons (msize);
   tsm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP);
-  memcpy (&(tsm->destination_finger), &destination_finger, sizeof (uint64_t));
-  memcpy (&(tsm->source_peer), source_peer, sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&(tsm->current_destination), current_destination, sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&(tsm->current_source), current_source, sizeof (struct GNUNET_PeerIdentity));
-  tsm->trail_length = htonl (trail_length); 
-  tsm->finger_map_index = htonl (finger_map_index);
+  tsm->final_destination_finger_value = GNUNET_htonll (ultimate_destination_finger_value);
+  tsm->source_peer = source_peer;
+  tsm->best_known_destination = best_known_destination;
+  tsm->is_predecessor = htonl (is_predecessor);
+  tsm->trail_id = trail_id;
+  
+  if (NULL == intermediate_trail_id)
+    memset (&tsm->intermediate_trail_id, 0, sizeof (tsm->intermediate_trail_id));
+  else
+    tsm->intermediate_trail_id = *intermediate_trail_id;
   
   if (trail_length > 0)
   {
@@ -1118,54 +1062,62 @@ GDS_NEIGHBOURS_send_trail_setup (const struct GNUNET_PeerIdentity *source_peer,
 
 
 /**
- * Construct a trail setup result message and forward it to a friend. 
- * @param destination_peer Peer which will get the trail to one of its finger.
- * @param source_finger Peer to which the trail has been setup to.
+ * Construct a trail setup result message and forward it to target friend.
+ * @param querying_peer Peer which sent the trail setup request and should get
+ *                      the result back. 
+ * @param Finger Peer to which the trail has been setup to.
  * @param target_friend Friend to which this message should be forwarded.
  * @param trail_length Numbers of peers in the trail.
- * @param trail_peer_list Peers which are part of the trail from source to destination.
- * @param finger_map_index Index in finger peer map 
+ * @param trail_peer_list Peers which are part of the trail from q
+ *                        querying_peer to Finger, NOT including them. 
+ * @param is_predecessor Is @a Finger predecessor to @a querying_peer
+ * @param ultimate_destination_finger_value Value to which @a finger is the closest
+ *                                          peer. 
+ * @param trail_id Unique identifier of the trail.
  */
 void
-GDS_NEIGHBOURS_send_trail_setup_result (const struct GNUNET_PeerIdentity *destination_peer,
-                                        const struct GNUNET_PeerIdentity *source_finger,
+GDS_NEIGHBOURS_send_trail_setup_result (struct GNUNET_PeerIdentity querying_peer,
+                                        struct GNUNET_PeerIdentity finger,
                                         struct FriendInfo *target_friend,
                                         unsigned int trail_length,
                                         const struct GNUNET_PeerIdentity *trail_peer_list,
-                                        unsigned int finger_map_index)
+                                        unsigned int is_predecessor,
+                                        uint64_t ultimate_destination_finger_value,
+                                        struct GNUNET_HashCode trail_id)
 {
   struct P2PPendingMessage *pending;
   struct PeerTrailSetupResultMessage *tsrm;
   struct GNUNET_PeerIdentity *peer_list;
   size_t msize;
-  
-  msize = sizeof (struct PeerTrailSetupResultMessage) + 
+
+  msize = sizeof (struct PeerTrailSetupResultMessage) +
           (trail_length * sizeof (struct GNUNET_PeerIdentity));
-  
+
   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
   {
     GNUNET_break (0);
     return;
   }
-  
+
   if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
-  {  
+  {
     GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
                                1, GNUNET_NO);
   }
-  
-  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize); 
-  pending->importance = 0;    
+
+  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
+  pending->importance = 0;
   pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
-  tsrm = (struct PeerTrailSetupResultMessage *) &pending[1]; 
+  tsrm = (struct PeerTrailSetupResultMessage *) &pending[1];
   pending->msg = &tsrm->header;
   tsrm->header.size = htons (msize);
   tsrm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP_RESULT);
-  memcpy (&(tsrm->destination_peer), destination_peer, sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&(tsrm->finger_identity), source_finger, sizeof (struct GNUNET_PeerIdentity));
-  tsrm->trail_length = htonl (trail_length);
-  tsrm->finger_map_index = htonl (finger_map_index);
+  tsrm->querying_peer = querying_peer;
+  tsrm->finger_identity = finger;
+  tsrm->is_predecessor = htonl (is_predecessor);
+  tsrm->trail_id = trail_id;
+  tsrm->ulitmate_destination_finger_value = 
+          GNUNET_htonll (ultimate_destination_finger_value);
   peer_list = (struct GNUNET_PeerIdentity *) &tsrm[1];
   if (trail_length > 0)
   {
@@ -1179,119 +1131,188 @@ GDS_NEIGHBOURS_send_trail_setup_result (const struct GNUNET_PeerIdentity *destin
 
 
 /**
- * Construct a PeerVerifySuccessor message and send it to friend.
- * @param source_peer Peer which wants to verify its successor
- * @param successor Peer which is our current successor
- * @param target_friend Friend to which this message should be forwarded.
- * @param trail_peer_list Peer which are part of trail from source to destination
- * @param trail_length Number of peers in the trail list.
+ * Send trail rejection message to target friend
+ * @param source_peer Peer which is trying to setup the trail.
+ * @param ultimate_destination_finger_value Peer closest to this value will be 
+ *                                          @a source_peer's finger
+ * @param congested_peer Peer which sent this message as it is congested.
+ * @param is_predecessor Is source_peer looking for trail to a predecessor or not.
+ * @param trail_peer_list Trails seen so far in trail setup before getting rejected
+ *                        by congested_peer. This does not include @a source_peer
+ * @param trail_length Total number of peers in trail_peer_list, not including
+ *                     @a source_peer
+ * @param trail_id Unique identifier of this trail.
+ * @param congestion_timeout Duration given by congested peer as an estimate of
+ *                           how long it may remain congested.
  */
-void GDS_NEIGHBOURS_send_verify_successor(const struct GNUNET_PeerIdentity *source_peer,
-                                          const struct GNUNET_PeerIdentity *successor,
-                                          struct FriendInfo *target_friend,
-                                          const struct GNUNET_PeerIdentity *trail_peer_list,
-                                          unsigned int trail_length)
+void
+GDS_NEIGHBOURS_send_trail_rejection (struct GNUNET_PeerIdentity source_peer,
+                                     uint64_t ultimate_destination_finger_value,
+                                     struct GNUNET_PeerIdentity congested_peer,
+                                     unsigned int is_predecessor,
+                                     const struct GNUNET_PeerIdentity *trail_peer_list,
+                                     unsigned int trail_length,
+                                     struct GNUNET_HashCode trail_id,
+                                     struct FriendInfo *target_friend,
+                                     const struct GNUNET_TIME_Relative congestion_timeout)
 {
-  struct PeerVerifySuccessorMessage *vsm;
+  struct PeerTrailRejectionMessage *trm;
   struct P2PPendingMessage *pending;
   struct GNUNET_PeerIdentity *peer_list;
   size_t msize;
-  
-  msize = sizeof (struct PeerVerifySuccessorMessage) + 
+
+  msize = sizeof (struct PeerTrailRejectionMessage) +
           (trail_length * sizeof (struct GNUNET_PeerIdentity));
-  
+
   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
   {
     GNUNET_break (0);
     return;
   }
+
   if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
-  {  
+  {
     GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
                                1, GNUNET_NO);
   }
+
+  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
+  pending->importance = 0;
+  pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
+  trm = (struct PeerTrailRejectionMessage *)&pending[1];
+  pending->msg = &trm->header;
+  trm->header.size = htons (msize);
+  trm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP_REJECTION);
+  trm->source_peer = source_peer;
+  trm->congested_peer = congested_peer;
+  trm->congestion_time = congestion_timeout;
+  trm->is_predecessor = htonl (is_predecessor);
+  trm->trail_id = trail_id;
+  trm->ultimate_destination_finger_value = GNUNET_htonll (ultimate_destination_finger_value);
+
+  peer_list = (struct GNUNET_PeerIdentity *) &trm[1];
+  if (trail_length > 0)
+  {
+    memcpy (peer_list, trail_peer_list, trail_length * sizeof (struct GNUNET_PeerIdentity));
+  }
   
-  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize); 
+  /* Send the message to chosen friend. */
+  GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
+  target_friend->pending_count++;
+  process_friend_queue (target_friend);
+}
+
+
+/**
+ * Construct a verify successor message and forward it to target_friend.
+ * @param source_peer Peer which wants to verify its successor.
+ * @param successor Peer which is @a source_peer's current successor.
+ * @param trail_id Unique Identifier of trail from @a source_peer to @a successor,
+ *                 NOT including them. 
+ * @param trail List of peers which are part of trail to reach from @a source_peer
+ *              to @a successor, NOT including them. 
+ * @param trail_length Total number of peers in @a trail.
+ * @param target_friend Next friend to get this message. 
+ */
+void
+GDS_NEIGHBOURS_send_verify_successor_message (struct GNUNET_PeerIdentity source_peer,
+                                              struct GNUNET_PeerIdentity successor,
+                                              struct GNUNET_HashCode trail_id,
+                                              struct GNUNET_PeerIdentity *trail,
+                                              unsigned int trail_length,
+                                              struct FriendInfo *target_friend)
+{
+  struct PeerVerifySuccessorMessage *vsm;
+  struct P2PPendingMessage *pending;
+  struct GNUNET_PeerIdentity *peer_list;
+  size_t msize;
+
+  msize = sizeof (struct PeerVerifySuccessorMessage);
+  if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
+  {
+    GNUNET_break (0);
+    return;
+  }
+
+  if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
+  {
+    GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
+                               1, GNUNET_NO);
+  }
+
+  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
   pending->importance = 0;    /* FIXME */
   pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
   vsm = (struct PeerVerifySuccessorMessage *) &pending[1];
   pending->msg = &vsm->header;
   vsm->header.size = htons (msize);
   vsm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_VERIFY_SUCCESSOR);
-  memcpy (&(vsm->successor), successor, sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&(vsm->source_peer), source_peer, sizeof (struct GNUNET_PeerIdentity));
-  vsm->trail_length = htonl (trail_length);
+  vsm->source_peer = source_peer;
+  vsm->successor = successor;
+  vsm->trail_id = trail_id;
   
   if (trail_length > 0)
   {
     peer_list = (struct GNUNET_PeerIdentity *) &vsm[1];
-    memcpy (peer_list, trail_peer_list, trail_length * sizeof (struct GNUNET_PeerIdentity));
+    memcpy (peer_list, trail, trail_length * sizeof (struct GNUNET_PeerIdentity));
   }
-  
+
   /* Send the message to chosen friend. */
   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
   target_friend->pending_count++;
   process_friend_queue (target_friend);
-  
 }
 
 
 /**
- * Construct a PeerVerifySuccessorResult message and send it to friend.
- * @param destination_peer Peer which sent verify successor message
- * @param source_successor Peer to which verify successor message was sent.
- * @param my_predecessor source_successor's predecessor.
- * @param target_friend Friend to which this message should be forwarded.
- * @param trail_peer_list Peers which are part of trail from source to destination
- * @param trail_length Number of peers in the trail list.
+ * FIXME: In every function we pass target friend except for this one.
+ * so, either change everything or this one. also, should se just store
+ * the pointer to friend in routing table rather than gnunet_peeridentity.
+ * if yes then we should keep friend info in.h  andmake lot of changes. 
+ * Construct a trail teardown message and forward it to target friend. 
+ * @param trail_id Unique identifier of the trail.
+ * @param trail_direction Direction of trail.
+ * @param target_friend Friend to get this message.
  */
-void GDS_NEIGHBOURS_send_verify_successor_result (const struct GNUNET_PeerIdentity *destination_peer,
-                                                  const struct GNUNET_PeerIdentity *source_successor,
-                                                  const struct GNUNET_PeerIdentity *my_predecessor,
-                                                  struct FriendInfo *target_friend,
-                                                  const struct GNUNET_PeerIdentity *trail_peer_list,
-                                                  unsigned int trail_length)
+void
+GDS_NEIGHBOURS_send_trail_teardown (struct GNUNET_HashCode trail_id,
+                                    unsigned int trail_direction,
+                                    struct GNUNET_PeerIdentity *peer)
 {
-  struct PeerVerifySuccessorResultMessage *vsmr;
+  struct PeerTrailTearDownMessage *ttdm;
   struct P2PPendingMessage *pending;
-  struct GNUNET_PeerIdentity *peer_list;
+  struct FriendInfo *target_friend;
   size_t msize;
-  
-  msize = sizeof (struct PeerVerifySuccessorResultMessage) + 
-          (trail_length * sizeof(struct GNUNET_PeerIdentity));
-  
+
+  msize = sizeof (struct PeerTrailTearDownMessage);
+
   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
   {
     GNUNET_break (0);
     return;
   }
   
+  GNUNET_assert (NULL != (target_friend = 
+                GNUNET_CONTAINER_multipeermap_get (friend_peermap, peer)));
   
   if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
-  {  
+  {
     GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
                                1, GNUNET_NO);
   }
 
-  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize); 
+  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
   pending->importance = 0;    /* FIXME */
   pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
-  vsmr = (struct PeerVerifySuccessorResultMessage *) &pending[1];
-  pending->msg = &vsmr->header;
-  vsmr->header.size = htons (msize);
-  vsmr->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_VERIFY_SUCCESSOR_RESULT);
-  memcpy (&(vsmr->destination_peer), destination_peer, sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&(vsmr->source_successor), source_successor, sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&(vsmr->my_predecessor), my_predecessor, sizeof (struct GNUNET_PeerIdentity));
-  vsmr->trail_length = htonl (trail_length);  
-  if (trail_length > 0)
-  {
-    peer_list = (struct GNUNET_PeerIdentity *) &vsmr[1];
-    memcpy (peer_list, trail_peer_list, trail_length * sizeof (struct GNUNET_PeerIdentity));
-  }
+  ttdm = (struct PeerTrailTearDownMessage *) &pending[1];
+  pending->msg = &ttdm->header;
+  ttdm->header.size = htons (msize);
+  ttdm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_TEARDOWN);
+  ttdm->trail_id = trail_id;
+  ttdm->trail_direction = htonl (trail_direction);
+
+  /* Send the message to chosen friend. */
   
-   /* Send the message to chosen friend. */
   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
   target_friend->pending_count++;
   process_friend_queue (target_friend);
@@ -1299,119 +1320,134 @@ void GDS_NEIGHBOURS_send_verify_successor_result (const struct GNUNET_PeerIdenti
 
 
 /**
- * Construct a PeerNotifyNewSuccessor message and send it to friend.
- * @param source_peer Peer which is sending notify message to its new successor.
- * @param destination_peer Peer which is the new destination.
- * @param target_friend Next friend to pass this message to. 
- * @param peer_list List of peers in the trail to reach to destination_peer.
- * @param trail_length Total number of peers in peer list 
+ * Construct a verify successor result message and send it to target_friend
+ * @param querying_peer Peer which sent the verify successor message. 
+ * @param source_successor Current_successor of @a querying_peer. 
+ * @param current_predecessor Current predecessor of @a successor. Could be same
+ *                            or different from @a querying_peer.
+ * @param trail_id Unique identifier of the trail from @a querying_peer to 
+ *                 @a successor, NOT including them.
+ * @param trail List of peers which are part of trail from @a querying_peer to 
+ *                 @a successor, NOT including them.
+ * @param trail_length Total number of peers in @a trail
+ * @param trail_direction Direction in which we are sending the message. In this
+ *                        case we are sending result from @a successor to @a querying_peer.
+ * @param target_friend Next friend to get this message. 
  */
-void 
-GDS_NEIGHBOURS_send_notify_new_successor (const struct GNUNET_PeerIdentity *source_peer,
-                                          const struct GNUNET_PeerIdentity *destination_peer,
-                                          const struct GNUNET_PeerIdentity *old_successor,
-                                          struct FriendInfo *target_friend,
-                                          const struct GNUNET_PeerIdentity *trail_peer_list,
-                                          unsigned int trail_length)
+void
+GDS_NEIGHBOURS_send_verify_successor_result (struct GNUNET_PeerIdentity querying_peer,
+                                             struct GNUNET_PeerIdentity current_successor,
+                                             struct GNUNET_PeerIdentity probable_successor,
+                                             struct GNUNET_HashCode trail_id,
+                                             const struct GNUNET_PeerIdentity *trail,
+                                             unsigned int trail_length,
+                                             enum GDS_ROUTING_trail_direction trail_direction,
+                                             struct FriendInfo *target_friend)
 {
-  struct PeerNotifyNewSuccessorMessage *nsm;
+  struct PeerVerifySuccessorResultMessage *vsmr;
   struct P2PPendingMessage *pending;
   struct GNUNET_PeerIdentity *peer_list;
   size_t msize;
-  
-  msize = sizeof (struct PeerNotifyNewSuccessorMessage) + 
+
+  msize = sizeof (struct PeerVerifySuccessorResultMessage) +
           (trail_length * sizeof(struct GNUNET_PeerIdentity));
-  
+
   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
   {
     GNUNET_break (0);
     return;
   }
-  
+
   if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
-  {  
+  {
     GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
                                1, GNUNET_NO);
   }
-  
-  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize); 
+
+  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
   pending->importance = 0;    /* FIXME */
   pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
-  nsm = (struct PeerNotifyNewSuccessorMessage *) &pending[1];
-  pending->msg = &nsm->header;
-  nsm->header.size = htons (msize);
-  nsm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_NOTIFY_NEW_SUCCESSOR);
-  memcpy (&(nsm->source_peer), source_peer, sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&(nsm->destination_peer), destination_peer, sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&(nsm->old_successor), old_successor, sizeof (struct GNUNET_PeerIdentity));
-  nsm->trail_length = htonl (trail_length);
-
+  vsmr = (struct PeerVerifySuccessorResultMessage *) &pending[1];
+  pending->msg = &vsmr->header;
+  vsmr->header.size = htons (msize);
+  vsmr->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_VERIFY_SUCCESSOR_RESULT);
+  vsmr->querying_peer = querying_peer;
+  vsmr->current_successor = current_successor;
+  vsmr->probable_successor = probable_successor;
+  vsmr->trail_direction = htonl (trail_direction);
+  vsmr->trail_id = trail_id;
+  
   if (trail_length > 0)
   {
-    peer_list = (struct GNUNET_PeerIdentity *) &nsm[1];
-    memcpy (peer_list, trail_peer_list, trail_length * sizeof (struct GNUNET_PeerIdentity));
+    peer_list = (struct GNUNET_PeerIdentity *) &vsmr[1];
+    memcpy (peer_list, trail, trail_length * sizeof (struct GNUNET_PeerIdentity));
   }
+
    /* Send the message to chosen friend. */
   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
   target_friend->pending_count++;
   process_friend_queue (target_friend);
 }
 
+
 /**
- * Send a trail tear down message
- * @param source_peer Source of the trail.
- * @param destination_peer Destination of the trail. 
- * @param discarded_trail Discarded trail from source to destination. 
- * @param discarded_trail_length Total number of peers in trail_list. 
- * @pararm target_peer Next peer to forward this message to. 
- * @param new_first_friend The new first hop in the new trail from source to destination
- *                         peer.
+ * Construct a notify new successor message and send it to target_friend
+ * @param source_peer Peer which wants to notify to its new successor that it
+ *                    could be its predecessor. 
+ * @param successor New successor of @a source_peer
+ * @param successor_trail List of peers in Trail to reach from 
+ *                            @a source_peer to @a new_successor, NOT including 
+ *                            the endpoints. 
+ * @param successor_trail_length Total number of peers in @a new_successor_trail.
+ * @param successor_trail_id Unique identifier of @a new_successor_trail. 
+ * @param target_friend Next friend to get this message. 
  */
 void
-GDS_NEIGHBOURS_send_trail_teardown (const struct GNUNET_PeerIdentity *source_peer,
-                                    const struct GNUNET_PeerIdentity *destination_peer,
-                                    const struct GNUNET_PeerIdentity *discarded_trail,
-                                    unsigned int discarded_trail_length,
-                                    struct FriendInfo *target_friend,
-                                    const struct GNUNET_PeerIdentity *new_first_friend)
+GDS_NEIGHBOURS_send_notify_new_successor (struct GNUNET_PeerIdentity source_peer,
+                                          struct GNUNET_PeerIdentity successor,
+                                          const struct GNUNET_PeerIdentity *successor_trail,
+                                          unsigned int successor_trail_length,
+                                          struct GNUNET_HashCode succesor_trail_id,
+                                          struct FriendInfo *target_friend)
 {
+  struct PeerNotifyNewSuccessorMessage *nsm;
   struct P2PPendingMessage *pending;
-  struct PeerTrailTearDownMessage *ttdm;
   struct GNUNET_PeerIdentity *peer_list;
   size_t msize;
-  
-  msize = sizeof (struct PeerTrailTearDownMessage) + 
-          (discarded_trail_length * sizeof(struct GNUNET_PeerIdentity));
-  
+
+  msize = sizeof (struct PeerNotifyNewSuccessorMessage) +
+          (successor_trail_length * sizeof(struct GNUNET_PeerIdentity));
+
   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
   {
     GNUNET_break (0);
     return;
   }
-  
+
   if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
-  {  
+  {
     GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
                                1, GNUNET_NO);
   }
-  
-  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize); 
+
+  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
   pending->importance = 0;    /* FIXME */
   pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
-  ttdm = (struct PeerTrailTearDownMessage *) &pending[1];
-  pending->msg = &ttdm->header;
-  ttdm->header.size = htons (msize);
-  ttdm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_TEARDOWN);
-  memcpy (&(ttdm->source_peer), source_peer, sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&(ttdm->destination_peer), destination_peer, sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&(ttdm->new_first_friend),new_first_friend, sizeof (struct GNUNET_PeerIdentity));
-  ttdm->trail_length = htonl (discarded_trail_length);
+  nsm = (struct PeerNotifyNewSuccessorMessage *) &pending[1];
+  pending->msg = &nsm->header;
+  nsm->header.size = htons (msize);
+  nsm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_NOTIFY_NEW_SUCCESSOR);
+  nsm->new_successor = successor;
+  nsm->source_peer = source_peer;
+  nsm->trail_id = succesor_trail_id;
   
-  if (discarded_trail_length > 0)
+  if (successor_trail_length > 0)
   {
-    peer_list = (struct GNUNET_PeerIdentity *) &ttdm[1];
-    memcpy (peer_list, discarded_trail, discarded_trail_length * sizeof (struct GNUNET_PeerIdentity));
+    peer_list = (struct GNUNET_PeerIdentity *) &nsm[1];
+    memcpy (peer_list, successor_trail,
+            successor_trail_length * sizeof (struct GNUNET_PeerIdentity));
   }
+
    /* Send the message to chosen friend. */
   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
   target_friend->pending_count++;
@@ -1420,1248 +1456,649 @@ GDS_NEIGHBOURS_send_trail_teardown (const struct GNUNET_PeerIdentity *source_pee
 
 
 /**
- * 
- * @param source_peer
- * @param destination_peer
- * @param trail
- * @param trail_length
- * @param target_friend
+ * Construct an add_trail message and send it to target_friend
+ * @param source_peer Source of the trail.
+ * @param destination_peer Destination of the trail.
+ * @param trail_id Unique identifier of the trail from 
+ *                 @a source_peer to @a destination_peer, NOT including the endpoints.
+ * @param trail List of peers in Trail from @a source_peer to @a destination_peer,
+ *              NOT including the endpoints. 
+ * @param trail_length Total number of peers in @a trail.
+ * @param target_friend Next friend to get this message.
  */
 void
-GDS_NEIGHBOURS_send_add_trail_message (struct GNUNET_PeerIdentity *source_peer,
-                                       struct GNUNET_PeerIdentity *destination_peer,
-                                       struct GNUNET_PeerIdentity *trail,
-                                       unsigned int trail_length,
-                                       struct FriendInfo *target_friend)
+GDS_NEIGHBOURS_send_add_trail (struct GNUNET_PeerIdentity source_peer,
+                               struct GNUNET_PeerIdentity destination_peer,
+                               struct GNUNET_HashCode trail_id,
+                               const struct GNUNET_PeerIdentity *trail,
+                               unsigned int trail_length,
+                               struct FriendInfo *target_friend)
 {
-  struct P2PPendingMessage *pending;
   struct PeerAddTrailMessage *adm;
   struct GNUNET_PeerIdentity *peer_list;
+  struct P2PPendingMessage *pending;
   size_t msize;
-  
-  msize = sizeof (struct PeerAddTrailMessage) + 
+
+  msize = sizeof (struct PeerAddTrailMessage) +
           (trail_length * sizeof(struct GNUNET_PeerIdentity));
-  
+
   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
   {
     GNUNET_break (0);
     return;
   }
-  
+
   if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
-  {  
+  {
     GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
                                1, GNUNET_NO);
   }
-  
-  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize); 
+
+  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
   pending->importance = 0;    /* FIXME */
   pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
   adm = (struct PeerAddTrailMessage *) &pending[1];
   pending->msg = &adm->header;
   adm->header.size = htons (msize);
   adm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_ADD_TRAIL);
-  memcpy (&(adm->source_peer), source_peer, sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&(adm->destination_peer), destination_peer, sizeof (struct GNUNET_PeerIdentity));
-  adm->trail_length = htonl (trail_length);
-  
-  if (trail_length > 0)
-  {
-    peer_list = (struct GNUNET_PeerIdentity *)&adm[1];
-    memcpy (peer_list, trail, sizeof (struct GNUNET_PeerIdentity) * trail_length);
-  }
-  
+  adm->source_peer = source_peer;
+  adm->destination_peer = destination_peer;
+  adm->trail_id = trail_id;
+
+  peer_list = (struct GNUNET_PeerIdentity *)&adm[1];
+  memcpy (peer_list, trail, sizeof (struct GNUNET_PeerIdentity) * trail_length);
+
   /* Send the message to chosen friend. */
   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
   target_friend->pending_count++;
   process_friend_queue (target_friend);
+
 }
 
 
 /**
- * FIXME: CONGESTION: check the code once basic code is all correct. s
- * FIXME: call GNUNET_CONTAINER_multipeermap_iterator_destroy (iter);
- * In case the friend chosen in select_random_friend() is congested or
- * has crossed trail_threshold, then get next friend which is not congested or 
- * has not crossed trail threshold from friend peermap. 
- * @param current_index Index in finger peermap chosen randomly
- * @param friend_peermap_size Total number of entries in friend peermap.
- * @param count Total number of time this function has been called, in case
- *              count == sizeof(friend_peermap) - 1, it means none of the friends are free. 
- * @return Friend Friend found.
- *         NULL in case all the friends are congested or have crossed trail threshold.
+ * Construct a trail compression message and send it to target_friend.
+ * @param source_peer Source of the trail.
+ * @param trail_id Unique identifier of trail.
+ * @param first_friend First hop in compressed trail to reach from source to finger
+ * @param target_friend Next friend to get this message.
  */
-static struct FriendInfo *
-get_next_friend (unsigned int current_index, 
-                 unsigned int friend_peermap_size,
-                 unsigned int count)
+void
+GDS_NEIGHBOURS_send_trail_compression (struct GNUNET_PeerIdentity source_peer,
+                                       struct GNUNET_HashCode trail_id,
+                                       struct GNUNET_PeerIdentity first_friend,
+                                       struct FriendInfo *target_friend)
 {
-  struct GNUNET_CONTAINER_MultiPeerMapIterator *iter;
-  struct GNUNET_PeerIdentity key_ret;
-  struct FriendInfo *friend;
-  int j = 0;
-  
-  current_index = (current_index + 1) % friend_peermap_size;
-  iter = GNUNET_CONTAINER_multipeermap_iterator_create (friend_peermap);
-  while(j < (current_index))
+  struct P2PPendingMessage *pending;
+  struct PeerTrailCompressionMessage *tcm;
+  size_t msize;
+
+  msize = sizeof (struct PeerTrailCompressionMessage);
+
+  if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
   {
-    if(GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next (iter,NULL,NULL))
-    {
-      j++;
-    }
-    else 
-      return NULL;
-  }  
+    GNUNET_break (0);
+    return;
+  }
 
-  if(GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next (iter,&key_ret,(const void **)&friend))
+  if (target_friend->pending_count >= MAXIMUM_PENDING_PER_FRIEND)
   {
-    if ((friend->trails_count > TRAIL_THROUGH_FRIEND_THRESHOLD) ||
-        (0 != GNUNET_TIME_absolute_get_remaining (friend->congestion_duration).rel_value_us))
-    {
-      count++;
-      if (count == (friend_peermap_size -1))
-        return NULL;
-      else
-        return get_next_friend (j,friend_peermap_size,count);
-    }
-    return friend;
+    GNUNET_STATISTICS_update (GDS_stats,
+                              gettext_noop ("# P2P messages dropped due to full queue"),
+                                                     1, GNUNET_NO);
   }
-  else
-    return NULL;
-}
 
+  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
+  pending->importance = 0;    /* FIXME */
+  pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
+  tcm = (struct PeerTrailCompressionMessage *) &pending[1];
+  pending->msg = &tcm->header;
+  tcm->header.size = htons (msize);
+  tcm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_COMPRESSION);
+  tcm->source_peer = source_peer;
+  tcm->new_first_friend = first_friend;
+  tcm->trail_id = trail_id;
 
-/** 
- * FIXME: CONGESTION: check the code once basic code is all correct. 
- * FIXME: call GNUNET_CONTAINER_multipeermap_iterator_destroy (iter);
- * Randomly choose one of your friends from the friends_peer map
- * @return Friend Randomly chosen friend. 
- *         NULL in case friend peermap is empty, or all the friends are either
- *              congested or have crossed trail threshold. 
- */
-static struct FriendInfo *
-select_random_friend ()
-{  
-  unsigned int current_size;
-  unsigned int *index; 
-  unsigned int j = 0;
-  struct GNUNET_CONTAINER_MultiPeerMapIterator *iter;
-  struct GNUNET_PeerIdentity key_ret;
-  struct FriendInfo *friend;
-  
-  current_size = GNUNET_CONTAINER_multipeermap_size (friend_peermap);
-  if (0 == current_size)
-    return NULL;
-  
-  index = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, current_size);
-  iter = GNUNET_CONTAINER_multipeermap_iterator_create (friend_peermap);
-  while(j < (*index))
-  {
-    if(GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next (iter,NULL,NULL))
-    {
-      j++;
-    }
-    else 
-    {
-      return NULL;
-    }
-  }  
+  GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
+  target_friend->pending_count++;
+  process_friend_queue (target_friend);
 
-  if(GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next (iter,&key_ret,(const void **)&friend))
-  {
-    if ((TRAIL_THROUGH_FRIEND_THRESHOLD == friend->trails_count) ||
-        (0 != GNUNET_TIME_absolute_get_remaining (friend->congestion_duration).rel_value_us))
-    {
-      return get_next_friend (*index, current_size, 1);
-    } 
-    return friend;
-  }
-  else
-    return NULL;
 }
 
 
 /**
- * Compute finger_identity to which we want to setup the trail
- * @return finger_identity 
+ * Search my location in trail.
+ * @param trail List of peers
+ * @return my_index if found
+ *         -1 if no entry found.
  */
-static uint64_t 
-compute_finger_identity()
+static int
+search_my_index (const struct GNUNET_PeerIdentity *trail,
+                 int trail_length)
 {
-  uint64_t my_id64 ;
+  int i;
 
-  memcpy (&my_id64, &my_identity, sizeof (uint64_t));
-  my_id64 = GNUNET_ntohll (my_id64);
-  return (my_id64 + (unsigned long) pow (2, current_search_finger_index));
-}
+  for (i = 0; i < trail_length; i++)
+  {
+    if (0 == GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &trail[i]))
+      return i;
+  }
 
+  return -1;
+}
 
 /**
- * Compute immediate predecessor identity in the network.
- * @return peer identity of immediate predecessor.
+ * Check if the friend is congested or have reached maximum number of trails
+ * it can be part of of. 
+ * @param friend Friend to be chechked.
+ * @return #GNUNET_YES if friend is not congested or have not crossed threshold.
+ *         #GNUNET_NO if friend is either congested or have crossed threshold 
  */
-static uint64_t 
-compute_predecessor_identity()
+static int
+is_friend_congested (struct FriendInfo *friend)
 {
-  uint64_t my_id64;
-
-  memcpy (&my_id64, &my_identity, sizeof (uint64_t));
-  my_id64 = GNUNET_ntohll (my_id64);
-  return (my_id64 -1);
+  if ((friend->trails_count == TRAILS_THROUGH_FRIEND_THRESHOLD)||
+      ((0 != GNUNET_TIME_absolute_get_remaining
+             (friend->congestion_timestamp).rel_value_us)))
+    return GNUNET_YES;
+  else
+    return GNUNET_NO;
 }
 
 
 /**
- * Ping your successor to verify if it is still your successor or not. 
+ * FIXME: here we should also check if iterator is null or not. It can be NULL
+ * only if we insert randomly at locations. But as we are using trails_count
+ * as the parameter, it should not happen.
+ * Iterate over the list of all the trails of a finger. In case the first
+ * friend to reach the finger has reached trail threshold or is congested,
+ * then don't select it. In case there multiple available good trails to reach
+ * to Finger, choose the one with shortest trail length.
+ * Note: We use length as parameter. But we can use any other suitable parameter
+ * also. 
+ * @param finger Finger
+ * @return struct Selected_Finger_Trail which contains the first friend , trail id
+ * and trail length. NULL in case none of the trails are free.
  */
-static void
-send_verify_successor_message()
+static struct Selected_Finger_Trail *
+select_finger_trail (struct FingerInfo *finger)
 {
-  struct GNUNET_CONTAINER_MultiPeerMapIterator *finger_iter;
-  struct GNUNET_PeerIdentity key_ret;
-  struct FriendInfo *target_friend;
-  struct GNUNET_PeerIdentity next_hop;
-  struct GNUNET_PeerIdentity *peer_list;
-  struct FingerInfo *finger;
-  unsigned int finger_index;
-  int flag = 0;
+  struct FriendInfo *friend;
+  struct Trail *iterator;
+  struct Selected_Finger_Trail *finger_trail;
+  unsigned int i;
+
+  finger_trail = GNUNET_new (struct Selected_Finger_Trail);
   
-  /* Find the successor from the finger peermap.*/
-  finger_iter = GNUNET_CONTAINER_multipeermap_iterator_create (finger_peermap);  
-  for (finger_index = 0; finger_index < GNUNET_CONTAINER_multipeermap_size (finger_peermap); finger_index++)
+  for (i = 0; i < finger->trails_count; i++)
   {
-    if(GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next (finger_iter, &key_ret,
-                                                                 (const void **)&finger)) 
+    iterator = &finger->trail_list[i];
+    friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                                &iterator->trail_head->peer);
+    if (GNUNET_YES == is_friend_congested (friend))
+      continue;
+   
+    /* Check if the trail length of this trail is least seen so far. If yes then
+     set finger_trail to this trail.*/
+    if (finger_trail->trail_length > iterator->trail_length)
     {
-      if (0 == finger->finger_map_index)
-      {
-        flag = 1;
-        break;
-      }
+      finger_trail->friend = *friend;
+      finger_trail->trail_id = iterator->trail_id;
+      finger_trail->trail_length = iterator->trail_length;
     }
   }
-  GNUNET_CONTAINER_multipeermap_iterator_destroy (finger_iter);
-  
-  /* Either you don't have a successor or you are your own successor, then don't
-   send a successor message. */
-  if(( flag == 0) ||
-    (0 == GNUNET_CRYPTO_cmp_peer_identity(&my_identity, &(finger->finger_identity))))
-  {
-    return;
-  }
 
-  if (finger->first_trail_length > 0)
-  {
-    struct TrailPeerList *iterate;
-    int i = 0;
-    peer_list = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity) * finger->first_trail_length);
-    iterate = finger->first_trail_head;
-    
-    while ( i < (finger->first_trail_length))
-    {     
-      memcpy (&peer_list[i], &(iterate->peer), sizeof (struct GNUNET_PeerIdentity));
-      iterate = iterate->next;
-      i++;
-    }
-    memcpy (&next_hop, &peer_list[0], sizeof (struct GNUNET_PeerIdentity));
-    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop);
-  }
-  else
-  {
-    /* If trail length = 0, then our successor is our friend. */
-    peer_list = NULL;
-    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
-                                                      &(finger->finger_identity));
-  }
-   
-  GDS_NEIGHBOURS_send_verify_successor (&my_identity,
-                                        &(finger->finger_identity),
-                                        target_friend,
-                                        peer_list,
-                                        finger->first_trail_length);  
+  /* No trail found. */  
+  if (i == finger->trails_count)
+    finger_trail = NULL;
+  
+  return finger_trail;
 }
 
 
 /**
- * Choose a random friend and start looking for the trail to reach to 
- * finger identity through this random friend. 
- *
- * @param cls closure for this task
- * @param tc the context under which the task is running
+ * FIXME; not handling the wrap around logic correctly. 
+ * Select closest finger to value.
+ * @param peer1 First peer
+ * @param peer2 Second peer
+ * @param value Value to be compare
+ * @return Closest peer
  */
-static void
-send_find_finger_trail_message (void *cls,
-                                const struct GNUNET_SCHEDULER_TaskContext *tc)
+static struct GNUNET_PeerIdentity *
+select_closest_finger (struct GNUNET_PeerIdentity *peer1,
+                       struct GNUNET_PeerIdentity *peer2,
+                       uint64_t value)
 {
-  struct FriendInfo *target_friend;
-  struct GNUNET_TIME_Relative next_send_time;
-  uint64_t finger_identity;
-  unsigned int finger_map_index;
-  
-  next_send_time.rel_value_us =
-      DHT_FIND_FINGER_TRAIL_INTERVAL.rel_value_us +
-      GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
-                                DHT_FIND_FINGER_TRAIL_INTERVAL.rel_value_us);
-  find_finger_trail_task =
-      GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_finger_trail_message,
-                                    NULL);
+  uint64_t peer1_value;
+  uint64_t peer2_value;
   
-  target_friend = select_random_friend (); 
-  if (NULL == target_friend) 
+  memcpy (&peer1_value, peer1, sizeof (uint64_t));
+  memcpy (&peer2_value, peer2, sizeof (uint64_t));
+  if (peer1_value == value)
   {
-    return;
+    return peer1;
   }
   
-  if (PREDECESSOR_FINGER_ID == current_search_finger_index)
+  if (peer2_value == value)
   {
-    finger_identity = compute_predecessor_identity();  
+    return peer2;
   }
-  else
+   
+  if (peer2_value < peer1_value)
   {
-    finger_identity = compute_finger_identity();
-  }
-    
-  finger_map_index = current_search_finger_index;
-  GDS_NEIGHBOURS_send_trail_setup (&my_identity, finger_identity, &(target_friend->id),
-                                   &my_identity, target_friend, 0, NULL, finger_map_index);
-}
-
-
-/**
- * Scan the trail to check if any of my own friend is part of trail. If yes
- * then shortcut the trail, send a trail teardown for the discarded trail,
- * update trail list and trail_length. 
- * @param trail[Out] Current trail to reach to @a finger, will be updated
- *                          in case we compress the trail. 
- * @param trail_length[Out] Number of peers in @a finger_trail, will be updated
- *                          in case we compress the trail. 
- * @param finger Finger identity 
- */
-static void
-scan_and_compress_trail (struct GNUNET_PeerIdentity *trail,
-                         unsigned int *trail_length,
-                         const struct GNUNET_PeerIdentity *finger)
-{
-  int i;
-  struct FriendInfo *target_friend;
+    if ((peer2_value < value) && (value < peer1_value))
+    {
+      return peer1;
+    }
+    else if (((peer1_value < value) && (value < PEER_IDENTITES_WRAP_AROUND)) ||
+             ((0 < value) && (value < peer2_value)))
+    {
+      return peer2;
+    }
+  }  
    
-  if (0 == GNUNET_CRYPTO_cmp_peer_identity (&my_identity,finger))
-  {
-    /* Here you don't send a trail teardown as no one added this in their
-     routing table. */
-    *trail_length = 0;
-    trail = NULL;
-    return;    
-  }
-  if (GNUNET_CONTAINER_multipeermap_get (friend_peermap, finger))
-  {
-    int discarded_trail_length = *trail_length;
-    target_friend = GNUNET_CONTAINER_multipeermap_get(friend_peermap, &trail[0]);
-    GDS_NEIGHBOURS_send_trail_teardown (&my_identity, finger, trail,
-                                        discarded_trail_length, target_friend, finger);
-    *trail_length = 0;
-    trail = NULL;
-    return;
-  }
-  i = *trail_length - 1;
-
-  while (i > 1)
+  if (peer1_value < peer2_value)
   {
-    if (NULL == GNUNET_CONTAINER_multipeermap_get (friend_peermap, &trail[i]))
+    if ((peer1_value < value) && (value < peer2_value))
     {
-      /* This element of trail is not my friend. */
-      i--;
+      return peer2;
     }
-    else
+    else if (((peer2_value < value) && (value < PEER_IDENTITES_WRAP_AROUND)) ||
+             ((0 < value) && (value < peer1_value)))
     {
-      /* A --> B(friend 1) --> C(friend 2)--> D ---> E, then we can rewrite the trail as
-       * C --> D --> E,
-       * Now, we should remove the entry from A's routing table, B's routing table
-       * and update the entry in C's routing table. Rest everything will be same.
-       * C's routing table should have source peer as the prev.hop. 
-       */
-      struct GNUNET_PeerIdentity *discarded_trail;
-      struct FriendInfo *target_friend;
-      int discarded_trail_length;
-      int j = 0;
-
-      discarded_trail_length = i - 1;
-      discarded_trail = GNUNET_malloc (discarded_trail_length * sizeof (struct GNUNET_PeerIdentity));
-      memcpy (discarded_trail, trail, discarded_trail_length * sizeof (struct GNUNET_PeerIdentity));
-      target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &trail[0]);
-      GDS_NEIGHBOURS_send_trail_teardown (&my_identity, finger, discarded_trail,
-                                         discarded_trail_length, target_friend,
-                                         &trail[i]);
-     
-      /* Copy the trail from index i to index trail_length -1 and change
-       trail length and return */
-      while (i < *trail_length)
-      {
-        memcpy (&trail[j], &trail[i], sizeof(struct GNUNET_PeerIdentity));
-        j++;
-        i++;
-      }
-      *trail_length = j+1;
-      return;
+      return peer1;
     }
   }
-  return;
+  return NULL;
 }
 
 
-/** 
- * FIXME: Adapt the code for List of trails. 
- * Free finger and its trail.  
- * @param finger Finger to be freed.
+/**
+ * FIMXE: COMPLETE THE LOGIC.
+ * my_id = 0
+ * finger = 5
+ * key = 3
+ * [0,5) â†’ my_id
+ * [5,0) â†’ finger
+ *
+ * 0 <= key < 5, so my_id 0 is the predecessor. 
+ * peer1 != peer2 ever.
+ * Select closest predecessor to value.
+ * @param peer1 First peer
+ * @param peer2 Second peer
+ * @param value Value to be compare
+ * @return Closest peer
  */
-static void
-free_finger (struct FingerInfo *finger)
+static struct GNUNET_PeerIdentity *
+select_closest_predecessor (struct GNUNET_PeerIdentity *peer1,
+                            struct GNUNET_PeerIdentity *peer2,
+                            uint64_t value)
 {
-  struct TrailPeerList *peer;
-
-  if(finger->first_trail_head != NULL)
+  uint64_t peer1_value;
+  uint64_t peer2_value;
+  
+  memcpy (&peer1_value, peer1, sizeof (uint64_t));
+  memcpy (&peer2_value, peer2, sizeof (uint64_t));
+  
+  if (peer1_value == value)
+    return peer1;
+  
+  if (peer2_value == value)
+    return peer2;
+  
+  if (peer1_value < peer2_value)
   {
-    while (NULL != (peer = finger->first_trail_head))
-    {
-      GNUNET_CONTAINER_DLL_remove (finger->first_trail_head, finger->first_trail_tail, peer);
-      GNUNET_free (peer);
-    }
+    if ((peer1_value < value) && (value < peer2_value))
+      return peer1;
+    else if (((peer2_value < value) && (value < PEER_IDENTITES_WRAP_AROUND)) ||
+             ((PEER_IDENTITES_WRAP_AROUND > value) && (value < peer1_value)))
+      return peer2;
   }
   
-  if (finger->second_trail_head != NULL)
+  if (peer2_value < peer1_value)
   {
-    while (NULL != (peer = finger->second_trail_head))
-    {
-      GNUNET_CONTAINER_DLL_remove (finger->second_trail_head, finger->second_trail_tail, peer);
-      GNUNET_free (peer);
-    }
-    GNUNET_free (finger);
+    if ((peer2_value < value) && (value < peer1_value))
+      return peer2;
+    else if (((peer1_value < value) && (value < PEER_IDENTITES_WRAP_AROUND)) ||
+             ((PEER_IDENTITES_WRAP_AROUND > value) && (value < peer2_value)))
+      return peer1;
   }
+  return NULL;
 }
 
 
+/* FIXME: select closest peer w.r.t. value. [finger->friend_id, current_successor->id)
+     and [current_successor->id, finger->friend_id). Check in which range value lies.
+     Also, check for wrap around. But this will give you the immediate predecessor
+     For example. if we have 0,1,6 and I am 0 and one of my finger is 6. Then
+     for 1, we will have ranges like [0,6) and [6,0) 1 lies in range from [0,6)
+     but successor is 6 not 0 as 6 is > than 1. If you are the closest one, 
+     then set the values
+     in current_successor. Want to write a generic code so that it is used in 
+     * finger_table_add also while choosing the closest one among new and existing
+     * one. */
+/**
+ * my_id = 0
+ * finger = 5
+ * key = 3
+ * [0,5) â†’ my_id
+ * [5,0) â†’ finger
+
+ * 0 <= key < 5, so key should go to 5. 
+
+ */
 /**
- * FIXME: First check if both the trails are present if yes then send it
- * for both of them. Currently sending it only for one trail.
- * Send a trail teardown message for the trail of removed finger from the finger
- * peermap. 
- * @param existing_finger Finger to removed from the finger peermap.
+ * Select the closest peer among two peers (which should not be same)
+ * with respect to value and finger_table_index
+ * @param peer1 First peer
+ * @param peer2 Second peer
+ * @param value Value relative to which we find the closest
+ * @param finger_table_index Index in finger map. If equal to PREDECESSOR_FINGER_ID,
+ *                         then we use different logic than other
+ *                         finger_table_index
+ * @return Closest peer among two peers.
  */
-static
-void send_trail_teardown (struct FingerInfo *removed_finger)
+static struct GNUNET_PeerIdentity *
+select_closest_peer (struct GNUNET_PeerIdentity *peer1,
+                     struct GNUNET_PeerIdentity *peer2,
+                     uint64_t value,
+                     unsigned int finger_table_index)
 {
- struct GNUNET_PeerIdentity *peer_list; 
- struct FriendInfo *friend; 
- struct TrailPeerList *finger_trail;
- int removed_finger_trail_length = removed_finger->first_trail_length;
- int i = 0;
+  struct GNUNET_PeerIdentity *closest_peer;
+  /* FIXME: select closest peer w.r.t. value. [friend_id, current_successor->id)
+     and [current_successor->id, friend_id). Check in which range value lies.
+     Also, check for wrap around. Set the value of current_successor accordingly.*/
+  if (PREDECESSOR_FINGER_ID == finger_table_index)
+    closest_peer = select_closest_predecessor (peer1, peer2, value);
+  else
+    closest_peer = select_closest_finger (peer1, peer2, value);
 
- if (removed_finger->first_trail_length == 0)
-    return;
- finger_trail = removed_finger->first_trail_head;
- friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &(finger_trail->peer)); 
- peer_list = GNUNET_malloc ( removed_finger_trail_length * sizeof (struct GNUNET_PeerIdentity));
- while (i < removed_finger->first_trail_length)
- {
-   memcpy (&peer_list[i], &(finger_trail->peer), sizeof (struct GNUNET_PeerIdentity));
-   finger_trail = finger_trail->next;
-   i++;
- }
-
- GDS_NEIGHBOURS_send_trail_teardown (&my_identity, &(removed_finger->finger_identity),
-                                     peer_list, removed_finger_trail_length, friend,
-                                     &(removed_finger->finger_identity)); 
+  return closest_peer;
 }
 
 
 /**
- * FIXME: How do we understand which is the correct trail head? 
- * Add a new trail to reach an existing finger in finger peermap and increment
- * the count of number of trails to reach to this finger. 
- * @param existing_finger Finger 
- * @param trail New trail to be added
- * @param trail_length Total number of peers in the trail. 
+ * FIXME: better names and more refactoring. 
+ * Compare FINGER entry with current successor. If finger's first friend of all
+ * its trail is not congested and  has not crossed trail threshold, then check 
+ * if finger peer identity is closer to final_destination_finger_value than
+ * current_successor. If yes then update current_successor. 
+ * @param current_successor[in/out]
+ * @return 
  */
-static
-void add_new_trail (struct FingerInfo *existing_finger, 
-                    struct GNUNET_PeerIdentity *trail,
-                    unsigned int trail_length)
+static struct Closest_Peer *
+compare_finger_and_current_successor (struct Closest_Peer *current_closest_peer)
 {
+  struct FingerInfo *finger;
+  struct FriendInfo *friend;
+  struct GNUNET_PeerIdentity *closest_peer;
   int i;
-  i = 0;
-  /* FIXME: Here you need to understand which trail is there and which not. 
-   In case first_trail_head != NULL, then that trail is present 
-   so you should add the second one. Need to verify this logic. */    
-  if (existing_finger->first_trail_head != NULL)
+  
+  for (i = 0; i < MAX_FINGERS; i++)
   {
-    while (i < trail_length)
-    {
-      struct TrailPeerList *element;
-      element = GNUNET_malloc (sizeof (struct TrailPeerList));
-      element->next = NULL;
-      element->prev = NULL;
+    struct Selected_Finger_Trail *finger_trail;
+    finger = &finger_table[i];
     
-      memcpy (&(element->peer), &trail[i], sizeof(struct GNUNET_PeerIdentity));
-      GNUNET_CONTAINER_DLL_insert_tail(existing_finger->second_trail_head, existing_finger->second_trail_tail, element);
-      i++;
-    }
-  }
-  else if (existing_finger->second_trail_head != NULL)
-  {
-    while (i < trail_length)
-    {
-      struct TrailPeerList *element;
-      element = GNUNET_malloc (sizeof (struct TrailPeerList));
-      element->next = NULL;
-      element->prev = NULL;
+    if (GNUNET_NO == finger->is_present)
+      continue;
     
-      memcpy (&(element->peer), &trail[i], sizeof(struct GNUNET_PeerIdentity));
-      GNUNET_CONTAINER_DLL_insert_tail(existing_finger->first_trail_head, existing_finger->first_trail_tail, element);
-      i++;
-    }
-  }  
-  existing_finger->trail_count++;
-}
-
-
-/**
- * In case there are already maximum number of possible trail to reach to a finger,
- * then check if the new trail's length is lesser than any of the existing trails.
- * If yes then replace that old trail by new trail.
- * Note: Here we are taking length as a parameter to choose the best possible trail,
- * but there could be other parameters also like - 1. duration of existence of a
- * trail - older the better. 2. if the new trail is completely disjoint than the 
- * other trails, then may be choosing it is better. 
- * @param existing_finger
- * @param trail
- * @param trail_length
- * @return #GNUNET_YES 
- *         #GNUNET_NO
- */
-static 
-void select_and_replace_trail (struct FingerInfo *existing_finger, 
-                               struct GNUNET_PeerIdentity *new_trail,
-                               unsigned int new_trail_length)
-{
-  if (existing_finger->first_trail_length == existing_finger->second_trail_length)
-  {
-    if (new_trail_length < existing_finger->first_trail_length)
+    /* If my identity is same as current closest peer then don't consider me*/
+    if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger->finger_identity,
+                                              &current_closest_peer->best_known_destination))
+      continue;
+    
+    /* If I am my own finger, then ignore this finger. */
+    if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger->finger_identity,
+                                              &my_identity))
+      continue;
+    
+    /* If finger is friend. */
+    if (NULL != (friend = GNUNET_CONTAINER_multipeermap_get 
+                (friend_peermap, &finger->finger_identity)))
     {
-      /* Randomly choose one of the trail. FIXME:currently I am just replacing the
-       first trail.*/
-      struct TrailPeerList *peer;
-      int i = 0;
-        
-      while (NULL != (peer = existing_finger->first_trail_head))
-      {
-        GNUNET_CONTAINER_DLL_remove (existing_finger->first_trail_head, existing_finger->first_trail_tail, peer);
-        GNUNET_free (peer);
-      } 
-        
-      while (i < new_trail_length)
+      if (GNUNET_YES == is_friend_congested (friend))
+        continue;
+      
+       /* If not congested then compare it with current_successor. */
+      if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger->finger_identity,
+                                                 &current_closest_peer->best_known_destination))
+        continue;
+      
+      closest_peer = select_closest_peer (&finger->finger_identity, 
+                                          &current_closest_peer->best_known_destination,
+                                          current_closest_peer->destination_finger_value,
+                                          current_closest_peer->is_predecessor);
+      if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger->finger_identity,
+                                                closest_peer))
       {
-        struct TrailPeerList *element;
-        element = GNUNET_malloc (sizeof (struct TrailPeerList));
-        element->next = NULL;
-        element->prev = NULL;
-    
-        memcpy (&(element->peer), &new_trail[i], sizeof(struct GNUNET_PeerIdentity));
-        GNUNET_CONTAINER_DLL_insert_tail(existing_finger->second_trail_head, existing_finger->second_trail_tail, element);
-        i++;
+        current_closest_peer->best_known_destination = finger->finger_identity;
+        current_closest_peer->next_hop = finger->finger_identity;
       }
+      continue;
     }
-  }
-  else if ((new_trail_length < existing_finger->second_trail_length) && 
-          (existing_finger->second_trail_length < existing_finger->first_trail_length))
-  {
-    /* Replace the first trail by the new trail. */
-    struct TrailPeerList *peer;
-    int i = 0;
-        
-    while (NULL != (peer = existing_finger->first_trail_head))
-    {
-      GNUNET_CONTAINER_DLL_remove (existing_finger->first_trail_head, existing_finger->first_trail_tail, peer);
-      GNUNET_free (peer);
-    } 
-        
-    while (i < new_trail_length)
-    {
-      struct TrailPeerList *element;
-      element = GNUNET_malloc (sizeof (struct TrailPeerList));
-      element->next = NULL;
-      element->prev = NULL;
     
-      memcpy (&(element->peer), &new_trail[i], sizeof(struct GNUNET_PeerIdentity));
-      GNUNET_CONTAINER_DLL_insert_tail(existing_finger->second_trail_head, existing_finger->second_trail_tail, element);
-      i++;
-    }
-  }
-  else if ( (new_trail_length < existing_finger->first_trail_length) &&
-           (existing_finger->first_trail_length < existing_finger->second_trail_length))
-  {
-    /* Replace the second trail by the new trail. */
-    struct TrailPeerList *peer;
-    int i = 0;
-        
-    while (NULL != (peer = existing_finger->second_trail_head))
-    {
-      GNUNET_CONTAINER_DLL_remove (existing_finger->second_trail_head, existing_finger->second_trail_tail, peer);
-      GNUNET_free (peer);
-    }
-        
-    while (i < new_trail_length)
-    {
-      struct TrailPeerList *element;
-      element = GNUNET_malloc (sizeof (struct TrailPeerList));
-      element->next = NULL;
-      element->prev = NULL;
+    /* Choose one of the trail to reach to finger. */
+    finger_trail = select_finger_trail (finger);
+    
+    /* In case no trail found, ignore this finger. */
+    if (NULL == finger_trail)
+      continue;
     
-      memcpy (&(element->peer), &new_trail[i], sizeof(struct GNUNET_PeerIdentity));
-      GNUNET_CONTAINER_DLL_insert_tail(existing_finger->second_trail_head, existing_finger->second_trail_tail, element);
-      i++;
+     closest_peer = select_closest_peer (&finger->finger_identity, 
+                                         &current_closest_peer->best_known_destination,
+                                          current_closest_peer->destination_finger_value,
+                                          current_closest_peer->is_predecessor);
+     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger->finger_identity,
+                                               closest_peer))
+     {
+       current_closest_peer->best_known_destination = finger->finger_identity;
+       current_closest_peer->next_hop = finger_trail->friend.id;
+       current_closest_peer->trail_id = finger_trail->trail_id;
      }
-  } 
+      continue;
+  }
+  return current_closest_peer;
 }
 
 
 /**
- * FIXME: If we remove a finger which is our friend, then how should we handle it. 
- * Ideally only in case if the trail_length > 0,we increment the trail count
- * of the first friend in the trail to reach to the finger. in case finger is
- * our friend then trail length = 0, and hence, we have never incremented the
- * trail count associated with that friend. 
- * Decrement the trail count for the first friend to reach to the finger. 
- * @param finger
+ * Compare friend entry with current successor. If friend is not congested and
+ * has not crossed trail threshold, then check if friend peer identity is
+ * closer to final_destination_finger_value than current_successor. If yes
+ * then update current_successor. 
+ * @param cls closure
+ * @param key current public key
+ * @param value struct Closest_Peer
+ * @return #GNUNET_YES if we should continue to iterate,
+ *         #GNUNET_NO if not.
  */
-static void
-decrement_friend_trail_count (struct FingerInfo *finger)
+static int
+compare_friend_and_current_closest_peer (void *cls,
+                                         const struct GNUNET_PeerIdentity *key,
+                                         void *value)
 {
-  struct FriendInfo *first_trail_friend;
-  struct FriendInfo *second_trail_friend;
+  struct FriendInfo *friend = value;
+  struct Closest_Peer *current_closest_peer = cls;
+  struct GNUNET_PeerIdentity *closest_peer;
   
-  if(finger->first_trail_head != NULL)
-  {
-    first_trail_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, 
-                                                            &(finger->first_trail_head->peer));
-    first_trail_friend->trails_count--;
-  }
-    
-  if(finger->second_trail_head != NULL)
-  {
-    second_trail_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, 
-                                                           &(finger->second_trail_head->peer));
-    second_trail_friend->trails_count--;
-  }
+  if (GNUNET_YES == is_friend_congested (friend))
+    return GNUNET_YES;
   
-#if 0
-  /* We will not need this variable any more, all_friends_trail_threshold,
-   FIXME: REMOVE IT. */
-  if (GNUNET_YES == all_friends_trail_threshold)
+  if (0 == 
+          GNUNET_CRYPTO_cmp_peer_identity (&friend->id,
+                                           &current_closest_peer->best_known_destination))
+    return GNUNET_YES;
+  
+  closest_peer = select_closest_peer (&friend->id, 
+                                      &current_closest_peer->best_known_destination,
+                                      current_closest_peer->destination_finger_value,
+                                      current_closest_peer->is_predecessor);
+
+  /* If friend is the closest successor. */
+  if (0 == GNUNET_CRYPTO_cmp_peer_identity (&friend->id, closest_peer))
   {
-    all_friends_trail_threshold = GNUNET_NO;
-    /* FIXME; Here you should reschedule the send_find_finger_task here. or
-     make a call.*/
+    current_closest_peer->best_known_destination = friend->id;
+    current_closest_peer->next_hop = friend->id;
   }
-#endif
+  
+  return GNUNET_YES;
 }
 
-
 /**
- * FIXME: create a different data structure for storing the peer ids here. 
- * Select the closest finger. Used for both predecessor and other fingers..
- * But internally calls different functions for predecessor and other fingers.
- * @param existing_finger Finger in finger peermap. 
- * @param new_finger New finger identity
- * @param finger_map_index Index in finger peermap where @a existing_finger is stored.
- * @return #GNUNET_YES if the new finger is closest.
- *         #GNUNET_NO if the old finger is closest.
- *         #GNUNET_SYSERR in case our own identity is closest (should never happen).
+ * Initialize current_successor to my_identity.
+ * @param my_identity My peer identity
+ * @return current_successor
  */
-static 
-int select_finger (struct FingerInfo *existing_finger,
-                   const struct GNUNET_PeerIdentity *new_finger,
-                   unsigned int finger_map_index)
+static struct Closest_Peer *
+init_current_successor (struct GNUNET_PeerIdentity my_identity,
+                        uint64_t destination_finger_value,
+                        unsigned int is_predecessor)
 {
-  struct Sorting_List peers[3]; /* 3 for existing_finger, new_finger, my_identity */
-  struct Sorting_List *closest_finger; 
-  uint64_t value;
-  int k;
+  struct Closest_Peer *current_closest_peer;
   
-  for (k = 0; k < 3; k++)
-    peers[k].data = 0;
+  current_closest_peer = GNUNET_new (struct Closest_Peer);
+  memset (&current_closest_peer->trail_id, 0, sizeof (current_closest_peer->trail_id)); 
+  current_closest_peer->destination_finger_value = destination_finger_value;
+  current_closest_peer->is_predecessor = is_predecessor;
+  current_closest_peer->next_hop = my_identity;
+  current_closest_peer->best_known_destination = my_identity;
   
-  /* Add your entry to peers. */
-  memcpy (&peers[0], &my_identity, sizeof (uint64_t));
-  peers[0].type = MY_ID;
-  peers[0].data = NULL;
-  
-  /* Add existing_finger identity to the peers. */
-  memcpy (&peers[1], &(existing_finger->finger_identity), sizeof (uint64_t));
-  peers[1].type = FINGER;
-  peers[1].data = existing_finger;
-  
-  /* Add new_finger identity to the peers. s*/
-  memcpy (&peers[2], &new_finger, sizeof (uint64_t));
-  peers[2].type = VALUE;
-  peers[2].data = NULL;
-  
-  memcpy (&value, &my_identity, sizeof (uint64_t));
-  qsort (&peers, 3, sizeof (struct Sorting_List), &compare_peer_id);
-  
-  if (PREDECESSOR_FINGER_ID == finger_map_index)
-    closest_finger = find_closest_predecessor (peers, value, 3);
-  else
-    closest_finger = find_closest_successor (peers, value, 3);
-  
-  if (closest_finger->type  == FINGER)
-  {
-    return GNUNET_NO;
-  }
-  else if (closest_finger->type == VALUE)
-  {
-    return GNUNET_YES;
-  }
-  else if (closest_finger->type == MY_ID);
-  {
-    return GNUNET_SYSERR;  
-  }
+  return current_closest_peer;
 }
 
 
 /**
- * FIXME: Better name, and make the code more cleaner.
- * Compare the new finger entry added and our successor. 
- * @return #GNUNET_YES if same.
- *         #GNUNET_NO if not. 
+ * FIXME: first check if the finger == closest_peer then don't do anything. 
+ * Find the successor for destination_finger_value among my_identity, all my
+ * friend and all my fingers. Don't consider friends or fingers
+ * which are congested or have crossed the threshold.
+ * @param destination_finger_value Peer closest to this value will be the next successor.
+ * @param local_best_known_destination [out] Updated to my_identity if I am the 
+ *                                     final destination. Updated to friend 
+ *                                     identity in case a friend is successor,
+ *                                     updated to first friend to reach to finger
+ *                                     in case finger is the destination.
+ * @param new_intermediate_trail_id [out] In case a finger is the
+ *                                  @a local_best_known_destination,
+ *                                  then it is the trail to reach it. Else
+ *                                  default set to 0.
+ * @param is_predecessor Are we looking for predecessor or finger?
+ * @return Next hop to reach to local_best_known_destination. In case my_identity
+ *         or a friend is a local_best_known_destination, then 
+ *         next_hop = local_best_known_destination. Else
+ *         next_hop is the first friend to reach to finger (local_best_known_destination)
  */
-static int
-compare_new_entry_and_successor (const struct GNUNET_PeerIdentity *new_finger,
-                                 int finger_map_index)
+static struct GNUNET_PeerIdentity *
+find_successor (uint64_t destination_finger_value,
+                struct GNUNET_PeerIdentity *local_best_known_destination,
+                struct GNUNET_HashCode *new_intermediate_trail_id,
+                unsigned int is_predecessor)
 {
-  int successor_flag = 0;
-  struct FingerInfo *successor_finger;
-  struct GNUNET_CONTAINER_MultiPeerMapIterator *finger_iter;
-  int i;
+  struct Closest_Peer *current_closest_peer;
+  struct GNUNET_PeerIdentity *next_hop;
 
-  if (PREDECESSOR_FINGER_ID == finger_map_index)
-    return GNUNET_NO;
+   /* Initialize current_successor to my_identity. */
+  current_closest_peer = init_current_successor (my_identity,
+                                                 destination_finger_value,
+                                                 is_predecessor);
+
+  /* Compare each friend entry with current_successor and update current_successor
+   * with friend if its closest. */
+  GNUNET_assert (GNUNET_SYSERR != 
+                 GNUNET_CONTAINER_multipeermap_iterate (friend_peermap, 
+                                                        &compare_friend_and_current_closest_peer,
+                                                        current_closest_peer));
   
-  finger_iter = GNUNET_CONTAINER_multipeermap_iterator_create (finger_peermap); 
-  for (i= 0; i < GNUNET_CONTAINER_multipeermap_size (finger_peermap); i++)
-  {
-    if(GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next (finger_iter, NULL,
-                                                                 (const void **)&successor_finger)) 
-    {
-      if (successor_finger->finger_map_index == 0)
-      {
-        successor_flag = 1;
-        break;
-      }
-    }
-  }
-  GNUNET_CONTAINER_multipeermap_iterator_destroy (finger_iter);
+  /* Compare each finger entry with current_successor and update current_successor
+   * with finger if its closest. */
+  compare_finger_and_current_successor (current_closest_peer);
   
-  /* Ideally we should never reach here. */
-  if (successor_flag == 0)
-  {
-    GNUNET_break (0);
-    return GNUNET_NO;
-  }
+  *local_best_known_destination = current_closest_peer->best_known_destination;
+  new_intermediate_trail_id = &current_closest_peer->trail_id;
+  next_hop = GNUNET_new (struct GNUNET_PeerIdentity);
+  *next_hop = current_closest_peer->next_hop;
   
-  if (0 == GNUNET_CRYPTO_cmp_peer_identity (new_finger, &(successor_finger->finger_identity)))
-    return GNUNET_YES;
-  else
-    return GNUNET_NO;
+  return next_hop;
 }
 
 
 /**
- * Add a new entry in finger table. 
- * @param finger_identity PeerIdentity of the new finger
- * @param finger_trail Trail to reach to the finger, can be NULL in case I am my own
- *                     finger.
- * @param finger_trail_length Number of peers in the trail, can be 0 in case finger
- *                            is a friend or I am my own finger.
- * @param finger_map_index Index in finger map. 
+ * Construct a Put message and send it to target_peer.
+ * @param key Key for the content
+ * @param block_type Type of the block
+ * @param options Routing options
+ * @param desired_replication_level Desired replication count
+ * @param best_known_dest Peer to which this message should reach eventually,
+ *                        as it is best known destination to me. 
+ * @param intermediate_trail_id Trail id in case 
+ * @param target_peer Peer to which this message will be forwarded.
+ * @param hop_count Number of hops traversed so far.
+ * @param put_path_length Total number of peers in @a put_path
+ * @param put_path Number of peers traversed so far
+ * @param expiration_time When does the content expire
+ * @param data Content to store
+ * @param data_size Size of content @a data in bytes
  */
-static int
-add_new_entry (const struct GNUNET_PeerIdentity *finger_identity,
-               struct GNUNET_PeerIdentity *finger_trail,
-               uint32_t finger_trail_length,
-               uint32_t finger_map_index)
+void
+GDS_NEIGHBOURS_send_put (const struct GNUNET_HashCode *key,
+                         enum GNUNET_BLOCK_Type block_type,
+                                          enum GNUNET_DHT_RouteOption options,
+                                          uint32_t desired_replication_level,
+                                          struct GNUNET_PeerIdentity *best_known_dest,
+                                          struct GNUNET_HashCode *intermediate_trail_id,
+                                          struct GNUNET_PeerIdentity *target_peer,
+                         uint32_t hop_count,
+                         uint32_t put_path_length,
+                         struct GNUNET_PeerIdentity *put_path,
+                         struct GNUNET_TIME_Absolute expiration_time,
+                         const void *data, size_t data_size)
 {
-  struct FriendInfo *first_friend_trail;
-  struct FingerInfo *new_finger_entry;
-  int i;
+  struct PeerPutMessage *ppm;
+  struct P2PPendingMessage *pending;
+  struct FriendInfo *target_friend;
+  struct GNUNET_PeerIdentity *pp;
+  struct GNUNET_PeerIdentity *local_best_known_dest;
+  size_t msize;
+
+  msize = put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size +
+          sizeof (struct PeerPutMessage);
   
-  /* Add a new entry. */
-  new_finger_entry = GNUNET_malloc (sizeof (struct FingerInfo));
-  memcpy (&(new_finger_entry->finger_identity), finger_identity, sizeof (struct GNUNET_PeerIdentity));
-  new_finger_entry->finger_map_index = finger_map_index;
-  new_finger_entry->first_trail_length = finger_trail_length;
-  new_finger_entry->trail_count = 1;
+  if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
+  {
+    put_path_length = 0;
+    msize = data_size + sizeof (struct PeerPutMessage);
+  }
   
-  if (0 != GNUNET_CRYPTO_cmp_peer_identity (&my_identity,finger_identity)) /* finger_trail is NULL in case I am my own finger identity. */
+  if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
   {
-    /* Incrementing the friend trails count. */
-    if (finger_trail_length > 0)   
-    {
-      first_friend_trail = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &finger_trail[0]);
-      first_friend_trail->trails_count++;
-    }
-    else
-    {
-      /* It means the finger is my friend. */
-      first_friend_trail = GNUNET_CONTAINER_multipeermap_get (friend_peermap, finger_identity);
-      first_friend_trail->trails_count++;
-    }
-    new_finger_entry->first_friend_trails_count = first_friend_trail->trails_count; 
+    GNUNET_break (0);
+    return;
+  }
+  
+   /* This is the first call made from clients file. So, we should search for the
+     target_friend. */
+  if (NULL == target_peer)
+  {
+    uint64_t key_value;
+    struct GNUNET_PeerIdentity *next_hop;
+   
+    memcpy (&key_value, key, sizeof (uint64_t));
+    local_best_known_dest = GNUNET_new (struct GNUNET_PeerIdentity);
     
-    /* Copy the trail. */
-    i = 0;
-    while (i < finger_trail_length)
+    next_hop = find_successor (key_value, local_best_known_dest, 
+                               intermediate_trail_id, GDS_FINGER_TYPE_NON_PREDECESSOR);
+    if (0 == GNUNET_CRYPTO_cmp_peer_identity (local_best_known_dest, &my_identity)) 
     {
-      struct TrailPeerList *element;
-      element = GNUNET_malloc (sizeof (struct TrailPeerList));
-      element->next = NULL;
-      element->prev = NULL;
-    
-      memcpy (&(element->peer), &finger_trail[i], sizeof(struct GNUNET_PeerIdentity));
-      GNUNET_CONTAINER_DLL_insert_tail(new_finger_entry->first_trail_head, new_finger_entry->first_trail_tail, element);
-      i++;
+      /* I am the destination but we have already done datacache_put in client file.  */
+      return;
     }
-  }
-  return GNUNET_CONTAINER_multipeermap_put (finger_peermap,
-                                            &(new_finger_entry->finger_identity),
-                                            new_finger_entry,
-                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);    
-}
-
-
-/**
- * Choose the closest finger between existing finger and new finger.
- * If the new finger is closest, then send a trail_teardown message along 
- * existing_finger's trail. In case both the id's are same, and there is a place
- * to add more trails, then store both of them. In case there is no space to 
- * store any more trail, then choose the best trail (best - depends on length in
- * current_implementation) and discard the others. 
- * @param existing_finger
- * @param new_finger Existing finger in finger_peermap for @a finger_map_index
- * @param trail Trail to reach from me to @a new_finger
- * @param trail_length Total number of peers in @a trail.
- * @param finger_map_index Index in finger peermap. 
- * @return #GNUNET_YES In case we want to store the new entry.
- *         #GNUNET_NO In case we want the existing entry.
- *         #GNUNET_SYSERR Error. 
- */
-static 
-int select_closest_finger (struct FingerInfo *existing_finger,
-                           const struct GNUNET_PeerIdentity *new_finger,
-                           struct GNUNET_PeerIdentity *trail,
-                           unsigned int trail_length,
-                           unsigned int finger_map_index)
-{
-  if (0 == GNUNET_CRYPTO_cmp_peer_identity (&(existing_finger->finger_identity), new_finger))
-  {
-    /* New entry and existing entry are same. */
-    if (0 == GNUNET_CRYPTO_cmp_peer_identity (&(existing_finger->finger_identity), &my_identity))
-    {
-      /* If existing_finger is my_identity then trail_length = 0, trail = NULL. In
-       this case you don't need to check the trails. Exit. */
-      return GNUNET_NO;
-    }
-    if (trail_length > 0)
-    {
-      scan_and_compress_trail (trail, &trail_length, new_finger);
-    }
-    if (existing_finger->trail_count < TRAIL_COUNT)
-    {
-      add_new_trail (existing_finger, trail, trail_length);
-      return GNUNET_NO;
-    }
-    else
-    {
-      select_and_replace_trail (existing_finger, trail, trail_length);
-      return GNUNET_NO;
-    }  
-  }
-  else if (GNUNET_YES == select_finger (existing_finger, new_finger, finger_map_index))
-  {
-    /* New finger is the closest finger. */
-    if (0 == GNUNET_CRYPTO_cmp_peer_identity (&my_identity, new_finger))
-    {
-      /* FIXME: Here in case the new finger is my_identity and old entry is not,
-       should we keep the old entry even if the old entry is not the closest? */
-      return GNUNET_NO;    
-    }
-    send_trail_teardown (existing_finger);
-    decrement_friend_trail_count (existing_finger);
-    free_finger (existing_finger);
-    
-    if (trail_length > 0)
-    {
-      scan_and_compress_trail (trail, &trail_length, new_finger);
-    }
-    return GNUNET_YES;
-  }
-  else if (GNUNET_NO == select_finger (existing_finger, new_finger,finger_map_index))
-  {
-    /* existing_finger is the closest finger. */
-    return GNUNET_NO;
-  }
-  return GNUNET_SYSERR;
-}
-
-
-/**
- * Check if there is already an entry for finger map index in finger table.
- * If yes then choose the closest finger. 
- * @param finger_identity Peer Identity of finger. 
- * @param finger_trail Trail to reach from me to @a finger_identity
- * @param finger_trail_length Total number of peers in finger_trail.
- * @param finger_map_index Index in finger_peermap.
- * @return #GNUNET_YES if the new entry is added.
- *         #GNUNET_NO if the new entry is discarded.
- */
-static 
-int finger_table_add (const struct GNUNET_PeerIdentity *finger_identity,
-                      struct GNUNET_PeerIdentity *finger_trail,
-                      uint32_t finger_trail_length,
-                      uint32_t finger_map_index)
-{
-  struct FingerInfo *existing_finger;
-  struct GNUNET_CONTAINER_MultiPeerMapIterator *finger_iter;
-  int i;
-  int old_entry_found = GNUNET_NO;
-  int new_entry_added = GNUNET_NO;  
-  
-  /* Check if there is already an entry for the finger map index in the finger peer map. */
-  finger_iter = GNUNET_CONTAINER_multipeermap_iterator_create (finger_peermap); 
-  for (i= 0; i < GNUNET_CONTAINER_multipeermap_size (finger_peermap); i++)
-  {
-    if(GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next (finger_iter, NULL,
-                                                                 (const void **)&existing_finger)) 
-    {
-      if (existing_finger->finger_map_index == finger_map_index)
-      {
-        old_entry_found = GNUNET_YES;
-        if ( GNUNET_NO == select_closest_finger (existing_finger, finger_identity, 
-                                                 finger_trail, finger_trail_length,
-                                                 finger_map_index)) 
-          goto update_current_search_finger_index;
-        else
-          break;
-      }
-    } 
-  }
-  GNUNET_CONTAINER_multipeermap_iterator_destroy (finger_iter);
-  
-  if (GNUNET_NO == old_entry_found)
-  {
-    if (finger_trail_length > 0)
-    {
-      scan_and_compress_trail (finger_trail, &finger_trail_length, finger_identity);
-    }
-  }
-  
-  /* FIXME: handle the case when addition in peer map failed. */
-  if(GNUNET_OK == add_new_entry (finger_identity,finger_trail,finger_trail_length, finger_map_index))
-    new_entry_added = GNUNET_YES;
-  else
-    return GNUNET_NO;
-  
-  update_current_search_finger_index:
-  if (0 == finger_map_index)
-  {
-    current_search_finger_index = PREDECESSOR_FINGER_ID;
-    if (0 != GNUNET_CRYPTO_cmp_peer_identity (&my_identity,finger_identity))
-      send_verify_successor_message();
-  }
-  else if (GNUNET_YES == compare_new_entry_and_successor (finger_identity,finger_map_index))
-  {
-    current_search_finger_index = 0;
-  }
-  else 
-  {
-    current_search_finger_index = current_search_finger_index - 1;
-  }
-  
-  return new_entry_added;
-}
-
-
-/**
- * 
- * @param all_known_peers
- * @param array_size
- * @param friend
- * @param key_value
- * @return 
- */
-static struct Sorting_List *
-get_next_successor (struct Sorting_List *all_known_peers,
-                    unsigned int array_size,
-                    struct FriendInfo *friend,
-                    uint64_t key_value)
-{
-  /* 1. search friend in all_known_peers.
-     2. get the next peer. if peer == my_identity or peer == value, then go to
-         next element.
-     3. if friend then again check if threshold crossed or not . If not then return
-        or else again increment. remember starting index of friend in all_known_peers
-       and when you reach to it again then return NULL as it means all the friend
-        are congested or threshold reached. 
-  */
-  return NULL;
-}
-
-
-/**
- * Check if the friend is congested or has crossed TRAIL_THRESHOLD. If yes
- * then choose the peer next to it in the array. In case number of times this 
- * function is called is equal to total number of entries in the array then it
- * means that none of the friends are busy. But remember in this array you also
- * have your own identity, value that you were searching, You should skip those
- * and also keep the count = size -2. But if we call in this order is our get/put
- * not getting wrong. 
- * @param all_known_peers
- * @param array_size
- * @param friend Friend to be checked if 
- * @param key_value To be ignored 
- * @return #GNUNET_YES
- *         #GNUNET_NO
- */
-static int
-check_friend_threshold_and_congestion (struct Sorting_List *all_known_peers,
-                                       unsigned int array_size,
-                                       struct FriendInfo *friend,
-                                       uint64_t key_value)
-{  
-  if (friend->trails_count == TRAIL_THROUGH_FRIEND_THRESHOLD)
-  {
-    return GNUNET_YES;
-  }
-  return GNUNET_NO;
-}
-
-
-/**
- * FIXME: Complete the code for checking the threshold and getting the next
- * peer, add the case in finger. 
- * In case a friend is either congested or has crossed its trail threshold,
- * then don't consider it as next successor, In case of finger if its first
- * friend has crossed the threshold then don't consider it. In case no finger
- * or friend is found, then return NULL.
- * Find closest successor for the value.
- * @param value Value for which we are looking for successor
- * @param[out] current_destination set to my_identity in case I am the final destination,
- *                                 set to friend identity in case friend is final destination,
- *                                 set to first friend to reach to finger, in case finger
- *                                 is final destination. 
- * @param[out] current_source set to my_identity.
- * @param finger_map_index Index in finger peer map. 
- * @return Peer identity of next hop to send trail setup message to,
- *         NULL in case all the friends are either congested or have crossed
- *              their trail threshold.
- */
-static struct GNUNET_PeerIdentity *
-find_successor (uint64_t value, struct GNUNET_PeerIdentity *current_destination,
-               struct GNUNET_PeerIdentity *current_source, unsigned int finger_map_index)
-{
-  struct GNUNET_CONTAINER_MultiPeerMapIterator *friend_iter;
-  struct GNUNET_CONTAINER_MultiPeerMapIterator *finger_iter;
-  struct GNUNET_PeerIdentity key_ret;
-  struct FriendInfo *friend;
-  struct FingerInfo *finger;
-  unsigned int finger_index;
-  unsigned int friend_index;
-  struct Sorting_List *successor;
-  unsigned int size;
-  int j;
-  
-  /* 2 is added in size for my_identity and value which will part of all_known_peers. */
-  size = GNUNET_CONTAINER_multipeermap_size (friend_peermap)+
-         GNUNET_CONTAINER_multipeermap_size (finger_peermap)+
-         2;
-  
-  struct Sorting_List all_known_peers[size];
-  
-  int k;
-  for (k = 0; k < size; k++)
-    all_known_peers[k].peer_id = 0;
-  
-  /* Copy your identity at 0th index in all_known_peers. */
-  j = 0;
-  memcpy (&(all_known_peers[j].peer_id), &my_identity, sizeof (uint64_t));
-  all_known_peers[j].type = MY_ID;
-  all_known_peers[j].data = 0;
-  j++;
-  
-  /* Copy value */
-  all_known_peers[j].peer_id = value;
-  all_known_peers[j].type = VALUE;
-  all_known_peers[j].data = 0;
-  j++;
-  
-  /* Iterate over friend peer map and copy all the elements into array. */
-  friend_iter = GNUNET_CONTAINER_multipeermap_iterator_create (friend_peermap); 
-  for (friend_index = 0; friend_index < GNUNET_CONTAINER_multipeermap_size (friend_peermap); friend_index++)
-  {
-    if(GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next(friend_iter,&key_ret,(const void **)&friend)) 
-    {
-      memcpy (&(all_known_peers[j].peer_id), &(friend->id), sizeof (uint64_t));
-      all_known_peers[j].type = FRIEND;
-      all_known_peers[j].data = friend;
-      j++;
-    }
-  }
-  
-  /* Iterate over finger map and copy all the entries into all_known_peers array. */
-  finger_iter = GNUNET_CONTAINER_multipeermap_iterator_create (finger_peermap);  
-  for (finger_index = 0; finger_index < GNUNET_CONTAINER_multipeermap_size (finger_peermap); finger_index++)
-  {
-    if(GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next(finger_iter,&key_ret,(const void **)&finger)) 
-    {
-      memcpy (&(all_known_peers[j].peer_id), &(finger->finger_identity), sizeof (uint64_t));
-      all_known_peers[j].type = FINGER;
-      all_known_peers[j].data = finger;
-      j++;
-    }
-  }
-  
-  GNUNET_CONTAINER_multipeermap_iterator_destroy (finger_iter);
-  GNUNET_CONTAINER_multipeermap_iterator_destroy (friend_iter); 
-  
-  qsort (&all_known_peers, size, sizeof (struct Sorting_List), &compare_peer_id);
-  
-  /* search value in all_known_peers array. */
-  if (PREDECESSOR_FINGER_ID == finger_map_index)
-    successor = find_closest_predecessor (all_known_peers, value, size);
-  else
-    successor = find_closest_successor (all_known_peers, value, size);
-  
-  if (successor->type == MY_ID)
-  {
-    memcpy (current_destination, &my_identity, sizeof (struct GNUNET_PeerIdentity));
-    return &my_identity;
-  }
-  else if (successor->type == FRIEND)
-  {
-    struct FriendInfo *target_friend;
-    target_friend = (struct FriendInfo *)successor->data;
-    if( GNUNET_YES == check_friend_threshold_and_congestion (all_known_peers, size, target_friend, value))
-    {
-      get_next_successor (all_known_peers, size, friend, value);
-    }
-    memcpy (current_destination, &(target_friend->id), sizeof (struct GNUNET_PeerIdentity));
-    memcpy (current_source, &my_identity, sizeof (struct GNUNET_PeerIdentity));
-    return current_destination;
-  }
-  else if (successor->type == FINGER)
-  {
-    struct GNUNET_PeerIdentity *next_hop;
-    struct FingerInfo *finger;
-    finger = successor->data;
-    next_hop = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
-    
-    if (finger->first_trail_length > 0)
-    {
-      struct TrailPeerList *iterator;
-      iterator = GNUNET_malloc (sizeof (struct TrailPeerList));
-      iterator = finger->first_trail_head;
-      memcpy (next_hop, &(iterator->peer), sizeof (struct GNUNET_PeerIdentity));
-    }
-    else /* This means finger is our friend. */
-      memcpy (next_hop, &(finger->finger_identity), sizeof(struct GNUNET_PeerIdentity));
-    
-    memcpy (current_destination, &(finger->finger_identity), sizeof (struct GNUNET_PeerIdentity));
-    memcpy (current_source, &my_identity, sizeof (struct GNUNET_PeerIdentity));
-    return next_hop;
+    else
+      target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);   
   }
   else
   {
-    GNUNET_assert (0);
-    return NULL;
-  }
-}
-
-
-/**
- * Construct a Put message and send it to target_peer. 
- * @param key Key for the content  
- * @param data Content to store
- * @param data_size Size of content @a data in bytes
- * @param block_type Type of the block
- * @param options Routing options
- * @param desired_replication_level Desired replication count
- * @param expiration_time When does the content expire
- * @param current_destination 
- * @param current_source 
- * @param target_peer Peer to which this message will be forwarded.
- * @param hop_count Number of hops traversed so far.
- * @param put_path_length Total number of peers in @a put_path
- * @param put_path Number of peers traversed so far 
- */
-void
-GDS_NEIGHBOURS_send_put (const struct GNUNET_HashCode *key,
-                         const void *data, size_t data_size,
-                         enum GNUNET_BLOCK_Type block_type,
-                         enum GNUNET_DHT_RouteOption options,
-                         uint32_t desired_replication_level,
-                         struct GNUNET_TIME_Absolute expiration_time,
-                         struct GNUNET_PeerIdentity current_destination,
-                         struct GNUNET_PeerIdentity current_source,
-                         struct GNUNET_PeerIdentity *target_peer,
-                         uint32_t hop_count,
-                         uint32_t put_path_length,
-                         struct GNUNET_PeerIdentity *put_path)
-{
-  struct PeerPutMessage *ppm;
-  struct P2PPendingMessage *pending;
-  struct FriendInfo *target_friend;
-  struct GNUNET_PeerIdentity *pp;
-  size_t msize;
-
-  msize = put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size +
-          sizeof (struct PeerPutMessage);
-  
-  if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
-  {
-    put_path_length = 0;
-    msize = data_size + sizeof (struct PeerPutMessage);
-  }
-  
-  if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
-  {
-    GNUNET_break (0);
-    return;
-  }
-  
-  /* This is the first call made from clients file. So, we should search for the
-     target_friend. */
-  if (NULL == target_peer)
-  {
-    uint64_t key_value;
-    struct GNUNET_PeerIdentity *next_hop;
-   
-    memcpy (&key_value, key, sizeof (uint64_t));
-    next_hop = find_successor (key_value, &current_destination, &current_source,PUT_GET_REQUEST);
-    if (0 == GNUNET_CRYPTO_cmp_peer_identity(next_hop, &my_identity)) /* I am the destination do datacache_put */
-    {
-      GDS_DATACACHE_handle_put (expiration_time, key, put_path_length, put_path,
-                                block_type, data_size, data);
-      return;
-    }
-    else
-      target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);   
+    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, target_peer); 
   }
-  
   pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
   pending->timeout = expiration_time;
   ppm = (struct PeerPutMessage *) &pending[1];
@@ -2674,10 +2111,15 @@ GDS_NEIGHBOURS_send_put (const struct GNUNET_HashCode *key,
   ppm->desired_replication_level = htonl (desired_replication_level);
   ppm->put_path_length = htonl (put_path_length);
   ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
+  if (NULL == best_known_dest)
+    ppm->best_known_destination = *local_best_known_dest;
+  else
+    ppm->best_known_destination = *best_known_dest;
   ppm->key = *key;
-  ppm->current_destination = current_destination;
-  ppm->current_source = current_source;
+  if (NULL == intermediate_trail_id)
+    memset (&ppm->intermediate_trail_id, 0, sizeof (ppm->intermediate_trail_id));
+  else
+    ppm->intermediate_trail_id = *intermediate_trail_id;
   pp = (struct GNUNET_PeerIdentity *) &ppm[1];
   if (put_path_length != 0)
   {
@@ -2692,27 +2134,28 @@ GDS_NEIGHBOURS_send_put (const struct GNUNET_HashCode *key,
 
 
 
-/** 
- * Construct a Get message and send it to target_peer. 
- * @param key Key for the content  
+/**
+ * Construct a Get message and send it to target_peer.
+ * @param key Key for the content
  * @param block_type Type of the block
  * @param options Routing options
  * @param desired_replication_level Desired replication count
- * @param expiration_time When does the content expire
- * @param current_destination 
- * @param current_source 
+ * @param best_known_dest 
+ * @param intermediate_trail_id 
  * @param target_peer Peer to which this message will be forwarded.
  * @param hop_count Number of hops traversed so far.
- * @param put_path_length Total number of peers in @a put_path
- * @param put_path Number of peers traversed so far 
+ * @param data Content to store
+ * @param data_size Size of content @a data in bytes
+ * @param get_path_length Total number of peers in @a get_path
+ * @param get_path Number of peers traversed so far
  */
 void
 GDS_NEIGHBOURS_send_get (const struct GNUNET_HashCode *key,
                          enum GNUNET_BLOCK_Type block_type,
                          enum GNUNET_DHT_RouteOption options,
                          uint32_t desired_replication_level,
-                         struct GNUNET_PeerIdentity current_destination,
-                         struct GNUNET_PeerIdentity current_source,
+                         struct GNUNET_PeerIdentity *best_known_dest,
+                         struct GNUNET_HashCode *intermediate_trail_id,
                          struct GNUNET_PeerIdentity *target_peer,
                          uint32_t hop_count,
                          uint32_t get_path_length,
@@ -2721,6 +2164,7 @@ GDS_NEIGHBOURS_send_get (const struct GNUNET_HashCode *key,
   struct PeerGetMessage *pgm;
   struct P2PPendingMessage *pending;
   struct FriendInfo *target_friend;
+  struct GNUNET_PeerIdentity *local_best_known_dest;
   struct GNUNET_PeerIdentity *gp;
   size_t msize;
 
@@ -2735,14 +2179,16 @@ GDS_NEIGHBOURS_send_get (const struct GNUNET_HashCode *key,
   
   if (NULL == target_peer)
   {
-    /* This is the first call from client file, we need to search for next_hop*/
     struct GNUNET_PeerIdentity *next_hop;
     uint64_t key_value;
     
     memcpy (&key_value, key, sizeof (uint64_t));
        // FIXME: endianess of key_value!?
-    next_hop = find_successor (key_value, &current_destination, &current_source,PUT_GET_REQUEST);
-    if (0 == GNUNET_CRYPTO_cmp_peer_identity(&my_identity,next_hop)) /* I am the destination do datacache_put */
+    local_best_known_dest = GNUNET_new (struct GNUNET_PeerIdentity);
+    next_hop = find_successor (key_value, local_best_known_dest,
+                               intermediate_trail_id, GDS_FINGER_TYPE_NON_PREDECESSOR);
+    
+    if (0 == GNUNET_CRYPTO_cmp_peer_identity (&my_identity,next_hop)) 
     {
       GDS_DATACACHE_handle_get (key,block_type, NULL, 0, 
                                 NULL, 0, 1, &my_identity, NULL,&my_identity);
@@ -2753,6 +2199,10 @@ GDS_NEIGHBOURS_send_get (const struct GNUNET_HashCode *key,
       target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
     }
   }
+  else
+  {
+    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, target_peer); 
+  }
   
   pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
   pending->importance = 0;    /* FIXME */
@@ -2762,8 +2212,15 @@ GDS_NEIGHBOURS_send_get (const struct GNUNET_HashCode *key,
   pgm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET);
   pgm->get_path_length = htonl (get_path_length);
   pgm->key = *key;
-  pgm->current_destination = current_destination;
-  pgm->current_source = current_source;
+  if (NULL != best_known_dest)
+   pgm->best_known_destination = *best_known_dest;
+  else
+    pgm->best_known_destination = *local_best_known_dest;
+  
+  if (NULL == intermediate_trail_id)
+    memset (&pgm->intermediate_trail_id, 0, sizeof (pgm->intermediate_trail_id));
+  else
+    pgm->intermediate_trail_id = *intermediate_trail_id;
   pgm->hop_count = htonl (hop_count + 1);
   
   if (get_path != 0)
@@ -2779,29 +2236,29 @@ GDS_NEIGHBOURS_send_get (const struct GNUNET_HashCode *key,
 
 /**
  * Send the get result to requesting client.
- * @param expiration When will this result expire?
  * @param key Key of the requested data.
+ * @param type Block type
+ * @param target_peer Next peer to forward the message to.
+ * @param source_peer Peer which has the data for the key.
  * @param put_path_length Number of peers in @a put_path
  * @param put_path Path taken to put the data at its stored location.
- * @param type Block type
- * @param data_size Size of the @a data 
- * @param data Payload to store
- * @param get_path Path taken to reach to the location of the key.
  * @param get_path_length Number of peers in @a get_path
- * @param next_hop Next peer to forward the message to. 
- * @param source_peer Peer which has the data for the key.
+ * @param get_path Path taken to reach to the location of the key.
+ * @param expiration When will this result expire?
+ * @param data Payload to store
+ * @param data_size Size of the @a data
  */
-void 
-GDS_NEIGHBOURS_send_get_result (struct GNUNET_TIME_Absolute expiration,
-                                const struct GNUNET_HashCode *key,
+void
+GDS_NEIGHBOURS_send_get_result (const struct GNUNET_HashCode *key,
+                                enum GNUNET_BLOCK_Type type,
+                                struct GNUNET_PeerIdentity *target_peer,
+                                struct GNUNET_PeerIdentity *source_peer,
                                 unsigned int put_path_length,
                                 const struct GNUNET_PeerIdentity *put_path,
-                                enum GNUNET_BLOCK_Type type, size_t data_size,
-                                const void *data,
-                                struct GNUNET_PeerIdentity *get_path,
                                 unsigned int get_path_length,
-                                struct GNUNET_PeerIdentity *next_hop,
-                                struct GNUNET_PeerIdentity *source_peer)
+                                struct GNUNET_PeerIdentity *get_path,
+                                struct GNUNET_TIME_Absolute expiration,
+                                const void *data, size_t data_size)
 {
   struct PeerGetResultMessage *get_result;
   struct GNUNET_PeerIdentity *get_result_path;
@@ -2810,7 +2267,7 @@ GDS_NEIGHBOURS_send_get_result (struct GNUNET_TIME_Absolute expiration,
   struct FriendInfo *target_friend;
   int current_path_index;
   size_t msize;
-  
+
   msize = get_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size +
           sizeof (struct PeerPutMessage);
  
@@ -2825,14 +2282,14 @@ GDS_NEIGHBOURS_send_get_result (struct GNUNET_TIME_Absolute expiration,
     current_path_index = search_my_index(get_path, get_path_length);
     if (GNUNET_SYSERR == current_path_index)
     {
-      /* FIXME: This assertion always fails. FIX IT. */
       GNUNET_break (0);
       return;
     }
   }
   if (0 == current_path_index)
   {
-    GDS_CLIENTS_handle_reply (expiration, key, get_path_length, get_path, put_path_length,
+    GDS_CLIENTS_handle_reply (expiration, key, get_path_length, 
+                              get_path, put_path_length,
                               put_path, type, data_size, data);
     return;
   }
@@ -2844,15 +2301,15 @@ GDS_NEIGHBOURS_send_get_result (struct GNUNET_TIME_Absolute expiration,
   get_result->header.size = htons (msize);
   get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET_RESULT);
   get_result->key = *key;
-  memcpy (&(get_result->source_peer), source_peer, sizeof (struct GNUNET_PeerIdentity));
+  /* FIXME: check if you are passing the correct querying_peer as described in
+   the get_result documentation. */
+  memcpy (&(get_result->querying_peer), source_peer, sizeof (struct GNUNET_PeerIdentity));
   get_result->expiration_time = expiration;
   
-  if (get_path_length != 0)
-  {
-    get_result_path = (struct GNUNET_PeerIdentity *)&get_result[1];
-    memcpy (get_result_path, get_path,
+  
+  get_result_path = (struct GNUNET_PeerIdentity *)&get_result[1];
+  memcpy (get_result_path, get_path,
             sizeof (struct GNUNET_PeerIdentity) * get_path_length);
-  }
   memcpy (&get_result_path[get_path_length], data, data_size);
   
   /* FIXME: Is this correct? */
@@ -2861,7 +2318,9 @@ GDS_NEIGHBOURS_send_get_result (struct GNUNET_TIME_Absolute expiration,
     pp = (struct GNUNET_PeerIdentity *)&get_result_path[1];
     memcpy (pp, put_path,sizeof (struct GNUNET_PeerIdentity) * put_path_length);
   }
-  target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
+  
+  target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, 
+                                                     &get_result_path[current_path_index - 1]);
   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
   target_friend->pending_count++;
   process_friend_queue (target_friend);
@@ -2869,85 +2328,1002 @@ GDS_NEIGHBOURS_send_get_result (struct GNUNET_TIME_Absolute expiration,
 
 
 /**
- * Send trail rejection message to the peer which sent me a trail setup message. 
- * @param source_peer Source peer which wants to set up the trail.
- * @param finger_identity Value whose successor will be the finger of @a source_peer.
- * @param congested_peer Peer which has send trail rejection message.
- * @param next_hop Peer to which this message should be forwarded.
- * @param finger_map_index Index in @a source_peer finger peermap.
- * @param trail_peer_list Trail followed to reach from @a source_peer to next_hop,
- *                        NULL, in case the @a congested_peer was the first peer 
- *                        to which trail setup message was forwarded.
- * @param trail_length Number of peers in trail_peer_list. 
+ * Randomly choose one of your friends (which is not congested and have not crossed
+ * trail threshold) from the friends_peer map
+ * @return Friend Randomly chosen friend.
+ *         NULL in case friend peermap is empty, or all the friends are either
+ *              congested or have crossed trail threshold.
  */
-void
-GDS_NEIGHBOURS_send_trail_rejection (const struct GNUNET_PeerIdentity *source_peer,
-                                     uint64_t finger_identity,
-                                     const struct GNUNET_PeerIdentity *congested_peer,
-                                     const struct GNUNET_PeerIdentity *next_hop,
-                                     unsigned int finger_map_index,
-                                     struct GNUNET_PeerIdentity *trail_peer_list,
-                                     unsigned int trail_length)
+static struct FriendInfo *
+select_random_friend ()
 {
-  struct PeerTrailRejectionMessage *trail_rejection;
-  struct GNUNET_PeerIdentity *trail_list;
-  struct P2PPendingMessage *pending;
-  struct FriendInfo *target_friend;
-  size_t msize;
-  
-  msize = trail_length * sizeof(struct GNUNET_PeerIdentity) +
-          sizeof (struct PeerTrailRejectionMessage);
-  
-  if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
-  {
-    GNUNET_break (0);
-    return;
-  }
-  
-  pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize); 
-  pending->importance = 0;    
-  pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
-  trail_rejection = (struct PeerTrailRejectionMessage *) &pending[1]; 
-  pending->msg = &trail_rejection->header;
-  trail_rejection->header.size = htons (msize);
-  trail_rejection->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP);
-  memcpy (&(trail_rejection->source_peer), source_peer, sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&(trail_rejection->congested_peer), congested_peer, sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&(trail_rejection->finger_identity_value), &finger_identity, sizeof (uint64_t));
-  trail_rejection->finger_map_index = htonl (finger_map_index);
-  trail_rejection->trail_length = htonl (trail_length);
-  
-  if (trail_length != 0)
+  unsigned int current_size;
+  uint32_t index;
+  unsigned int j = 0;
+  struct GNUNET_CONTAINER_MultiPeerMapIterator *iter;
+  struct GNUNET_PeerIdentity key_ret;
+  struct FriendInfo *friend;
+
+  current_size = GNUNET_CONTAINER_multipeermap_size (friend_peermap);
+  if (0 == current_size)
+    return NULL;
+
+  index = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, current_size);
+  iter = GNUNET_CONTAINER_multipeermap_iterator_create (friend_peermap);
+
+  for (j = 0; j < index ; j++)
+    GNUNET_assert (GNUNET_YES ==
+                   GNUNET_CONTAINER_multipeermap_iterator_next (iter, NULL, NULL));
+  do
   {
-    trail_list = (struct GNUNET_PeerIdentity *)&trail_rejection[1];
-    memcpy (trail_list, trail_peer_list, trail_length * sizeof (struct GNUNET_PeerIdentity));
-  }
-  
-  target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
-  GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
-  target_friend->pending_count++;
-  process_friend_queue (target_friend);
+    if (j == current_size)
+    {
+      j = 0;
+      GNUNET_CONTAINER_multipeermap_iterator_destroy (iter);
+      iter = GNUNET_CONTAINER_multipeermap_iterator_create (friend_peermap);
+
+    }
+    GNUNET_assert (GNUNET_YES ==
+                GNUNET_CONTAINER_multipeermap_iterator_next (iter,
+                                                             &key_ret,
+                                                             (const void **)&friend));
+
+    /* This friend is not congested and has not crossed trail threshold. */
+    if ((TRAILS_THROUGH_FRIEND_THRESHOLD > friend->trails_count) &&
+        (0 == GNUNET_TIME_absolute_get_remaining (friend->congestion_timestamp).rel_value_us))
+    {
+      break;
+    }
+    friend = NULL;
+    j++;
+  } while (j != index);
+
+  GNUNET_CONTAINER_multipeermap_iterator_destroy (iter);
+  return friend;
+}
+
+
+/**
+ * Compute 64 bit value of finger_identity corresponding to a finger index using 
+ * chord formula. 
+ * For all fingers:
+ * n.finger[i] = n + pow (2,i),
+ * For predecessor
+ * n.finger[i] = n - 1, where
+ * n = my_identity
+ * i = finger_index.
+ * n.finger[i] = 64 bit finger value
+ * @param finger_index Index corresponding to which we calculate 64 bit value.
+ * @return 64 bit value.
+ */
+static uint64_t
+compute_finger_identity_value (unsigned int finger_index)
+{
+  uint64_t my_id64;
+
+  memcpy (&my_id64, &my_identity, sizeof (uint64_t));
+  my_id64 = GNUNET_ntohll (my_id64);
+  
+  /* Are we looking for immediate predecessor? */
+  if (PREDECESSOR_FINGER_ID == finger_index)
+    return (my_id64 -1);
+  else
+    return (my_id64 + (unsigned long) pow (2, finger_index));
+}
+
+
+/*
+ * Choose a random friend. Start looking for the trail to reach to
+ * finger identity corresponding to current_search_finger_index through 
+ * this random friend.
+ *
+ * @param cls closure for this task
+ * @param tc the context under which the task is running
+ */
+static void
+send_find_finger_trail_message (void *cls,
+                                const struct GNUNET_SCHEDULER_TaskContext *tc)
+{
+  struct FriendInfo *target_friend;
+  struct GNUNET_TIME_Relative next_send_time;
+  struct GNUNET_HashCode trail_id;
+  unsigned int is_predecessor;
+  uint64_t finger_id_value;
+
+  /* Schedule another send_find_finger_trail_message task. */
+  next_send_time.rel_value_us =
+      DHT_FIND_FINGER_TRAIL_INTERVAL.rel_value_us +
+      GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
+                                DHT_FIND_FINGER_TRAIL_INTERVAL.rel_value_us);
+  find_finger_trail_task =
+      GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_finger_trail_message,
+                                    NULL);
+
+  /* My own routing table is all full. I can not store any more trails for which 
+     I am source. */
+  if (GNUNET_YES == GDS_ROUTING_threshold_reached())
+    return;
+  
+  target_friend = select_random_friend ();
+  if (NULL == target_friend)
+  {
+    return;
+  }
+  
+  finger_id_value = compute_finger_identity_value (current_search_finger_index);
+  if (PREDECESSOR_FINGER_ID == current_search_finger_index)
+    is_predecessor = 1;
+  else
+    is_predecessor = 0;
+
+  /* Generate a unique trail id for trail we are trying to setup. */
+  GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_STRONG,
+                              &trail_id, sizeof (trail_id));
+  GDS_NEIGHBOURS_send_trail_setup (my_identity, finger_id_value,
+                                   target_friend->id, target_friend, 0, NULL,
+                                   is_predecessor, trail_id, NULL);
+}
+
+
+/**
+ * In case there are already maximum number of possible trails to reach to a
+ * finger, then check if the new trail's length is lesser than any of the
+ * existing trails.
+ * If yes then replace that old trail by new trail.
+ *
+ * Note: Here we are taking length as a parameter to choose the best possible
+ * trail, but there could be other parameters also like:
+ * 1. duration of existence of a trail - older the better.
+ * 2. if the new trail is completely disjoint than the
+ *    other trails, then may be choosing it is better.
+ *
+ * @param existing_finger
+ * @param new_finger_trail
+ * @param new_finger_trail_length
+ * @param new_finger_trail_id
+ */
+static void
+select_and_replace_trail (struct FingerInfo *existing_finger,
+                          const struct GNUNET_PeerIdentity *new_trail,
+                          unsigned int new_trail_length,
+                          struct GNUNET_HashCode new_trail_id)
+{
+  struct Trail *trail_list_iterator;
+  unsigned int largest_trail_length;
+  unsigned int largest_trail_index;
+  struct Trail_Element *trail_element;
+  unsigned int i;
+
+  largest_trail_length = new_trail_length;
+  largest_trail_index = MAXIMUM_TRAILS_PER_FINGER + 1;
+
+  GNUNET_assert (MAXIMUM_TRAILS_PER_FINGER == existing_finger->trails_count);
+
+  for (i = 0; i < existing_finger->trails_count; i++)
+  {
+    trail_list_iterator = &existing_finger->trail_list[i];
+    if (trail_list_iterator->trail_length > largest_trail_length)
+    {
+      largest_trail_length = trail_list_iterator->trail_length;
+      largest_trail_index = i;
+    }
+  }
+
+  if (largest_trail_index == (MAXIMUM_TRAILS_PER_FINGER + 1))
+  {
+    // tear down new trail: it's not better than the existing ones
+    return;
+  }
+
+  /* Send trail teardown message across the replaced trail. */
+  struct Trail *replace_trail = &existing_finger->trail_list[largest_trail_index];
+
+  GDS_NEIGHBOURS_send_trail_teardown (replace_trail->trail_id,
+                                      GDS_ROUTING_SRC_TO_DEST,
+                                      &replace_trail->trail_head->peer);
+  /* Free the trail. */
+  while (NULL != (trail_element = replace_trail->trail_head))
+  {
+    GNUNET_CONTAINER_DLL_remove (replace_trail->trail_head,
+                                 replace_trail->trail_tail, trail_element);
+    GNUNET_free_non_null (trail_element);
+  }
+
+  /* Add new trial at that location. */
+  i = 0;
+  while (i < new_trail_length)
+  {
+    struct Trail_Element *element = GNUNET_new (struct Trail_Element);
+    element->peer = new_trail[i];
+
+    GNUNET_CONTAINER_DLL_insert_tail (replace_trail->trail_head,
+                                      replace_trail->trail_tail,
+                                      element);
+  }
+}
+
+
+/**
+ * Check if the new trail to reach to finger is unique or do we already have
+ * such a trail present for finger.
+ * @param existing_finger Finger identity
+ * @param new_trail New trail to reach @a existing_finger
+ * @param trail_length Total number of peers in new_trail.
+ * @return #GNUNET_YES if the new trail is unique
+ *         #GNUNET_NO if same trail is already present.
+ */
+static int
+is_new_trail_unique (struct FingerInfo *existing_finger,
+                     const struct GNUNET_PeerIdentity *new_trail,
+                     unsigned int trail_length)
+{
+  struct Trail *trail_list_iterator;
+  struct Trail_Element *trail_element;
+  int i;
+  int j;
+  int trail_unique = GNUNET_NO;
+
+  for (i = 0; i < existing_finger->trails_count; i++)
+  {
+    trail_list_iterator = &existing_finger->trail_list[i];
+    if (trail_list_iterator->trail_length != trail_length)
+      continue;
+    trail_element = trail_list_iterator->trail_head;
+    for (j = 0; j < trail_list_iterator->trail_length; j++)
+    {
+      if (0 != GNUNET_CRYPTO_cmp_peer_identity (&new_trail[j],
+                                                &trail_element->peer))
+      {
+        trail_unique = GNUNET_YES;
+        break;
+      }
+    }
+  }
+  return trail_unique;
+}
+
+
+/**
+ * Add a new trail to existing finger.
+ * @param existing_finger
+ * @param new_finger_trail
+ * @param new_finger_trail_length
+ * @param new_finger_trail_id
+ */
+static void
+add_new_trail (struct FingerInfo *existing_finger,
+               const struct GNUNET_PeerIdentity *new_trail,
+               unsigned int new_trail_length,
+               struct GNUNET_HashCode new_trail_id)
+{
+  struct Trail *trail_list_iterator;
+  struct FriendInfo *first_friend;
+  int i;
+
+  if (GNUNET_NO == is_new_trail_unique (existing_finger, new_trail,
+                                        new_trail_length))
+  {
+    return;
+  }
+
+  // FIXME checking trail_head is NOT a valid way to verify an open slot
+  for (i = 0; existing_finger->trail_list[i].trail_head != NULL; i++)
+    GNUNET_assert (i < MAXIMUM_TRAILS_PER_FINGER);
+
+  trail_list_iterator = &existing_finger->trail_list[i];
+
+  if (new_trail_length > 0)
+    first_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                                      &new_trail[0]);
+  else
+    first_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                                      &(existing_finger->finger_identity));
+  first_friend->trails_count++;
+  /* FIXME; we removed this field but read fixme. */
+  //trail_list_iterator->first_friend_trail_count = first_friend->trails_count;
+  trail_list_iterator->trail_length = new_trail_length;
+
+  for (i = 0; i < new_trail_length; i++)
+  {
+    struct Trail_Element *element;
+    element = GNUNET_new (struct Trail_Element);
+
+    element->peer = new_trail[i];
+    GNUNET_CONTAINER_DLL_insert_tail (trail_list_iterator->trail_head,
+                                      trail_list_iterator->trail_tail,
+                                      element);
+  }
+  existing_finger->trails_count++;
+}
+
+
+/**
+ * Send trail teardown message for a specific trail of a finger.
+ * @param finger Finger whose trail is to be removed. 
+ * @param trail List of peers in trail from me to a finger, NOT including 
+ *              endpoints. 
+ */
+static void
+send_trail_teardown (struct FingerInfo *finger,
+                     struct Trail *trail)
+{
+  /* FIXME: Now source also stores a trail entry in its routing table. before
+   sending the trail teardown, you should get next_hop from routing table.
+   If it is NULL, it means that path is broken, then remove the trail. 
+   return a value to calling function so that if all trails are removed,
+   then remove finger. */
+  /* We should decerement the friend trail count here. */
+  struct FriendInfo *friend;
+  
+  GNUNET_assert (NULL != (friend = 
+          GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                             &trail->trail_head->peer)));
+  
+  friend->trails_count--;
+  GDS_NEIGHBOURS_send_trail_teardown (trail->trail_id,
+                                      GDS_ROUTING_SRC_TO_DEST,
+                                      &trail->trail_head->peer);
+}
+
+
+/**
+ * Send trail teardown message across all the trails to reach to finger. 
+ * @param finger Finger whose all the trail should be freed. 
+ */
+static void
+send_all_finger_trails_teardown (struct FingerInfo *finger)
+{
+  struct Trail *trail;
+  int i;
+
+  for (i = 0; i < finger->trails_count; i++)
+  {
+    trail = &finger->trail_list[i];
+    if (trail->trail_length > 0)
+    {
+     /* decerement the friend trails count. */
+     send_trail_teardown (finger, trail);
+    }
+  }
+}
+
+
+/**
+ * Free a specific trail
+ * @param trail List of peers to be freed. 
+ */
+static void
+free_trail (struct Trail *trail)
+{
+  struct Trail_Element *trail_element;
+
+  while (NULL != (trail_element = trail->trail_head))
+  {
+    GNUNET_CONTAINER_DLL_remove (trail->trail_head, 
+                                 trail->trail_tail,
+                                 trail_element);
+    GNUNET_free_non_null (trail_element);
+  }  
+  trail->trail_head = NULL;
+  trail->trail_tail = NULL;
+}
+
+
+/**
+ * Free finger and its trail.
+ * @param finger Finger to be freed.
+ */
+static void
+free_finger (struct FingerInfo *finger, unsigned int finger_table_index)
+{
+  struct Trail *trail;
+  unsigned int i;
+
+  for (i = 0; i < finger->trails_count; i++)
+  {
+    trail = &finger->trail_list[i];
+    if (GNUNET_NO == trail->is_present)
+      continue;
+    
+    if (trail->trail_length > 0)
+      free_trail (trail);
+  }
+  
+  finger->is_present = GNUNET_NO;
+  memset ((void *)&finger_table[finger_table_index], 0, sizeof (finger_table[finger_table_index]));
+}
+
+
+/**
+ * FIXME: ensure that you are not adding any trail to reach to a friend which
+ * is a finger. Also decide on should you increment trails count of a friend
+ * which is also a finger. 
+ * Add a new entry in finger table at finger_table_index. 
+ * In case finger identity is me or a friend, then don't add a trail. NOTE
+ * trail length to reach to a finger can be 0 only if the finger is a friend
+ * or my identity.
+ * In case a finger is a friend, then increment the trails count of the friend.
+ * @param finger_identity Peer Identity of new finger
+ * @param finger_trail Trail to reach from me to finger (excluding both end points).
+ * @param finger_trail_length Total number of peers in @a finger_trail.
+ * @param trail_id Unique identifier of the trail.
+ * @param finger_table_index Index in finger table.
+ */
+static void
+add_new_finger (struct GNUNET_PeerIdentity finger_identity,
+                const struct GNUNET_PeerIdentity *finger_trail,
+                unsigned int finger_trail_length,
+                struct GNUNET_HashCode trail_id,
+                unsigned int finger_table_index)
+{
+  struct FingerInfo *new_entry;
+  struct FriendInfo *first_trail_hop;
+  struct Trail *trail;
+  int i = 0;
+  
+  new_entry = GNUNET_new (struct FingerInfo);
+  new_entry->finger_identity = finger_identity;
+  new_entry->finger_table_index = finger_table_index;
+  new_entry->is_present = GNUNET_YES;
+  
+  /* If the new entry is my own identity or a friend. */
+  if ((0 == GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &finger_identity)) ||
+     (NULL != GNUNET_CONTAINER_multipeermap_get (friend_peermap, &finger_identity)))
+  {
+    new_entry->trails_count = 0;
+    finger_table[finger_table_index] = *new_entry;
+    return;
+  }
+  
+  /* finger trail length can be 0 only in case if finger is my identity or
+   finger is friend. We should never reach here. */
+  GNUNET_assert (finger_trail_length > 0);
+  
+  GNUNET_assert (NULL != 
+                (first_trail_hop = 
+                       GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                                          &finger_trail[0])));
+  new_entry->trails_count = 1;
+  first_trail_hop->trails_count++;
+   
+  /* Copy the finger trail into trail. */
+  trail = GNUNET_new (struct Trail);
+  while (i < finger_trail_length)
+  {
+    struct Trail_Element *element = GNUNET_new (struct Trail_Element);
+
+    element->next = NULL;
+    element->prev = NULL;
+    element->peer = finger_trail[i];
+    GNUNET_CONTAINER_DLL_insert_tail (trail->trail_head,
+                                      trail->trail_tail,
+                                      element);
+    i++;
+  }
+  
+  /* Add trail to trail list. */
+  new_entry->trail_list[0].trail_head = trail->trail_head;
+  new_entry->trail_list[0].trail_tail = trail->trail_tail;
+  new_entry->trail_list[0].trail_length = finger_trail_length;
+  new_entry->trail_list[0].trail_id = trail_id;
+  new_entry->trail_list[0].is_present = GNUNET_YES;
+  finger_table[finger_table_index] = *new_entry;
+  return;
+}
+
+
+/**
+ * Scan the trail to check if there is any other friend in the trail other than
+ * first hop. If yes then shortcut the trail, send trail compression message to
+ * peers which are no longer part of trail and send back the updated trail
+ * and trail_length to calling function.
+ * @param finger_identity Finger whose trail we will scan.
+ * @param finger_trail [in, out] Trail to reach from source to finger,
+ * @param finger_trail_length  Total number of peers in original finger_trail.
+ * @param finger_trail_id Unique identifier of the finger trail.
+ * @return updated trail length in case we shortcut the trail, else original
+ *         trail length.
+ */
+static struct GNUNET_PeerIdentity *
+scan_and_compress_trail (struct GNUNET_PeerIdentity finger_identity,
+                         const struct GNUNET_PeerIdentity *trail,
+                         unsigned int trail_length,
+                         struct GNUNET_HashCode trail_id,
+                         int *new_trail_length)
+{
+  struct FriendInfo *target_friend;
+  struct GNUNET_PeerIdentity *new_trail;
+  int i;
+  
+  /* If I am my own finger identity, then we set trail_length = 0.
+   Note: Here we don't send trail compression message, as no peer in its
+   trail added an entry in its routing table.*/
+  if (0 == GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &finger_identity))
+  {
+    *new_trail_length = 0;
+    return NULL;
+  }
+
+  /* If finger identity is a friend. */
+  if (NULL != GNUNET_CONTAINER_multipeermap_get (friend_peermap, &finger_identity))
+  {
+    *new_trail_length = 0;
+    
+    /* If there is trail to reach this finger/friend */
+    if (trail_length > 0)
+    {
+      target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                                         &trail[0]);
+      /* FIXME: In case its finger == friend, then may be we send a trail 
+       teardown message as it does not make any sense to have any routing e
+       entry in your own routing table.*/
+      GDS_NEIGHBOURS_send_trail_compression (my_identity, 
+                                             trail_id, finger_identity,
+                                             target_friend);
+    }
+    return NULL;
+  }
+
+  /*  For other cases, when its neither a friend nor my own identity.*/
+  for (i = trail_length - 1; i > 0; i--)
+  {
+    /* If the element at this index in trail is a friend. */
+    if (NULL != GNUNET_CONTAINER_multipeermap_get (friend_peermap, &trail[i]))
+    {
+      struct FriendInfo *target_friend;
+      int j = 0;
+
+      target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                                         &trail[0]);
+      GDS_NEIGHBOURS_send_trail_compression (my_identity, 
+                                             trail_id, trail[i],
+                                             target_friend);
+
+    
+      /* Copy the trail from index i to index (trail_length -1) into a new trail
+       *  and update new trail length */
+      new_trail = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity) * i);
+      while (i < trail_length)
+      {
+        memcpy (&new_trail[j], &trail[i], sizeof(struct GNUNET_PeerIdentity));
+        j++;
+        i++;
+      }
+      *new_trail_length = j+1;
+      return new_trail;
+    }
+  }
+  
+  /* If we found no other friend except the first hop, return the original
+     trail back.*/
+  new_trail = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity) * trail_length); 
+  *new_trail_length = trail_length;
+  memcpy (new_trail, trail, trail_length * sizeof (struct GNUNET_PeerIdentity));
+  return new_trail;
+}
+
+
+/**
+ * Send verify successor message to your current successor over the shortest
+ * trail. 
+ * @param successor Current successor.
+ */
+static void
+send_verify_successor_message (struct FingerInfo *successor)
+{
+  /*
+   * FIXME: should we send a verify successor message across all the trails
+   * in case we send through all friends. It complicates the logic, don't
+   * do it at the moment. Write it as optimization and do it later. 
+   * 1. Here we can have 3 types of fingers
+   * --> my own identity
+   *     Assumption that the calling function will not send request for
+   *     such successor. Move the logic here. 
+   * --> friend is a finger
+   *     Need to verify if we keep the trails count for a friend. In case of
+   *     friend there is no trail to reach to that friend, so
+   *     1. no entry in routing table
+   *     2. no trail id
+   *     3. no trails count
+   *     4. but do we increment the count of trails through the friend? 
+   *        Trails count is used only to keep a limit on number of trails
+   *        that a friend should be part of. No need to increment the trails
+   *        count for a friend which is a finegr also. so, if finger = friend
+   *        then don't increment the trails count. But if the same friend 
+   *        is the first friend to reach to some other finger then increment
+   *        the trails count. Not sure if this design is correct need to verify
+   *        again. 
+   * --> real finger
+   */
+  struct FriendInfo *target_friend;
+  struct GNUNET_HashCode trail_id;
+  int i;
+  
+  /* If successor is a friend. */
+  if (successor->trails_count == 0)
+  {
+    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                                       &successor->finger_identity);
+    memset ((void *)&trail_id, 0 , sizeof (trail_id));
+    GDS_NEIGHBOURS_send_verify_successor_message (my_identity,
+                                                  successor->finger_identity,
+                                                  trail_id, NULL, 0,
+                                                  target_friend);
+    return;
+  }
+  
+  for (i = 0; i < successor->trails_count; i++)
+  {
+    struct Trail *trail;
+    struct Trail_Element *element;
+    unsigned int trail_length;
+    int j;
+    
+    trail = &successor->trail_list[i];
+    
+    /* No trail stored at this index. */
+    if (GNUNET_YES == trail->is_present)
+      continue;
+    
+    /* Only in case of a friend we can have no trail. We have already handled
+     * that case. So, now we should never have any such trail. */
+    GNUNET_assert (trail->trail_length > 0);
+    trail_id = trail->trail_id;
+    trail_length = trail->trail_length;
+    
+    /* Copy the trail into peer list. */
+    element = trail->trail_head;
+    struct GNUNET_PeerIdentity peer_list[trail_length];
+    while (j < trail_length)
+    {
+      peer_list[j] = element->peer;
+      element = element->next;
+      j++;
+    }
+   
+    GNUNET_assert (NULL != (target_friend = 
+                           GNUNET_CONTAINER_multipeermap_get (friend_peermap, 
+                                                              &peer_list[0])));
+    GDS_NEIGHBOURS_send_verify_successor_message (my_identity,
+                                                  successor->finger_identity,
+                                                  trail_id, peer_list, trail_length,
+                                                  target_friend);
+    
+  }
+}
+
+
+/**
+ * FIXME" clear abstraction of current search finger index and finger map index.
+ * it never goes to 63. I don't know why
+ * Update the current search finger index. 
+ */
+static void
+update_current_search_finger_index (struct GNUNET_PeerIdentity finger_identity,
+                                    unsigned int finger_table_index)
+{
+  struct FingerInfo *successor;
+
+  if (finger_table_index != current_search_finger_index)
+    return;
+  
+  successor = &finger_table[0];
+  if (GNUNET_NO == successor->is_present)
+    GNUNET_break(0);
+  /* We were looking for immediate successor.  */
+  if (0 == current_search_finger_index)
+  {
+    /* Start looking for immediate predecessor. */
+    current_search_finger_index = PREDECESSOR_FINGER_ID;
+
+    /* If I am not my own successor, then send a verify successor message. */
+    if (0 != GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &finger_identity))
+    {
+      send_verify_successor_message (successor);
+    }
+    return;
+  }
+  
+  current_search_finger_index = current_search_finger_index - 1;
+  return;
+}
+
+
+/**
+ * Calculate finger_table_index from initial 64 bit finger identity value that 
+ * we send in trail setup message. 
+ * @param ultimate_destination_finger_value Value that we calculated from our
+ *                                          identity and finger_table_index.
+ * @param is_predecessor Is the entry for predecessor or not?
+ * @return finger_table_index Value between 0 <= finger_table_index <= 64
+ *                            -1, if no valid finger_table_index is found. 
+ */
+static unsigned int
+get_finger_table_index (uint64_t ultimate_destination_finger_value,
+                        unsigned int is_predecessor)
+{
+  uint64_t my_id64;
+  int diff;
+  unsigned int finger_table_index;
+
+  memcpy (&my_id64, &my_identity, sizeof (uint64_t));
+  my_id64 = GNUNET_ntohll (my_id64);
+  
+  /* Is this a predecessor finger? */
+  if (1 == is_predecessor)
+  {
+    diff =  my_id64 - ultimate_destination_finger_value;
+    if (1 == diff)
+      finger_table_index = PREDECESSOR_FINGER_ID;
+    else
+      finger_table_index = PREDECESSOR_FINGER_ID + 1; //error value
+    
+  }
+  else 
+  {
+    diff = ultimate_destination_finger_value - my_id64;
+    finger_table_index = (log10 (diff))/(log10 (2));
+  }
+  
+  return finger_table_index;
+}
+
+
+/**
+ * Remove finger and its associated data structures from finger table. 
+ * @param finger Finger to be removed.
+ */
+static void
+remove_existing_finger (struct FingerInfo *existing_finger, unsigned int finger_table_index)
+{
+  struct FriendInfo *friend;
+  struct FingerInfo *finger;
+  
+  finger = &finger_table[finger_table_index];
+  GNUNET_assert (GNUNET_YES == finger->is_present);
+  
+  /* If I am my own finger, then we have no trails. */
+  if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger->finger_identity,
+                                            &my_identity))
+  {
+    finger->is_present = GNUNET_NO;
+    memset ((void *)&finger_table[finger_table_index], 0, sizeof (finger_table[finger_table_index]));
+    return;
+  }
+  
+  /* If finger is a friend, then decrement the trail count and free the finger. */
+  friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                              &finger->finger_identity);
+  if (NULL != friend)
+  {
+    friend->trails_count--;
+    finger->is_present = GNUNET_NO;
+    memset ((void *)&finger_table[finger_table_index], 0, sizeof (finger_table[finger_table_index]));
+    return;
+  }
+  
+  /* For all other fingers, send trail teardown across all the trails to reach
+   finger, and free the finger. */
+  send_all_finger_trails_teardown (finger);
+  free_finger (finger, finger_table_index);
+  return;
+}
+
+#if 0
+/**
+ * This is a test function to print all the entries of friend table.
+ */
+static void
+test_friend_peermap_print ()
+{
+  struct FriendInfo *friend;
+  struct GNUNET_CONTAINER_MultiPeerMapIterator *friend_iter;
+  struct GNUNET_PeerIdentity print_peer;
+  struct GNUNET_PeerIdentity key_ret;
+  int i;
+  
+  friend_iter = GNUNET_CONTAINER_multipeermap_iterator_create (friend_peermap);
+  
+  for (i = 0; i < GNUNET_CONTAINER_multipeermap_size (friend_peermap); i++)
+  {
+    if(GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next (friend_iter,
+                                                                  &key_ret,
+                                                                  (const void **)&friend))
+    {
+      memcpy (&print_peer, &key_ret, sizeof (struct GNUNET_PeerIdentity));
+      FPRINTF (stderr,_("\nSUPU %s, %s, %d, friend = %s, friend->trails_count = %d"),
+              __FILE__, __func__,__LINE__, GNUNET_i2s(&print_peer), friend->trails_count);
+    }
+  }
+}
+
+
+/**
+ * This is a test function, to print all the entries of finger table.
+ */
+static void
+test_finger_table_print()
+{
+  struct FingerInfo *finger;
+  struct GNUNET_PeerIdentity print_peer;
+  struct Trail *trail;
+  int i;
+  int j;
+  int k;
+  
+  FPRINTF (stderr,_("\nSUPU************  FINGER_TABLE"));
+  for (i = 0; i < MAX_FINGERS; i++)
+  {
+    finger = &finger_table[i];
+    
+    if (GNUNET_NO == finger->is_present)
+      continue;
+    
+    print_peer = finger->finger_identity;
+    FPRINTF (stderr,_("\nSUPU %s, %s, %d, finger_table[%d] = %s, trails_count = %d"),
+            __FILE__, __func__,__LINE__,i,GNUNET_i2s (&print_peer), finger->trails_count);
+    
+    
+    for (j = 0; j < finger->trails_count; j++)
+    {
+      trail = &finger->trail_list[j];
+      FPRINTF (stderr,_("\nSUPU %s, %s, %d, trail_id[%d]=%s"),__FILE__, __func__,__LINE__,j, GNUNET_h2s(&trail->trail_id));
+      struct Trail_Element *element;
+      element = trail->trail_head;
+      for (k = 0; k < trail->trail_length; k++)
+      {  
+        print_peer = element->peer;
+        FPRINTF (stderr,_("\nSUPU %s, %s, %d,trail[%d] = %s "),__FILE__, __func__,__LINE__,k, GNUNET_i2s(&print_peer));
+        element = element->next;
+      }
+    }
+  }
+}
+#endif
+
+/**
+ * Check if there is already an entry in finger_table at finger_table_index.
+ * We get the finger_table_index from 64bit finger value we got from the network.
+ * -- If yes, then select the closest finger.
+ *   -- If new and existing finger are same, then check if you can store more 
+ *      trails. 
+ *      -- If yes then add trail, else keep the best trails to reach to the 
+ *         finger. 
+ *   -- If the new finger is closest, remove the existing entry, send trail
+ *      teardown message across all the trails to reach the existing entry.
+ *      Add the new finger.
+ *  -- If new and existing finger are different, and existing finger is closest
+ *     then do nothing.  
+ * -- Update current_search_finger_index.
+ * @param finger_identity Peer Identity of new finger
+ * @param finger_trail Trail to reach the new finger
+ * @param finger_length Total number of peers in @a new_finger_trail.
+ * @param is_predecessor Is this entry for predecessor in finger_table?
+ * @param finger_value 64 bit value of finger identity that we got from network.
+ * @param finger_trail_id Unique identifier of @finger_trail.
+ */
+static void
+finger_table_add (struct GNUNET_PeerIdentity finger_identity, 
+                  const struct GNUNET_PeerIdentity *finger_trail, 
+                  unsigned int finger_trail_length,
+                  unsigned int is_predecessor,
+                  uint64_t finger_value,
+                  struct GNUNET_HashCode finger_trail_id)
+{
+  struct FingerInfo *existing_finger;
+  struct GNUNET_PeerIdentity *closest_peer;
+  struct GNUNET_PeerIdentity *updated_trail;
+  struct FingerInfo *successor;
+  int updated_finger_trail_length; 
+  unsigned int finger_table_index;
+  
+  //test_friend_peermap_print();
+  //test_finger_table_print();
+  
+  /* Get the finger_table_index corresponding to finger_value we got from network.*/
+  finger_table_index = get_finger_table_index (finger_value, is_predecessor);
+
+  /* Invalid finger_table_index. */
+  if ((finger_table_index > PREDECESSOR_FINGER_ID))
+  {
+    GNUNET_break_op (0);
+    return;
+  }
+  
+  updated_finger_trail_length = finger_trail_length;
+  updated_trail =
+       scan_and_compress_trail (finger_identity, finger_trail,
+                                finger_trail_length, finger_trail_id, 
+                                &updated_finger_trail_length);
+   
+  /* If the new entry is same as successor then don't add it in finger table,
+   reset the current search finger index and exit. */
+  if ((0 != finger_table_index) && 
+      (PREDECESSOR_FINGER_ID != finger_table_index) &&
+      (finger_table_index == current_search_finger_index))
+  {
+    successor = &finger_table[0];
+    GNUNET_assert (GNUNET_YES == successor->is_present);
+    if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger_identity,
+                                              &successor->finger_identity))
+    {
+      current_search_finger_index = 0;
+      return;
+    }
+  }
+  
+  existing_finger = &finger_table[finger_table_index];
+  
+  /* No entry present in finger_table for given finger map index. */
+  if (GNUNET_NO == existing_finger->is_present)
+  {
+    add_new_finger (finger_identity, updated_trail, updated_finger_trail_length,
+                    finger_trail_id, finger_table_index);
+    update_current_search_finger_index (finger_identity, finger_table_index);
+    return;
+  }
+  
+  /* If existing entry and finger identity are not same. */
+  if (0 != GNUNET_CRYPTO_cmp_peer_identity (&(existing_finger->finger_identity),
+                                            &finger_identity))
+  {
+    closest_peer = select_closest_peer (&existing_finger->finger_identity,
+                                        &finger_identity,
+                                        finger_value, finger_table_index);
+    
+    /* If the new finger is the closest peer. */
+    if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger_identity, closest_peer))
+    {
+      remove_existing_finger (existing_finger, finger_table_index);
+      add_new_finger (finger_identity, updated_trail, updated_finger_trail_length,
+                      finger_trail_id, finger_table_index);
+    }
+  }
+  else
+  {
+    /* If both new and existing entry are same as my_identity, then do nothing. */
+    if (0 == GNUNET_CRYPTO_cmp_peer_identity (&(existing_finger->finger_identity),
+                                              &my_identity))
+      return;
+    
+    /* If the existing finger is not a friend. */
+    if (NULL ==
+        GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                           &existing_finger->finger_identity))
+    {
+      /* If there is space to store more trails. */
+      if (existing_finger->trails_count < MAXIMUM_TRAILS_PER_FINGER)
+        add_new_trail (existing_finger, updated_trail,
+                       finger_trail_length, finger_trail_id);
+      else
+        select_and_replace_trail (existing_finger, updated_trail,
+                                  finger_trail_length, finger_trail_id);
+    }
+  }
+  update_current_search_finger_index (finger_identity, finger_table_index);
+  return;
 }
 
 
 /**
- * Core handler for P2P put messages. 
+ * Core handler for P2P put messages.
  * @param cls closure
  * @param peer sender of the request
  * @param message message
  * @return #GNUNET_OK to keep the connection open,
  *         #GNUNET_SYSERR to close it (signal serious error)
  */
-static int 
+static int
 handle_dht_p2p_put (void *cls, const struct GNUNET_PeerIdentity *peer,
                     const struct GNUNET_MessageHeader *message)
 {
-  struct PeerPutMessage *put;
+   struct PeerPutMessage *put;
   struct GNUNET_PeerIdentity *put_path;
   struct GNUNET_HashCode test_key;
   enum GNUNET_DHT_RouteOption options;
-  struct GNUNET_PeerIdentity current_destination;
-  struct GNUNET_PeerIdentity current_source;
+  struct GNUNET_PeerIdentity best_known_dest;
+  struct GNUNET_HashCode intermediate_trail_id;
   struct GNUNET_PeerIdentity *next_hop;
   void *payload;
   size_t msize;
@@ -2975,11 +3351,12 @@ handle_dht_p2p_put (void *cls, const struct GNUNET_PeerIdentity *peer,
     return GNUNET_YES;
   }
 
-  current_destination = put->current_destination;
-  current_source = put->current_source;
+  best_known_dest = put->best_known_destination;
   put_path = (struct GNUNET_PeerIdentity *) &put[1];
   payload = &put_path[putlen];
   options = ntohl (put->options);
+  intermediate_trail_id = put->intermediate_trail_id;
+  
   payload_size = msize - (sizeof (struct PeerPutMessage) + 
                           putlen * sizeof (struct GNUNET_PeerIdentity));
   
@@ -3031,9 +3408,8 @@ handle_dht_p2p_put (void *cls, const struct GNUNET_PeerIdentity *peer,
     }
   }
   
-   struct GNUNET_PeerIdentity pp[putlen + 1];
   /* extend 'put path' by sender */
-  /* FIXME: Check what are we doing here? */
+  struct GNUNET_PeerIdentity pp[putlen + 1];
   if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
   {
     memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
@@ -3044,44 +3420,52 @@ handle_dht_p2p_put (void *cls, const struct GNUNET_PeerIdentity *peer,
     putlen = 0;
   
   memcpy (&key_value, &(put->key), sizeof (uint64_t));
-  if (0 != (GNUNET_CRYPTO_cmp_peer_identity (&current_destination, &my_identity)))
+  if (0 != (GNUNET_CRYPTO_cmp_peer_identity (&best_known_dest, &my_identity)))
   {
-    GDS_ROUTING_print();
-    next_hop = GDS_ROUTING_search (&current_source, &current_destination, peer);
-    if (next_hop == NULL)
-    {
-       /* refer to handle_dht_p2p_trail_setup. */
-    }
+    next_hop = GDS_ROUTING_get_next_hop (intermediate_trail_id, 
+                                         GDS_ROUTING_SRC_TO_DEST);
   }
   else
   {
-    next_hop = find_successor (key_value, &current_destination, &current_source,PUT_GET_REQUEST); 
+    next_hop = find_successor (key_value, &best_known_dest, 
+                               &intermediate_trail_id, GDS_FINGER_TYPE_NON_PREDECESSOR); 
   }
   
+  if (NULL == next_hop)
+  {
+    GNUNET_STATISTICS_update (GDS_stats,
+                              gettext_noop ("# Next hop to forward the packet not found "
+                              "trail setup request, packet dropped."),
+                              1, GNUNET_NO);
+    return GNUNET_SYSERR;
+  }
+  
+  GDS_CLIENTS_process_put (options,
+                           ntohl (put->block_type),
+                           ntohl (put->hop_count),
+                           ntohl (put->desired_replication_level),
+                           putlen, pp,
+                           GNUNET_TIME_absolute_ntoh (put->expiration_time),
+                           &put->key,
+                           payload,
+                           payload_size);
+  
   if (0 == GNUNET_CRYPTO_cmp_peer_identity(&my_identity, next_hop)) /* I am the final destination */
   {
     GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (put->expiration_time),
                               &(put->key),putlen, pp, ntohl (put->block_type), 
                               payload_size, payload);
-     return GNUNET_YES;
+    return GNUNET_YES;
   }
   else
   {
-    GDS_CLIENTS_process_put (options,
-                              ntohl (put->block_type),
-                              ntohl (put->hop_count),
-                              ntohl (put->desired_replication_level),
-                              putlen, pp,
-                              GNUNET_TIME_absolute_ntoh (put->expiration_time),
-                              &put->key,
-                              payload,
-                              payload_size);
-    GDS_NEIGHBOURS_send_put (&put->key, payload, payload_size, 
+    GDS_NEIGHBOURS_send_put (&put->key,  
                              ntohl (put->block_type),ntohl (put->options),
                              ntohl (put->desired_replication_level),
+                             &best_known_dest, &intermediate_trail_id, next_hop,
+                             ntohl (put->hop_count), putlen, pp,
                              GNUNET_TIME_absolute_ntoh (put->expiration_time),
-                             current_destination, current_source, next_hop,
-                             ntohl (put->hop_count), putlen, pp);
+                             payload, payload_size);
  
      return GNUNET_YES;
   }
@@ -3104,8 +3488,8 @@ handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
 {
   struct PeerGetMessage *get;
   struct GNUNET_PeerIdentity *get_path;
-  struct GNUNET_PeerIdentity current_destination;
-  struct GNUNET_PeerIdentity current_source;
+  struct GNUNET_PeerIdentity best_known_dest;
+  struct GNUNET_HashCode intermediate_trail_id;
   struct GNUNET_PeerIdentity *next_hop;
   uint32_t get_length;
   uint64_t key_value;
@@ -3120,9 +3504,9 @@ handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
   
   get = (struct PeerGetMessage *)message;
   get_length = ntohl (get->get_path_length);
+  best_known_dest = get->best_known_destination;
+  intermediate_trail_id = get->intermediate_trail_id;
   get_path = (struct GNUNET_PeerIdentity *)&get[1];
-  current_destination = get->current_destination;
-  current_source = get->current_source;
   
   if ((msize <
        sizeof (struct PeerGetMessage) +
@@ -3133,7 +3517,7 @@ handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
     GNUNET_break_op (0);
     return GNUNET_YES; 
   }
-
+  
   /* Add sender to get path */
   struct GNUNET_PeerIdentity gp[get_length + 1];
   memcpy (gp, get_path, get_length * sizeof (struct GNUNET_PeerIdentity));
@@ -3141,20 +3525,25 @@ handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
   get_length = get_length + 1;
   
   memcpy (&key_value, &(get->key), sizeof (uint64_t));
-  if (0 != (GNUNET_CRYPTO_cmp_peer_identity (&current_destination, &my_identity)))
+  if (0 != (GNUNET_CRYPTO_cmp_peer_identity (&best_known_dest, &my_identity)))
   {
-    GDS_ROUTING_print();
-    next_hop = GDS_ROUTING_search (&current_source, &current_destination, peer);
-    if (next_hop == NULL)
-    {
-       /* refer to handle_dht_p2p_trail_setup. */
-    }
+    next_hop = GDS_ROUTING_get_next_hop (intermediate_trail_id, 
+                                         GDS_ROUTING_SRC_TO_DEST);
   }
   else
   {
-    next_hop = find_successor (key_value, &current_destination, &current_source,PUT_GET_REQUEST);  
+    next_hop = find_successor (key_value, &best_known_dest, 
+                               &intermediate_trail_id, GDS_FINGER_TYPE_NON_PREDECESSOR);  
   }
   
+  if (NULL == next_hop)
+  {
+    GNUNET_STATISTICS_update (GDS_stats,
+                              gettext_noop ("# Next hop to forward the packet not found "
+                              "trail setup request, packet dropped."),
+                              1, GNUNET_NO);
+    return GNUNET_SYSERR;
+  }
   if (0 == GNUNET_CRYPTO_cmp_peer_identity(&my_identity, next_hop))
   {
     /* I am the destination.*/
@@ -3167,14 +3556,14 @@ handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
     memcpy (&next_hop, &final_get_path[get_length-2], sizeof (struct GNUNET_PeerIdentity));
     GDS_DATACACHE_handle_get (&(get->key),(get->block_type), NULL, 0, NULL, 0,
                               get_length, final_get_path,&next_hop, &my_identity);
-
+    
     return GNUNET_YES;
   }
   else
   {
     GDS_NEIGHBOURS_send_get (&(get->key), get->block_type, get->options, 
-                             get->desired_replication_level,current_destination,
-                             current_source, next_hop, 0,
+                             get->desired_replication_level, &best_known_dest,
+                             &intermediate_trail_id, next_hop, 0,
                              get_length, gp);  
   }
   return GNUNET_SYSERR;
@@ -3182,9 +3571,6 @@ handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
 
 
 /**
- * FIXME: In case of trail, we don't have source and destination part of the trail,
- * Check if we follow the same in case of get/put/get_result. Also, in case of 
- * put should we do a routing table add.
  * Core handler for get result
  * @param cls closure
  * @param peer sender of the request
@@ -3230,12 +3616,12 @@ handle_dht_p2p_get_result (void *cls, const struct GNUNET_PeerIdentity *peer,
     return GNUNET_YES;
   }
   
-  get_path = (struct GNUNET_PeerIdentity *) &get_result[1];
+  if (getlen > 0)
+   get_path = (struct GNUNET_PeerIdentity *) &get_result[1];
   payload = &get_path[getlen];
   payload_size = msize - (sizeof (struct PeerGetResultMessage) + 
                           getlen * sizeof (struct GNUNET_PeerIdentity));
-  /* FIXME: Check if its correct or not. */
-
+  
   if (putlen > 0)
     put_path = &get_path[1];
   else
@@ -3250,20 +3636,17 @@ handle_dht_p2p_get_result (void *cls, const struct GNUNET_PeerIdentity *peer,
   }
   else
   {
-    struct GNUNET_PeerIdentity *next_hop;
-    next_hop = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
-    /* FIXME: handle the case when current_path_index = GNUNET_SYSERR;*/
     current_path_index = search_my_index (get_path, getlen);
-    /* FIXME: First check if you are adding yourself to the get path or not.
-     if yes then don't check if current_path_index == 0, if not then check 
-     and next_hop == source_peer. */
-    memcpy (next_hop, &get_path[current_path_index - 1], sizeof (struct GNUNET_PeerIdentity));
-  
-    GDS_NEIGHBOURS_send_get_result (get_result->expiration_time, &(get_result->key),
-                                     putlen, put_path,
-                                     get_result->type, payload_size,payload,
-                                     get_path, getlen,
-                                     next_hop, &(get_result->source_peer));
+    if (GNUNET_SYSERR == current_path_index )
+    {
+      GNUNET_break (0);
+      return GNUNET_SYSERR;
+    }
+    GDS_NEIGHBOURS_send_get_result (&(get_result->key), get_result->type,
+                                    &get_path[current_path_index - 1],
+                                    &(get_result->querying_peer), putlen, put_path,
+                                    getlen, get_path, get_result->expiration_time,
+                                    payload, payload_size);
     return GNUNET_YES;
   }  
   return GNUNET_SYSERR;
@@ -3271,488 +3654,876 @@ handle_dht_p2p_get_result (void *cls, const struct GNUNET_PeerIdentity *peer,
 
 
 /**
- * FIXME: URGENT: refactor it. 
- * FIXME; now we can make a new ds to store 2 peers and one value as we are
- * using it at two places. Will complete the logic and then add a new ds.
- * In case finger map index is 64 do we need to call find_closest_predecessor? 
- * Select the closest peer.
- * @param prev_hop
- * @param current_destination
- * @param current_source
- * @param value
- * @para finger_map_index
- * @return Peer which is closest, in case of error NULL.
+ * Get the best known next destination (local_dest) among your fingers, friends 
+ * and my identity. If @a current_dest is some other peer and not me, then 
+ * compare curent_dest and local_dest. 
+ * @param final_dest_finger_value Peer closest to this value will be
+ *                                @a local_best_known_dest
+ * @param local_best_known_dest[out] Updated to peer identity which is closest to
+ *                                   @a final_dest_finger_value.
+ * @param new_intermediate_trail_id In case @a local_best_known_dest is a finger,
+ *                                  then the trail id to reach to the finger
+ * @param is_predecessor Is source peer trying to setup trail to its predecessor
+ *                       or not.
+ * @param current_dest Peer which should get this message ultimately according
+ *                     to the peer which sent me this message. It could be me
+ *                     or some other peer. In case it is not me, then I am a part
+ *                     of trail to reach to that peer.
+ * @return 
  */
-struct GNUNET_PeerIdentity *
-select_closest_peer (const struct GNUNET_PeerIdentity *prev_hop,
-                     struct GNUNET_PeerIdentity *current_destination,
-                     struct GNUNET_PeerIdentity *current_source,
-                     uint64_t value,
-                     unsigned int finger_map_index)
+static struct GNUNET_PeerIdentity *
+get_local_best_known_next_hop (uint64_t final_dest_finger_value,
+                               struct GNUNET_PeerIdentity *local_best_known_dest,
+                               struct GNUNET_HashCode *new_intermediate_trail_id,
+                               struct GNUNET_HashCode intermediate_trail_id,
+                               unsigned int is_predecessor,
+                               struct GNUNET_PeerIdentity *current_dest)
 {
-  struct GNUNET_PeerIdentity *peer1;
-  struct GNUNET_PeerIdentity *peer2;
-  struct Sorting_List peers[3];
-  struct Sorting_List *closest_finger;
+  struct GNUNET_PeerIdentity *next_hop_to_local_best_known_dest;
   
-  peer1 = GDS_ROUTING_search (current_source, current_destination, prev_hop);
-  peer2 = find_successor (value, current_destination, current_source,finger_map_index);
+ /* Choose a local best known hop among your fingers, friends and you.  */
+  next_hop_to_local_best_known_dest = find_successor (final_dest_finger_value,
+                                                      local_best_known_dest,
+                                                      new_intermediate_trail_id,
+                                                      is_predecessor);
+
+  /* Are we just a part of a trail towards a finger (current_destination)? */
+  if (0 != (GNUNET_CRYPTO_cmp_peer_identity (&my_identity, current_dest)))
+  {
+    struct GNUNET_PeerIdentity *closest_peer;
+    
+    /* Select best successor among one found locally and current_destination 
+     * that we got from network.*/
+    closest_peer = select_closest_peer (local_best_known_dest,
+                                        current_dest,
+                                        final_dest_finger_value,
+                                        is_predecessor);
+    
+    /* Is current dest (end point of the trail of which I am a part) closest_peer? */
+    if (0 == GNUNET_CRYPTO_cmp_peer_identity (current_dest, closest_peer))
+    {
+      next_hop_to_local_best_known_dest = 
+              GDS_ROUTING_get_next_hop (intermediate_trail_id,
+                                        GDS_ROUTING_SRC_TO_DEST);
+      /* FIXME: Here we found next_hop NULL from routing table, but we still 
+       * have a next_hop from find_successor should we not break and choose that
+       * next_hop. */
+      if (NULL == next_hop_to_local_best_known_dest) 
+      {
+        GNUNET_break_op (0);
+        return NULL;
+      }
+      
+      local_best_known_dest =  current_dest;
+      *new_intermediate_trail_id = intermediate_trail_id;
+    }
+  }
   
-  /* SUPU TEST CODE */
-  struct GNUNET_PeerIdentity print_peer;
-  memcpy (&print_peer, &peer1, sizeof (struct GNUNET_PeerIdentity));
-  FPRINTF (stderr,_("\nSUPU  %s, %s, %d,routing_peer = %s"), __FILE__, __func__,__LINE__,GNUNET_i2s(&print_peer));
-  memcpy (&print_peer, &peer2, sizeof (struct GNUNET_PeerIdentity));
-  FPRINTF (stderr,_("\nSUPU  %s, %s, %d,find_successor_peer = %s"), __FILE__, __func__,__LINE__,GNUNET_i2s(&print_peer));
-  /* SUPU TEST CODE ENDS*/
-  if( (peer1 != NULL) && (peer2 != NULL))
-  {
-    /* Add peer 1 to the list. */
-    memcpy (&peers[0], &peer1, sizeof (uint64_t));
-    peers[0].type = FINGER;
-    peers[0].data = NULL;
-  
-    /* Add peer 2 to the list. */
-    memcpy (&peers[1], &peer1, sizeof (uint64_t));
-    peers[0].type = FRIEND;
-    peers[0].data = NULL;
-  
-    /* Add value to the list. */
-    memcpy (&peers[2], &peer1, sizeof (uint64_t));
-    peers[0].type = VALUE;
-    peers[0].data = NULL;
-  
-    qsort (&peers, 3, sizeof (struct Sorting_List), &compare_peer_id);
-    if (PREDECESSOR_FINGER_ID == finger_map_index)
-      closest_finger = find_closest_predecessor (peers, value, 3);
+  GNUNET_assert (NULL != next_hop_to_local_best_known_dest);
+  return next_hop_to_local_best_known_dest;
+}
+
+
+/* Core handle for PeerTrailSetupMessage.
+ * @param cls closure
+ * @param message message
+ * @param peer peer identity this notification is about
+ * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
+ */
+static int
+handle_dht_p2p_trail_setup (void *cls, const struct GNUNET_PeerIdentity *peer,
+                            const struct GNUNET_MessageHeader *message)
+{
+  const struct PeerTrailSetupMessage *trail_setup;
+  const struct GNUNET_PeerIdentity *trail_peer_list;
+  struct GNUNET_PeerIdentity *local_best_known_dest; 
+  struct GNUNET_PeerIdentity current_dest;
+  struct GNUNET_PeerIdentity *next_hop_towards_local_best_known_dest;
+  struct GNUNET_PeerIdentity next_peer;
+  struct FriendInfo *target_friend;
+  struct GNUNET_PeerIdentity source;
+  uint64_t final_dest_finger_val;
+  struct GNUNET_HashCode new_intermediate_trail_id;
+  struct GNUNET_HashCode intermediate_trail_id;
+  struct GNUNET_HashCode trail_id;
+  unsigned int is_predecessor;
+  uint32_t trail_length;
+  size_t msize;
+
+  msize = ntohs (message->size);
+  if (msize < sizeof (struct PeerTrailSetupMessage))
+  {
+    GNUNET_break_op (0);
+    return GNUNET_YES;
+  }
+
+  trail_setup = (const struct PeerTrailSetupMessage *) message;
+  trail_length = (msize - sizeof (struct PeerTrailSetupMessage))/
+                  sizeof (struct GNUNET_PeerIdentity);
+  if ((msize - sizeof (struct PeerTrailSetupMessage)) % 
+      sizeof (struct GNUNET_PeerIdentity) != 0)
+  {
+    GNUNET_break_op (0);
+    return GNUNET_OK;      
+  }           
+  
+  trail_peer_list = (const struct GNUNET_PeerIdentity *)&trail_setup[1];
+  current_dest = trail_setup->best_known_destination;
+  trail_id = trail_setup->trail_id;
+  final_dest_finger_val = 
+          GNUNET_ntohll (trail_setup->final_destination_finger_value);
+  source = trail_setup->source_peer;
+  is_predecessor = ntohl (trail_setup->is_predecessor);
+  intermediate_trail_id = trail_setup->intermediate_trail_id;
+  
+  /* Is my routing table full?  */
+  if (GNUNET_YES == GDS_ROUTING_threshold_reached())
+  {
+    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, peer);
+    GDS_NEIGHBOURS_send_trail_rejection (source, final_dest_finger_val,
+                                         my_identity, is_predecessor,
+                                         trail_peer_list, trail_length,
+                                         trail_id, target_friend,
+                                         CONGESTION_TIMEOUT);
+    return GNUNET_OK;
+  }
+
+  local_best_known_dest = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
+  
+  /* Get the next hop to forward the trail setup request. */
+  next_hop_towards_local_best_known_dest = 
+          get_local_best_known_next_hop (final_dest_finger_val, 
+                                         local_best_known_dest,
+                                         &new_intermediate_trail_id,
+                                         intermediate_trail_id,
+                                         is_predecessor,
+                                         &current_dest);
+  /* Am I the final destination? */
+  if (0 == (GNUNET_CRYPTO_cmp_peer_identity (local_best_known_dest,
+                                             &my_identity)))
+  {
+    /* If I was not the source of this message for which now I am destination */
+    if ((0 != GNUNET_CRYPTO_cmp_peer_identity (&source, &my_identity)) ||
+        (trail_length > 0))
+    {
+      GDS_ROUTING_add (trail_id, *peer, my_identity);
+    }
+    if (0 == trail_length)
+      memcpy (&next_peer, &source, sizeof (struct GNUNET_PeerIdentity));
+    else
+      memcpy (&next_peer, &trail_peer_list[trail_length-1], sizeof (struct GNUNET_PeerIdentity));
+
+    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_peer);
+    GDS_NEIGHBOURS_send_trail_setup_result (source,
+                                            my_identity,
+                                            target_friend, trail_length,
+                                            trail_peer_list,
+                                            final_dest_finger_val,
+                                            is_predecessor, trail_id);
+  }
+  else
+  {
+    /* Add yourself to list of peers. */
+    struct GNUNET_PeerIdentity peer_list[trail_length + 1];
+
+    memcpy (peer_list, trail_peer_list, trail_length * sizeof (struct GNUNET_PeerIdentity));
+    peer_list[trail_length] = my_identity;
+    target_friend = 
+            GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                               next_hop_towards_local_best_known_dest);
+    GDS_NEIGHBOURS_send_trail_setup (source,
+                                     final_dest_finger_val,
+                                     *local_best_known_dest,
+                                     target_friend, trail_length + 1, peer_list,
+                                     is_predecessor, trail_id,
+                                     &new_intermediate_trail_id);
+  }
+  GNUNET_free (local_best_known_dest);
+  GNUNET_free (next_hop_towards_local_best_known_dest);
+  return GNUNET_OK;
+}
+
+
+/* FIXME: here we are calculating my_index and comparing also in this function.
+   And we are doing it again here in this function. Re factor the code. */
+/**
+ * FIXME: Should we call this function everywhere in all the handle functions
+ * where we have a trail to verify from or a trail id. something like
+ * if prev hop is not same then drop the message. 
+ * Check if sender_peer and peer from which we should receive the message are
+ * same or different.
+ * @param trail_peer_list List of peers in trail
+ * @param trail_length Total number of peers in @a trail_peer_list
+ * @param sender_peer Peer from which we got the message. 
+ * @param finger_identity Finger to which trail is setup. It is not part of trail.
+ * @return #GNUNET_YES if sender_peer and peer from which we should receive the
+ *                    message are different.
+ *         #GNUNET_NO if sender_peer and peer from which we should receive the
+ *                    message are different. 
+ */
+static int
+is_sender_peer_correct (const struct GNUNET_PeerIdentity *trail_peer_list,
+                        unsigned int trail_length,
+                        const struct GNUNET_PeerIdentity *sender_peer,
+                        struct GNUNET_PeerIdentity finger_identity,
+                        struct GNUNET_PeerIdentity source_peer)
+{
+  int my_index;
+  
+  /* I am the source peer. */
+  if (0 == (GNUNET_CRYPTO_cmp_peer_identity (&source_peer,
+                                             &my_identity)))
+  {
+    /* Is the first element of the trail is sender_peer.*/
+    if (trail_length > 0)
+    {
+      if (0 != GNUNET_CRYPTO_cmp_peer_identity (&trail_peer_list[0],
+                                                sender_peer))
+        return GNUNET_NO;
+    }
     else
-      closest_finger = find_closest_successor (peers, value, 3);
+    {
+      /* Is finger the sender peer? */
+      if (0 != GNUNET_CRYPTO_cmp_peer_identity (sender_peer,
+                                                &finger_identity))
+        return GNUNET_NO;
+    }
+  }
+  else
+  {
+    /* Get my current location in the trail. */
+    my_index = search_my_index (trail_peer_list, trail_length);
+    if (-1 == my_index)
+      return GNUNET_NO;
     
-    /* SUPU TEST CODE*/
-    if (closest_finger->type == FINGER)
+    /* I am the last element in the trail. */
+    if ((trail_length - 1) == my_index)
     {
-      FPRINTF (stderr,_("\nSUPU  %s, %s, %d"), __FILE__, __func__,__LINE__);
-      return peer2;
+      /* Is finger the sender_peer? */
+      if (0 != GNUNET_CRYPTO_cmp_peer_identity (sender_peer,
+                                                &finger_identity))
+        return GNUNET_NO;
     }
-    else if (closest_finger->type == VALUE)
-    { 
-      return NULL;
+    else
+    {
+      /* Is peer after me in trail the sender peer? */
+      if (0 != GNUNET_CRYPTO_cmp_peer_identity (sender_peer,
+                                                &trail_peer_list[my_index + 1]))
+        return GNUNET_NO;
     }
-    else if (closest_finger->type == FRIEND);
+  }
+  return GNUNET_YES;
+}
+
+
+/**
+ * FIXME: we should also add a case where we search if we are present in the trail
+ * twice.
+ * Core handle for p2p trail setup result messages.
+ * @param closure
+ * @param message message
+ * @param peer sender of this message. 
+ * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
+ */
+static int
+handle_dht_p2p_trail_setup_result(void *cls, const struct GNUNET_PeerIdentity *peer,
+                                  const struct GNUNET_MessageHeader *message)
+{
+  const struct PeerTrailSetupResultMessage *trail_result;
+  const struct GNUNET_PeerIdentity *trail_peer_list;
+  struct GNUNET_PeerIdentity next_hop;
+  struct FriendInfo *target_friend;
+  struct GNUNET_PeerIdentity querying_peer;
+  struct GNUNET_PeerIdentity finger_identity;
+  uint32_t trail_length;
+  uint64_t ulitmate_destination_finger_value;
+  uint32_t is_predecessor;
+  struct GNUNET_HashCode trail_id;
+  int my_index;
+  size_t msize;
+
+  msize = ntohs (message->size);
+  if (msize < sizeof (struct PeerTrailSetupResultMessage))
+  {
+    GNUNET_break_op (0);
+    return GNUNET_YES;
+  }
+
+  trail_result = (const struct PeerTrailSetupResultMessage *) message;
+  trail_length = (msize - sizeof (struct PeerTrailSetupResultMessage))/
+                  sizeof (struct GNUNET_PeerIdentity);
+  if ((msize - sizeof (struct PeerTrailSetupResultMessage)) % 
+      sizeof (struct GNUNET_PeerIdentity) != 0)
+  {
+    GNUNET_break_op (0);
+    return GNUNET_OK;      
+  }       
+  
+  is_predecessor = htonl (trail_result->is_predecessor);
+  querying_peer = trail_result->querying_peer;
+  finger_identity = trail_result->finger_identity;
+  trail_id = trail_result->trail_id;
+  trail_peer_list = (const struct GNUNET_PeerIdentity *) &trail_result[1];
+  ulitmate_destination_finger_value = 
+          GNUNET_ntohll (trail_result->ulitmate_destination_finger_value);
+
+  /* FIXME: here we are calculating my_index and comparing also in this function.
+   And we are doing it again here in this function. Re factor the code. */
+  /* Ensure that sender peer is the peer from which we were expecting the message. */
+  if (GNUNET_NO == is_sender_peer_correct (trail_peer_list,
+                                           trail_length,
+                                           peer, finger_identity, querying_peer))
+  {
+    GNUNET_break_op (0);
+    return GNUNET_SYSERR;
+  }
+  
+  /* Am I the one who initiated the query? */
+  if (0 == (GNUNET_CRYPTO_cmp_peer_identity (&querying_peer,
+                                             &my_identity)))
+  {
+    /* If I am not my own finger identity, then add routing table entry. */
+    if (0 != GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &finger_identity))
     {
-      /* If we are returning peer2 then find_successor has already taken care
-       of setting up current_destination and current_source. */
-      return peer1;  
+      GDS_ROUTING_add (trail_id, my_identity, *peer);
     }
+    
+    finger_table_add (finger_identity, trail_peer_list,
+                      trail_length, ulitmate_destination_finger_value,
+                      is_predecessor, trail_id);
+    return GNUNET_YES;
   }
-  else if ((peer1 == NULL) && (peer2 == NULL))
+  
+  /* Get my location in the trail. */
+  my_index = search_my_index(trail_peer_list, trail_length);
+  if (-1 == my_index)
   {
-    return NULL;
+    GNUNET_break_op(0);
+    return GNUNET_SYSERR;
   }
-  else if (peer1 == NULL)
+  
+  if (my_index == 0)
+    next_hop = trail_result->querying_peer;
+  else
+    next_hop = trail_peer_list[my_index - 1];
+
+  /* If the querying_peer is its own finger, then don't add an entry in routing
+   * table as querying peer will discard the trail. */
+  if (0 != (GNUNET_CRYPTO_cmp_peer_identity (&(trail_result->querying_peer),
+                                             &(trail_result->finger_identity))))
   {
-    return peer2;
+    GDS_ROUTING_add (trail_id, next_hop, *peer);
   }
-  else if (peer2 == NULL)
+
+  target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop);
+  GDS_NEIGHBOURS_send_trail_setup_result (querying_peer, finger_identity,
+                                          target_friend, trail_length, trail_peer_list,
+                                          is_predecessor, 
+                                          ulitmate_destination_finger_value,
+                                          trail_id);
+  return GNUNET_OK;
+}
+
+
+/**
+ * Invert the trail.
+ * @param trail Trail to be inverted
+ * @param trail_length Total number of peers in the trail.
+ * @return Updated trail
+ */
+static struct GNUNET_PeerIdentity *
+invert_trail (const struct GNUNET_PeerIdentity *trail,
+              unsigned int trail_length)
+{
+  int i;
+  int j;
+  struct GNUNET_PeerIdentity *inverted_trail;
+  inverted_trail = GNUNET_malloc (sizeof(struct GNUNET_PeerIdentity) *
+                                  trail_length);
+  i = 0;
+  j = trail_length - 1;
+  while (i < trail_length)
   {
-    return peer1;
+    inverted_trail[i] = trail[j];
+    i++;
+    j--;
+  }
+  return inverted_trail;
+}
+
+
+/**
+ * Return the shortest trail to reach from me to my_predecessor. 
+ * @param my_predecessor my current predecessor.
+ * @param current_trail Trail from source to me.
+ * @param current_trail_length Total number of peers in @a current_trail
+ * @param trail_length [out] Total number of peers in selected trail.
+ * @return Updated trail from source peer to my_predecessor.
+ */
+static struct GNUNET_PeerIdentity *
+trail_source_to_my_predecessor (const struct GNUNET_PeerIdentity *current_trail,
+                                unsigned int current_trail_length,
+                                unsigned int *trail_length)
+{
+  struct GNUNET_PeerIdentity *trail_me_to_predecessor;
+  struct Trail *trail;
+  struct Trail_Element *trail_element;
+  struct FingerInfo *my_predecessor;
+  unsigned int i;
+  unsigned int shortest_trail_length = 0;
+  unsigned int trail_index = 0;
+  my_predecessor = &finger_table[PREDECESSOR_FINGER_ID];
+  
+  GNUNET_assert (GNUNET_YES == my_predecessor->is_present);
+  
+  //if my_predecessor is a friend then don't send back any trail. as
+  // there is no trail. 
+  *trail_length = 0;
+  
+  /* Choose the shortest path from me to my predecessor. */
+  for (i = 0; i < my_predecessor->trails_count; i++)
+  {
+    trail = &my_predecessor->trail_list[i];
+    if (trail->trail_length > shortest_trail_length)
+      continue;
+    shortest_trail_length = trail->trail_length;
+    trail_index = i;
+  }
+
+  *trail_length = shortest_trail_length;
+  trail_me_to_predecessor = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity)
+                                          * *trail_length);
+  
+  /* Copy the selected trail and send this trail to calling function. */
+  i = 0;
+  trail = &my_predecessor->trail_list[trail_index];
+  trail_element = trail->trail_head;
+  while ( i < shortest_trail_length)
+  {
+    trail_me_to_predecessor[i] = trail_element->peer;
+    i++;
+    trail_element = trail_element->next;
+  }
+
+  return trail_me_to_predecessor;
+}
+
+
+/**
+ * FIXME In case predecessor is a friend then do we add it in routing table.
+ * if not then check the logic of trail teardown in case we compress the trail
+ * such that friend is finger. then do we remove the entry from end points or
+ * not. Ideally we should remove the entries from end point. 
+ * Add finger as your predecessor. To add, first generate a new trail id, invert
+ * the trail to get the trail from me to finger, add an entry in your routing 
+ * table, send add trail message to peers which are part of trail from me to 
+ * finger and add finger in finger table.
+ * @param finger
+ * @param trail
+ * @param trail_length
+ */
+static void
+update_predecessor (struct GNUNET_PeerIdentity finger, 
+                    struct GNUNET_PeerIdentity *trail, 
+                    unsigned int trail_length)
+{
+  struct GNUNET_HashCode trail_to_new_predecessor_id;
+  struct GNUNET_PeerIdentity *trail_to_new_predecessor;
+  struct FriendInfo *target_friend;
+  
+  /* Generate trail id for trail from me to new predecessor = finger. */
+  GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_STRONG,
+                              &trail_to_new_predecessor_id, 
+                              sizeof (trail_to_new_predecessor_id));
+    
+  /* Invert the trail from finger to me to get the trail from me to finger. */
+  if (trail_length == 0)
+    trail_to_new_predecessor = NULL;
+
+  if (trail_length > 0)
+  {
+    trail_to_new_predecessor = invert_trail (trail, trail_length);
+    /* Add an entry in your routing table. */
+    GDS_ROUTING_add (trail_to_new_predecessor_id, 
+                     trail_to_new_predecessor[trail_length - 1],
+                     my_identity);
+   
+    target_friend = 
+            GNUNET_CONTAINER_multipeermap_get (friend_peermap, 
+                                               &trail_to_new_predecessor[trail_length - 1]);
+      
+    // Before sending the trail may be you need to compress it. And in case
+    // it was a friend how did we got the trail. ?? 
+    
+    /* Add entry in routing table of all peers that are part of trail from me
+       to finger. */
+
+    GDS_NEIGHBOURS_send_add_trail (my_identity, 
+                                   finger,
+                                   trail_to_new_predecessor_id,
+                                   trail_to_new_predecessor,
+                                   trail_length,
+                                   target_friend);
+    }
+  
+    add_new_finger (finger, trail_to_new_predecessor, trail_length,
+                    trail_to_new_predecessor_id, PREDECESSOR_FINGER_ID);
+}
+
+
+/* 3. In case you are successor, then 
+   *   3.1 check if you have a predecessor
+   *   3.2 if no predecessor, then add the source of this message as your
+   *       predecessor. To add, first you should generate a new trail id,
+   *       invert the trail, send add trail message across new trail, add
+   *       an entry in finger table. Now, destination also have routing
+   *       table entry so add in your routing table also.
+   *   3.3 If its closer than existing one, then do everything in step 1 and
+   *       free existing finger. 
+   *   3.3 If its same as the old one, then do nothing.
+   *   3.4 if its not same as old one, and between source and old one, old one
+   *       is the correct predecessor, then construct a trail from source 
+   *       to your old successor. scan the trail to remove duplicate entries.
+   * 4. send verify successor result, with trail id of trail from source to
+   * me. And also send the new trail from source to reach to its probable
+   * predecessor. */
+ /*
+   * 1. this function is called from both verify and notify.
+   * 2. so write in a way that it is used in both.
+   */
+/**
+ * Check if you have a predecessor.
+ * 1. if no predecessor, then add finger as your predecessor. To add, first 
+ *    generate a new trail id, invert the trail to get the trail from me to finger,
+ *    add an entry in your routing table, send add trail message to peers which 
+ *    are part of trail from me to finger and add finger in finger table.
+ * 2. If there is a predecessor, then compare existing one and finger.
+ *    2.1 If finger is correct predecessor, then remove current_predecessor. And 
+ *        do everything in step 1 to add finger into finger table.
+ *    2.2 If current_predecessor is correct predecessor, the construct a trail from
+ *        finger to current_predecessor. 
+ * @param finger
+ * @param trail
+ * @param trail_length
+ * @return 
+ */
+static void
+compare_and_update_predecessor (struct GNUNET_PeerIdentity finger, 
+                                struct GNUNET_PeerIdentity *trail, 
+                                unsigned int trail_length)
+{
+  struct FingerInfo *current_predecessor;
+  struct GNUNET_PeerIdentity *closest_peer;
+  uint64_t predecessor_value;
+  
+  current_predecessor = &finger_table[PREDECESSOR_FINGER_ID];
+
+  /* No predecessor. Add finger as your predecessor. */
+  if (GNUNET_NO == current_predecessor->is_present) 
+  {
+    update_predecessor (finger, trail, trail_length);
+    return;
+  }
+  
+  predecessor_value = compute_finger_identity_value (PREDECESSOR_FINGER_ID);
+  closest_peer = select_closest_peer (&finger, 
+                                      &current_predecessor->finger_identity,
+                                      predecessor_value, PREDECESSOR_FINGER_ID);
+  
+  /* Finger is the closest predecessor. Remove the existing one and add the new
+     one. */
+  if (0 == GNUNET_CRYPTO_cmp_peer_identity (closest_peer, &finger))
+  {
+    remove_existing_finger (current_predecessor, PREDECESSOR_FINGER_ID);
+    update_predecessor (finger, trail, trail_length);
+    return;
   }
-  return NULL;
+  return;
 }
 
 
-/** 
- * Core handle for PeerTrailSetupMessage. 
+/* 
+ * FIXME: if i have no predecessor and I get a new predecessor but the first
+ * friend to reach to that hop is congested then?  
+ * 1. check if you are the successor or not.
+ * 2. if not then get the next hop from routing table, and pass the message,
+ * 3. In case you are successor, then 
+ *   3.1 check if you have a predecessor
+ *   3.2 if no predecessor, then add the source of this message as your
+ *       predecessor. To add, first you should generate a new trail id,
+ *       invert the trail, send add trail message across new trail, add
+ *       an entry in finger table. Now, destination also have routing
+ *       table entry so add in your routing table also.
+ *   3.3 If its closer than existing one, then do everything in step 1 and
+ *       free existing finger. 
+ *   3.3 If its same as the old one, then do nothing.
+ *   3.4 if its not same as old one, and between source and old one, old one
+ *       is the correct predecessor, then choose the shortest path to reach
+ *       from you to your predecessor. Pass this trail to source of this message.
+ *       It is the responsibility of source peer to scan the trail to reach to
+ *       its new probable successor. 
+ * 4. send verify successor result, with trail id of trail from source to
+ * me. And also send the  trail from me to reach to my predecessor, if
+ * my_predecessor != source. 
+ *
+ * Core handle for p2p verify successor messages.
  * @param cls closure
  * @param message message
  * @param peer peer identity this notification is about
  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
  */
 static int
-handle_dht_p2p_trail_setup (void *cls, const struct GNUNET_PeerIdentity *peer,
-                            const struct GNUNET_MessageHeader *message)
+handle_dht_p2p_verify_successor(void *cls, 
+                                const struct GNUNET_PeerIdentity *peer,
+                                const struct GNUNET_MessageHeader *message)
 {
-  const struct PeerTrailSetupMessage *trail_setup; 
-  struct GNUNET_PeerIdentity current_destination;
-  struct GNUNET_PeerIdentity current_source;
-  struct GNUNET_PeerIdentity source;
+  const struct PeerVerifySuccessorMessage *vsm;
+  struct GNUNET_HashCode trail_id;
+  struct GNUNET_PeerIdentity successor;
+  struct GNUNET_PeerIdentity source_peer;
+  struct GNUNET_PeerIdentity *trail;
   struct GNUNET_PeerIdentity *next_hop;
-  struct GNUNET_PeerIdentity next_peer;
-  struct GNUNET_PeerIdentity *trail_peer_list;
+  struct GNUNET_PeerIdentity *trail_to_predecessor;
+  struct FingerInfo *current_predecessor;
   struct FriendInfo *target_friend;
-  uint64_t destination_finger_value;
-  uint32_t trail_length;
-  uint32_t finger_map_index;
+  unsigned int trail_to_predecessor_length;
   size_t msize;
-
+  unsigned int trail_length;
+  
   msize = ntohs (message->size);
-  if (msize < sizeof (struct PeerTrailSetupMessage))
+  
+  /* Here we pass trail to reach from source to successor, and in case successor
+   * does not have any predecessor, then we will add source as my predecessor.
+   * So we pass the trail along with trail id. */
+  if (msize < sizeof (struct PeerVerifySuccessorMessage)) 
   {
     GNUNET_break_op (0);
     return GNUNET_YES;
   }
   
-  trail_setup = (const struct PeerTrailSetupMessage *) message; 
-  trail_length = ntohl (trail_setup->trail_length); 
-  if ((msize < sizeof (struct PeerTrailSetupMessage) +
-       trail_length * sizeof (struct GNUNET_PeerIdentity)) ||
-       (trail_length >
-        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
+  vsm = (const struct PeerVerifySuccessorMessage *) message;
+  trail_length = (msize - sizeof (struct PeerVerifySuccessorMessage))/
+                  sizeof (struct GNUNET_PeerIdentity);
+  if ((msize - sizeof (struct PeerVerifySuccessorMessage)) % 
+      sizeof (struct GNUNET_PeerIdentity) != 0)
   {
     GNUNET_break_op (0);
-    return GNUNET_OK; 
-  }
+    return GNUNET_OK;      
+  } 
   
-  if (trail_length > 0)
-    trail_peer_list = (struct GNUNET_PeerIdentity *)&trail_setup[1];
-  memcpy (&current_destination, &(trail_setup->current_destination), sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&current_source,&(trail_setup->current_source), sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&source, &(trail_setup->source_peer), sizeof (struct GNUNET_PeerIdentity));
-  finger_map_index = ntohl (trail_setup->finger_map_index);
-  destination_finger_value = ntohl (trail_setup->destination_finger);
-  
-  /* Check your routing table size, and if you can handle any more trails through you. */
-  if (GNUNET_YES == GDS_ROUTING_check_threshold())
-  {
-    GDS_NEIGHBOURS_send_trail_rejection (&source, destination_finger_value, &my_identity,
-                                         peer, finger_map_index, trail_peer_list, trail_length);
-    return GNUNET_OK;
-  }
+  trail_id = vsm->trail_id;
+  source_peer = vsm->source_peer;
+  successor = vsm->successor;
+  trail = (struct GNUNET_PeerIdentity *)&vsm[1];
   
-   /* Check if you are current_destination or not. */
-  if (0 != (GNUNET_CRYPTO_cmp_peer_identity (&current_destination, &my_identity)))
-  {
-    next_hop = select_closest_peer (peer, &current_destination, &current_source,
-                                    destination_finger_value, finger_map_index);
-  }
-  else
-  {
-    next_hop = find_successor (destination_finger_value, &current_destination, 
-                               &current_source,finger_map_index); 
-  } 
+  //GDS_ROUTING_test_print(); //FIXME REMOVE AFTERWARDS. 
+  //FIXME: we can have a check if peer is correct peer which should have
+  // sent this message. use same function is_sender_peer_correct
+  // but specify direction so that the function can be used in other functions
+  //also. 
   
-  if (NULL == next_hop)
-  {
-    GNUNET_STATISTICS_update (GDS_stats,
-                                gettext_noop ("# Trail not found in routing table during"
-                                "trail setup request, packet dropped."),
-                                1, GNUNET_NO);
-    return GNUNET_SYSERR;
-  }
-  else if (0 == (GNUNET_CRYPTO_cmp_peer_identity (next_hop, &my_identity)))/* This means I am the final destination */
+  /* I am not the successor of source_peer. Pass the message to next_hop on
+   * the trail. */
+  if(0 != (GNUNET_CRYPTO_cmp_peer_identity (&successor, &my_identity)))
   {
-    if (trail_length == 0)
-    {
-      memcpy (&next_peer, &source, sizeof (struct GNUNET_PeerIdentity));
-    }
-    else
+    next_hop = GDS_ROUTING_get_next_hop (trail_id, GDS_ROUTING_SRC_TO_DEST);
+    if (NULL == next_hop)
     {
-      memcpy (&next_peer, &trail_peer_list[trail_length-1], sizeof (struct GNUNET_PeerIdentity));
+      GNUNET_break (0);
+      return GNUNET_SYSERR;
     }
-    
-    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_peer);
-    GDS_NEIGHBOURS_send_trail_setup_result (&source,
-                                            &(my_identity),
-                                            target_friend, trail_length,
-                                            trail_peer_list,
-                                            finger_map_index);
-    return GNUNET_OK;
-  }
-  else
-  {
-    /* Now add yourself to the trail. */
-    struct GNUNET_PeerIdentity peer_list[trail_length + 1];
-    if (trail_length != 0)
-      memcpy (peer_list, trail_peer_list, trail_length * sizeof (struct GNUNET_PeerIdentity));
-    peer_list[trail_length] = my_identity;
-    trail_length++;
     target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
-    GDS_NEIGHBOURS_send_trail_setup (&source,
-                                     destination_finger_value,
-                                     &current_destination, &current_source,
-                                     target_friend, trail_length, peer_list, 
-                                     finger_map_index);
-     return GNUNET_OK;
-  }
-}
-
 
-/**
- * Core handle for p2p trail construction result messages.
- * @param closure
- * @param message message
- * @param peer peer identity this notification is about
- * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
- */
-static int
-handle_dht_p2p_trail_setup_result(void *cls, const struct GNUNET_PeerIdentity *peer,
-                                  const struct GNUNET_MessageHeader *message)
-{
-  const struct PeerTrailSetupResultMessage *trail_result;
-  struct GNUNET_PeerIdentity *trail_peer_list;
-  struct GNUNET_PeerIdentity destination_peer;
-  struct GNUNET_PeerIdentity finger_identity;    
-  uint32_t trail_length;
-  uint32_t finger_map_index;
-  size_t msize;
-  
-  msize = ntohs (message->size);
-  if (msize < sizeof (struct PeerTrailSetupResultMessage))
-  {
-    GNUNET_break_op (0);
-    return GNUNET_YES;
-  }
-  
-  trail_result = (const struct PeerTrailSetupResultMessage *) message; 
-  trail_length = ntohl (trail_result->trail_length); 
-  
-  if ((msize <
-       sizeof (struct PeerTrailSetupResultMessage) +
-       trail_length * sizeof (struct GNUNET_PeerIdentity)) ||
-       (trail_length >
-        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
-  {
-    GNUNET_break_op (0);
-    return GNUNET_YES;
+    GDS_NEIGHBOURS_send_verify_successor_message (source_peer, successor,
+                                                  trail_id, trail, trail_length,
+                                                  target_friend);
+    return GNUNET_OK;
   }
   
-  finger_map_index = htonl (trail_result->finger_map_index);
-  memcpy (&destination_peer, &(trail_result->destination_peer), sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&finger_identity, &(trail_result->finger_identity), sizeof (struct GNUNET_PeerIdentity));
-  
-  if (trail_length > 0)
-    trail_peer_list = (struct GNUNET_PeerIdentity *) &trail_result[1];
+  /* I am the destination of this message. */
   
+  /* Check if there is a predecessor or not. */
+  compare_and_update_predecessor (source_peer, trail, trail_length);
   
-  if (0 == (GNUNET_CRYPTO_cmp_peer_identity (&(trail_result->destination_peer),
-                                             &my_identity)))
+  current_predecessor = &finger_table[PREDECESSOR_FINGER_ID];
+  /* Is source of this message my predecessor. */
+  if (0 == (GNUNET_CRYPTO_cmp_peer_identity (&current_predecessor->finger_identity,
+                                             &source_peer)))
   {
-    finger_table_add (&(trail_result->finger_identity), trail_peer_list, trail_length, 
-                      finger_map_index);
-    return GNUNET_YES;
+    trail_to_predecessor = NULL;
+    trail_to_predecessor_length = 0;
   }
   else
   {
-    struct GNUNET_PeerIdentity next_hop;
-    struct FriendInfo *target_friend;
-    int my_index;
-    
-    my_index =  search_my_index (trail_peer_list, trail_length);
-    if (my_index == GNUNET_SYSERR)
-      return GNUNET_SYSERR;
-    
-    if (my_index == 0)
+    if (NULL == (GNUNET_CONTAINER_multipeermap_get (friend_peermap, 
+                                                    &current_predecessor->finger_identity)))
     {
-      next_hop = trail_result->destination_peer;
+      /* Only if current predecessor is not a friend, we have a trail to reach
+       to it. Only in that case we pass the trail. */
+      trail_to_predecessor = 
+            trail_source_to_my_predecessor (trail, trail_length, 
+                                            &trail_to_predecessor_length);
     }
     else
-      next_hop = trail_peer_list[my_index - 1];
-  
-    if (0 != (GNUNET_CRYPTO_cmp_peer_identity (&(trail_result->destination_peer),
-                                               &(trail_result->finger_identity))))
     {
-      struct GNUNET_PeerIdentity *routing_next_hop;
-      
-      routing_next_hop = GDS_ROUTING_search (&destination_peer,&finger_identity,
-                                             peer);
-      if ((NULL == routing_next_hop) || 
-          (0 != GNUNET_CRYPTO_cmp_peer_identity(routing_next_hop, &next_hop)))
-      {
-        GDS_ROUTING_add (&(trail_result->destination_peer), &(trail_result->finger_identity),
-                         peer, &next_hop);
-      }
-      GDS_ROUTING_print();
+      trail_to_predecessor = NULL;
+      trail_to_predecessor_length = 0;
     }
-    
-    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop);
-    GDS_NEIGHBOURS_send_trail_setup_result (&(trail_result->destination_peer),
-                                            &(trail_result->finger_identity),
-                                            target_friend, trail_length,
-                                            trail_peer_list,
-                                            finger_map_index);
-    return GNUNET_YES;
   }
-  return GNUNET_SYSERR;
+  
+  target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, peer);
+  GDS_NEIGHBOURS_send_verify_successor_result (source_peer, my_identity,
+                                               current_predecessor->finger_identity,
+                                               trail_id, trail_to_predecessor,
+                                               trail_to_predecessor_length,
+                                               GDS_ROUTING_DEST_TO_SRC,
+                                               target_friend);
+  return GNUNET_OK;
 }
 
 
 /**
- * Get my current predecessor from the finger peer map
- * @return Current predecessor.
+ * Construct the trail from me to probable successor that goes through current 
+ * successor. Scan this trail to check if you can shortcut the trail somehow. 
+ * In case we can shortcut the trail, don't send trail compression as we don't 
+ * have any entry in routing table.
+ * @param current_successor
+ * @param probable_successor
+ * @param trail_from_curr_to_probable_successor
+ * @param trail_from_curr_to_probable_successor_length
+ * @param trail_to_new_successor_length
+ * @return 
  */
-static struct FingerInfo *
-get_predecessor()
+static struct GNUNET_PeerIdentity *
+get_trail_to_new_successor (struct FingerInfo *current_successor,
+                            struct GNUNET_PeerIdentity probable_successor,
+                            const struct GNUNET_PeerIdentity *trail,
+                            unsigned int trail_length,
+                            unsigned int *trail_to_new_successor_length)
 {
-  struct GNUNET_CONTAINER_MultiPeerMapIterator *finger_iter;
-  struct GNUNET_PeerIdentity key_ret;
-  unsigned int finger_index;
-  struct FingerInfo *my_predecessor;
-  int flag = 0;
-  /* Iterate over finger peer map and extract your predecessor. */
-  finger_iter = GNUNET_CONTAINER_multipeermap_iterator_create (finger_peermap);  
-  for (finger_index = 0; finger_index < GNUNET_CONTAINER_multipeermap_size (finger_peermap); finger_index++)
-  {
-    if(GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next 
-                       (finger_iter,&key_ret,(const void **)&my_predecessor)) 
-    {
-      if(PREDECESSOR_FINGER_ID == my_predecessor->finger_map_index)
-      {
-        flag = 1;
-        break;
-      }
-    }
-  }
-  GNUNET_CONTAINER_multipeermap_iterator_destroy (finger_iter);
-  
-  if (0 == flag)
-    return NULL;
-  else
-    return my_predecessor;
+  struct GNUNET_PeerIdentity *trail_to_new_successor;
+  
+   /* If the probable successor is a friend, then we don't need to have a trail
+    * to reach to it.*/
+  if (NULL != GNUNET_CONTAINER_multipeermap_get (friend_peermap, 
+                                                 &probable_successor))
+  {
+    trail_to_new_successor = NULL;
+    *trail_to_new_successor_length = 0;
+    return trail_to_new_successor;
+  }
+  
+  /*
+   * FIXME: can we some how use the select_finger_trail here?? 
+   * complete this logic. 
+   * 1. Choose the shortest trail to reach to current successor.
+   * 2. append the trail with the current trail
+   * 3. scan the trail for duplicate elements
+   * 4. scan the trail for friend
+   * 5. get the shortest trail. 
+   * 6. send back the trail.
+   */
+  return NULL;
 }
 
 
 /**
- * Core handle for p2p verify successor messages.
- * @param cls closure
- * @param message message
- * @param peer peer identity this notification is about
- * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
+ * Compare probable successor and current successor.
+ * If the probable successor is the correct successor, then construct the trail
+ * from me to probable successor that goes through current successor. Scan this
+ * trail to check if you can shortcut the trail somehow. In case we can short
+ * cut the trail, don't send trail compression as we don't have any entry in 
+ * routing table.
+ * Once you have scanned trail, then add an entry in finger table.
+ * Add an entry in routing table (Only if new successor is NOT a friend).
+ * @param probable_successor Peer which could be our successor
+ * @param trail_from_curr_to_probable_successor Trail from current successor 
+ *                                               to probable successor, NOT 
+ *                                               including them.
+ * @param trail_from_curr_to_probable_successor_length Total number of peers
+ *                                               in @a trail_from_curr_to_probable_successor
  */
-static int
-handle_dht_p2p_verify_successor(void *cls, const struct GNUNET_PeerIdentity *peer,
-                                const struct GNUNET_MessageHeader *message)
+static void
+compare_and_update_successor (struct GNUNET_PeerIdentity probable_successor,
+                              const struct GNUNET_PeerIdentity *trail_from_curr_to_probable_successor,
+                              unsigned int trail_from_curr_to_probable_successor_length)
 {
-  const struct PeerVerifySuccessorMessage *vsm;
-  const struct GNUNET_PeerIdentity *trail_peer_list;
-  struct GNUNET_PeerIdentity source_peer;
-  struct GNUNET_PeerIdentity next_hop;
+  struct GNUNET_PeerIdentity *closest_peer;
+  struct GNUNET_PeerIdentity *trail_to_new_successor;
+  struct GNUNET_HashCode trail_id;
+  unsigned int trail_to_new_successor_length;
+  uint64_t successor_value;
+  struct FingerInfo *current_successor;
   struct FriendInfo *target_friend;
-  size_t msize;
-  uint32_t trail_length;
-   
-  msize = ntohs (message->size);
-  if (msize < sizeof (struct PeerVerifySuccessorMessage))
-  {
-    GNUNET_break_op (0);
-    return GNUNET_YES;
-  }
   
-  vsm = (struct PeerVerifySuccessorMessage *) message;
-  trail_length = ntohl (vsm->trail_length);
+  current_successor = &finger_table[0];
+  GNUNET_assert (GNUNET_YES == current_successor->is_present);
   
-  if ((msize < sizeof (struct PeerVerifySuccessorMessage) +
-               trail_length * sizeof (struct GNUNET_PeerIdentity)) ||
-      (trail_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
-  {
-    GNUNET_break_op (0);
-    return GNUNET_YES;
-  }
-  if (trail_length > 0)
-    trail_peer_list = (const struct GNUNET_PeerIdentity *)&vsm[1];
-  memcpy (&source_peer, &(vsm->source_peer), sizeof(struct GNUNET_PeerIdentity));
+  /* Compute the 64 bit value of successor identity. We need this as we need to
+   * find the closest peer w.r.t this value.*/
+  successor_value = compute_finger_identity_value (0);
+  closest_peer = select_closest_peer (&current_successor->finger_identity,
+                                      &probable_successor,
+                                      successor_value, GNUNET_NO);
+  
+  /* If the current_successor is the closest one, then exit. */
+  if (0 == GNUNET_CRYPTO_cmp_peer_identity (closest_peer,
+                                            &current_successor->finger_identity))
+    return;
+  
+  /* probable successor  is the closest_peer. */
+  
+  /* Get the trail to reach to your new successor. */
+  trail_to_new_successor = get_trail_to_new_successor (current_successor,
+                                                       probable_successor,
+                                                       trail_from_curr_to_probable_successor,
+                                                       trail_from_curr_to_probable_successor_length,
+                                                       &trail_to_new_successor_length);
+  /* Remove the existing successor. */
+  remove_existing_finger (current_successor, 0);
+  
+  /* Generate a new trail id to reach to your new successor. */
+  GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_STRONG,
+                              &trail_id, sizeof (trail_id));
+  add_new_finger (probable_successor, trail_to_new_successor, 
+                  trail_to_new_successor_length, trail_id, 0);
   
-  if(0 == (GNUNET_CRYPTO_cmp_peer_identity (&(vsm->successor),&my_identity)))
+  /* If probable successor is not a friend, then add an entry in your own
+   routing table. */
+  if (trail_to_new_successor_length > 0)
   {
-    struct FingerInfo *my_predecessor;
-    if (trail_length == 0)
-    {
-      memcpy (&next_hop, &source_peer, sizeof (struct GNUNET_PeerIdentity));
-    }
-    else
-    {
-      memcpy (&next_hop, &trail_peer_list[trail_length-1], sizeof (struct GNUNET_PeerIdentity));
-    }
-    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop);
-    
-    my_predecessor = get_predecessor();
-    if (NULL == my_predecessor)
-    {
-      /* FIXME: should we just return. */
-      return GNUNET_OK;
-    }
-    
-    if (0 == (GNUNET_CRYPTO_cmp_peer_identity (&source_peer,
-                                               &(my_predecessor->finger_identity))))
-    {
-      /* Source peer and my predecessor, both are same. */
-      GDS_NEIGHBOURS_send_verify_successor_result (&source_peer,
-                                                   &(my_identity),
-                                                   &(my_predecessor->finger_identity),
-                                                   target_friend,
-                                                   trail_peer_list,
-                                                   trail_length);
-    }
-    else
-    {
-      struct GNUNET_PeerIdentity *new_successor_trail;
-      struct TrailPeerList *iterator;
-      int new_trail_length;
-      int i;
-
-      new_trail_length = trail_length + my_predecessor->first_trail_length + 1;
-      new_successor_trail = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity) * new_trail_length);
-      if (trail_length > 0)
-        memcpy (new_successor_trail, trail_peer_list, (trail_length) * sizeof (struct GNUNET_PeerIdentity));
-      
-      memcpy (&new_successor_trail[trail_length], &my_identity, sizeof (struct GNUNET_PeerIdentity));
-     
-      if (my_predecessor->first_trail_length)
-      {
-        iterator = GNUNET_malloc (sizeof (struct TrailPeerList));
-        iterator = my_predecessor->first_trail_head; 
-        i = trail_length + 1;
-        while (i < new_trail_length)
-        {
-          memcpy (&new_successor_trail[i], &(iterator->peer), sizeof (struct GNUNET_PeerIdentity));
-          iterator = iterator->next;
-          i++;
-        }
-      }
-      GDS_NEIGHBOURS_send_verify_successor_result (&source_peer,
-                                                   &(my_identity),
-                                                   &(my_predecessor->finger_identity),
-                                                   target_friend,
-                                                   new_successor_trail,
-                                                   new_trail_length); 
-    }      
-    
+    GDS_ROUTING_add (trail_id, my_identity, trail_to_new_successor[0]);
+    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, 
+                                                       &trail_to_new_successor[0]);
   }
   else
   {
-   int my_index;
-   
-   if (trail_length == 0)
-   {
-     GNUNET_break (0);
-     return GNUNET_SYSERR;
-   }
-   
-   my_index = search_my_index (trail_peer_list, trail_length);
-   if (my_index == GNUNET_SYSERR)
-   {
-     GNUNET_break (0);
-     return GNUNET_SYSERR;
-   }
-   if (my_index == (trail_length - 1))
-   {
-      target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &(vsm->successor));
-   }
-   else
-   {
-     memcpy (&next_hop, &trail_peer_list[my_index + 1], sizeof (struct GNUNET_PeerIdentity));
-     target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop);
-   }   
-
-   GDS_NEIGHBOURS_send_verify_successor (&(vsm->source_peer), &(vsm->successor),target_friend,
-                                          trail_peer_list, trail_length); 
+    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, 
+                                                       &probable_successor);
   }
-  return GNUNET_SYSERR;
+  
+  GDS_NEIGHBOURS_send_notify_new_successor (my_identity, probable_successor,
+                                            trail_from_curr_to_probable_successor,
+                                            trail_from_curr_to_probable_successor_length,
+                                            trail_id,
+                                            target_friend);
+  return;
 }
 
 
-/**
+/*
+ * 1. If you are not the querying peer then pass on the message,
+ * 2. If you are querying peer, then
+ *   2.1 is new successor same as old one
+ *     2.1.1 if yes then do noting
+ *     2.1.2 if no then you need to notify the new one about your existence,
+ *     2.1.2,1 also you need to remove the older successor, remove entry
+ *             from finger table, send trail teardown message across all the trail
+ *             of older successor. Call notify new successor with new trail id 
+ *             and new trail to reach it. 
  * Core handle for p2p verify successor result messages.
  * @param cls closure
  * @param message message
@@ -3760,92 +4531,80 @@ handle_dht_p2p_verify_successor(void *cls, const struct GNUNET_PeerIdentity *pee
  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
  */
 static int
-handle_dht_p2p_verify_successor_result(void *cls, const struct GNUNET_PeerIdentity *peer,
+handle_dht_p2p_verify_successor_result(void *cls, 
+                                       const struct GNUNET_PeerIdentity *peer,
                                        const struct GNUNET_MessageHeader *message)
 {
   const struct PeerVerifySuccessorResultMessage *vsrm;
-  struct GNUNET_PeerIdentity *trail_peer_list;
-  struct GNUNET_PeerIdentity next_hop;
+  enum GDS_ROUTING_trail_direction trail_direction;
+  struct GNUNET_PeerIdentity querying_peer;
+  struct GNUNET_HashCode trail_id;
+  struct GNUNET_PeerIdentity *next_hop;
   struct FriendInfo *target_friend;
+  struct GNUNET_PeerIdentity probable_successor;
+  const struct GNUNET_PeerIdentity *trail;
+  unsigned int trail_length;
   size_t msize;
-  uint32_t trail_length;
-  
+
   msize = ntohs (message->size);
+  /* We send a trail to reach from old successor to new successor, if
+   * old_successor != new_successor.*/
   if (msize < sizeof (struct PeerVerifySuccessorResultMessage))
   {
     GNUNET_break_op (0);
     return GNUNET_YES;
   }
+  
   vsrm = (const struct PeerVerifySuccessorResultMessage *) message;
-  trail_length = ntohl (vsrm->trail_length); 
+  trail_length = (msize - sizeof (struct PeerVerifySuccessorResultMessage))/
+                      sizeof (struct GNUNET_PeerIdentity);
   
-  if ((msize <
-       sizeof (struct PeerVerifySuccessorResultMessage) +
-       trail_length * sizeof (struct GNUNET_PeerIdentity)) ||
-       (trail_length >
-       GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
+  if ((msize - sizeof (struct PeerVerifySuccessorResultMessage)) % 
+      sizeof (struct GNUNET_PeerIdentity) != 0)
   {
     GNUNET_break_op (0);
-    return GNUNET_YES;
-  }
+    return GNUNET_OK;      
+  }  
   
-  if (trail_length > 0)
-    trail_peer_list = (struct GNUNET_PeerIdentity *) &vsrm[1];
+  trail = (const struct GNUNET_PeerIdentity *) &vsrm[1];
+  querying_peer = vsrm->querying_peer;
+  trail_direction = ntohl (vsrm->trail_direction);
+  trail_id = vsrm->trail_id;
+  probable_successor = vsrm->probable_successor;
   
-  if(0 == (GNUNET_CRYPTO_cmp_peer_identity (&(vsrm->destination_peer), &(my_identity))))
-  {
-    if(0 != (GNUNET_CRYPTO_cmp_peer_identity (&(vsrm->my_predecessor), &(my_identity))))
-    {
-      if (GNUNET_YES == finger_table_add (&(vsrm->my_predecessor), trail_peer_list, trail_length, 0))
-      {
-        memcpy (&next_hop, &trail_peer_list[0], sizeof (struct GNUNET_PeerIdentity));
-        target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop);
-        /* FIXME: first call scan_and_compress_trail and then call the notify new
-         successor with new trail. */
-        GDS_NEIGHBOURS_send_notify_new_successor (&my_identity, &(vsrm->my_predecessor),
-                                                  &(vsrm->source_successor),
-                                                  target_friend, trail_peer_list,
-                                                  trail_length);
-        return GNUNET_OK;
-      }
-      else
-        return GNUNET_OK;
-    }
-  }
-  else
+  //FIXME: add a check to ensure that peer from which you got the message is
+  //the correct peer.
+  /* I am the querying_peer. */
+  if(0 == (GNUNET_CRYPTO_cmp_peer_identity (&querying_peer, &my_identity)))
   {
-    int my_index;
-    
-    my_index = search_my_index (trail_peer_list, trail_length);
-    if (GNUNET_SYSERR == my_index)
-    {
-      GNUNET_break (0);
-      return GNUNET_SYSERR;
-    }
-    
-    if (my_index == 0)
-    {
-      memcpy (&next_hop, &(vsrm->destination_peer), sizeof (struct GNUNET_PeerIdentity));
-    }
-    else
-    {
-      memcpy (&next_hop, &trail_peer_list[my_index-1], sizeof (struct GNUNET_PeerIdentity));
-    }
-    
-    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop); 
-    GDS_NEIGHBOURS_send_verify_successor_result (&(vsrm->destination_peer),
-                                                 &(vsrm->source_successor),
-                                                 &(vsrm->my_predecessor),
-                                                 target_friend,
-                                                 trail_peer_list,
-                                                 trail_length); 
+    compare_and_update_successor (probable_successor, trail, trail_length);
     return GNUNET_OK;
   }
-  return GNUNET_SYSERR;
+  
+  /*If you are not the querying peer then pass on the message */
+  GNUNET_assert (NULL != (next_hop =
+                         GDS_ROUTING_get_next_hop (trail_id, trail_direction)));
+  target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
+  GDS_NEIGHBOURS_send_verify_successor_result (querying_peer,
+                                               vsrm->current_successor,
+                                               probable_successor, trail_id,
+                                               trail,
+                                               trail_length,
+                                               trail_direction, target_friend);
+  return GNUNET_OK;
 }
 
 
-/**
+/* 
+ * Add entry in your routing table if source of the message is not a friend.
+ * Irrespective if destination peer accepts source peer as predecessor or not, 
+ * we need to add an entry. So, that in next round to verify successor, source 
+ * is able to reach to its successor.
+ * Check if you are the new successor of this message
+ * 1. If yes the call function compare_and_update_successor(). This function
+ *    checks if source is real predecessor or not and take action accordingly.
+ * 2. If not then find the next hop to find the message from the trail that 
+ *    you got from the message and pass on the message.
  * Core handle for p2p notify new successor messages.
  * @param cls closure
  * @param message message
@@ -3853,465 +4612,554 @@ handle_dht_p2p_verify_successor_result(void *cls, const struct GNUNET_PeerIdenti
  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
  */
 static int
-handle_dht_p2p_notify_new_successor(void *cls, const struct GNUNET_PeerIdentity *peer,
+handle_dht_p2p_notify_new_successor(void *cls, 
+                                    const struct GNUNET_PeerIdentity *peer,
                                     const struct GNUNET_MessageHeader *message)
 {
   const struct PeerNotifyNewSuccessorMessage *nsm;
-  struct GNUNET_PeerIdentity *trail_peer_list;
-  struct GNUNET_PeerIdentity source_peer;
-  struct GNUNET_PeerIdentity old_successor;
+  struct GNUNET_PeerIdentity *trail;
+  struct GNUNET_PeerIdentity source;
   struct GNUNET_PeerIdentity new_successor;
+  struct GNUNET_HashCode trail_id;
+  struct GNUNET_PeerIdentity next_hop;
+  struct FriendInfo *target_friend;
+  int my_index;
   size_t msize;
   uint32_t trail_length;
-  
+
   msize = ntohs (message->size);
+  /* We have the trail to reach from source to new successor. */
   if (msize < sizeof (struct PeerNotifyNewSuccessorMessage))
   {
     GNUNET_break_op (0);
     return GNUNET_YES;
   }
+
   nsm = (const struct PeerNotifyNewSuccessorMessage *) message;
-  trail_length = ntohl (nsm->trail_length);
-  
-  if ((msize < sizeof (struct PeerNotifyNewSuccessorMessage) +
-               trail_length * sizeof (struct GNUNET_PeerIdentity)) ||
-      (trail_length >
-       GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
+  trail_length = (msize - sizeof (struct PeerNotifyNewSuccessorMessage))/
+                  sizeof (struct GNUNET_PeerIdentity);
+  if ((msize - sizeof (struct PeerTrailRejectionMessage)) % 
+      sizeof (struct GNUNET_PeerIdentity) != 0)
   {
     GNUNET_break_op (0);
-    return GNUNET_YES;
+    return GNUNET_OK;      
   }
   
-  if( trail_length > 0)
-    trail_peer_list = (struct GNUNET_PeerIdentity *) &nsm[1];
-  memcpy (&source_peer, &(nsm->source_peer), sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&old_successor, &(nsm->old_successor), sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&new_successor, &(nsm->destination_peer), sizeof (struct GNUNET_PeerIdentity));
+  trail = (struct GNUNET_PeerIdentity *) &nsm[1];
+  source  = nsm->source_peer;
+  new_successor = nsm->new_successor;
+  trail_id = nsm->trail_id;  
   
-  if(0 == (GNUNET_CRYPTO_cmp_peer_identity (&new_successor, &my_identity)))
+  //FIXME: add a check to make sure peer is correct. 
+  
+  /* I am the new_successor to source_peer. */
+  if ( 0 == GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &new_successor))
   {
-    /* I am the new successor. */
-    struct GNUNET_PeerIdentity *new_predecessor;
-    new_predecessor = GNUNET_new (struct GNUNET_PeerIdentity);
-    memcpy (new_predecessor, &(nsm->source_peer), sizeof (struct GNUNET_PeerIdentity));
-    if (GNUNET_YES == finger_table_add (new_predecessor, trail_peer_list, trail_length, PREDECESSOR_FINGER_ID))
+    /* Add an entry in routing table only if new predecessor is not a friend. */
+    if (NULL == GNUNET_CONTAINER_multipeermap_get(friend_peermap, &source))
     {
-      /* You are adding a new predecessor in your finger table. but the intermediate
-          peers don't have an entry in their routing table. So, you need to check the
-          return value of finger_table_Add and if its successful then you should send
-          routing_add_message. */
+      GDS_ROUTING_add (trail_id, *peer, my_identity);
     }
+    compare_and_update_predecessor (source, trail, trail_length);
     return GNUNET_OK;
   }
-  else
-  {
-    struct FriendInfo *target_friend;
-    struct GNUNET_PeerIdentity next_hop;
-    int my_index;
-    
-    if (trail_length == 0)
-      return GNUNET_SYSERR;
-    
-    my_index = search_my_index (trail_peer_list, trail_length);
-    if (GNUNET_SYSERR == my_index)
-    {
-      /* FIXME: happend once */
-      GNUNET_break(0);
-      return GNUNET_SYSERR;
-    }
-    
-    if (my_index == (trail_length - 1))
-    {
-      target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &(nsm->destination_peer));
-    }
-    else
-    {
-      memcpy (&next_hop, &trail_peer_list[my_index+1], sizeof (struct GNUNET_PeerIdentity));
-      target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop);
-    }
-
-    GDS_ROUTING_remove_trail (&source_peer, &old_successor, peer);
-    GDS_ROUTING_add (&(nsm->source_peer), &(nsm->destination_peer), &next_hop, peer);
-    GDS_NEIGHBOURS_send_notify_new_successor (&(nsm->source_peer), 
-                                              &(nsm->destination_peer),
-                                              &(nsm->old_successor),
-                                              target_friend, trail_peer_list,
-                                              trail_length);
-    return GNUNET_OK;
+  
+  /* I am part of trail to reach to successor. */
+  my_index = search_my_index (trail, trail_length);
+  if (-1 == my_index)
+  {
+    GNUNET_break_op (0);
+    return GNUNET_SYSERR;
   }
-  return GNUNET_SYSERR;
+  if (trail_length == my_index)
+    next_hop = new_successor;
+  else
+    next_hop = trail[my_index + 1];
+  
+  /* Add an entry in routing table for trail from source to its new successor. */
+  GNUNET_assert (GNUNET_OK == GDS_ROUTING_add (trail_id, *peer, next_hop));
+  target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop);
+  GDS_NEIGHBOURS_send_notify_new_successor (source, new_successor, trail,
+                                            trail_length,
+                                            trail_id, target_friend);
+  return GNUNET_OK;
+  
 }
 
+
 /**
- * FIXME: pass congestion time in struct PeerTrailRejectionMessage,
- * we are calling exact same thing here as in handle_dht_p2p_trail_seutp.set
- * that value here. 
- * if we make it a function then we can it here. 
- * Core handler for P2P trail rejection message 
+ * 1. Set the congestion timeout for the friend which is congested and sent
+ * you this message.
+ * 2. Check if you were the source of this message
+ *   2.1 If yes then exit. find_finger_trail_task is scheduled periodically.
+ *       So, we will eventually send a new request to setup trail to finger.
+ * 2. Check if you can handle more trails through you. (Routing table space)
+ *   2.1 If not then you are congested. Set your congestion time and pass this
+ *       message to peer before you in the trail setup so far. 
+ *   2.2 If yes, the call find_successor(). It will give you the next hop to 
+ *       pass this message.
+ *      2.2.1 If you are the final destination, then send back the trail setup 
+ *            result.
+ *      2.2.2 If you are not the final dest, then send trail setup message to
+ *            next_hop.
+ * Core handler for P2P trail rejection message
  * @param cls closure
  * @param message message
  * @param peer peer identity this notification is about
  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
  */
-static
-int handle_dht_p2p_trail_rejection(void *cls, const struct GNUNET_PeerIdentity *peer,
-                                   const struct GNUNET_MessageHeader *message)
+static int
+handle_dht_p2p_trail_setup_rejection (void *cls,
+                                      const struct GNUNET_PeerIdentity *peer,
+                                      const struct GNUNET_MessageHeader *message)
 {
   const struct PeerTrailRejectionMessage *trail_rejection;
-  struct GNUNET_PeerIdentity *trail_peer_list;
+  unsigned int trail_length;
+  const struct GNUNET_PeerIdentity *trail_peer_list;
   struct FriendInfo *target_friend;
-  struct GNUNET_PeerIdentity next_hop;
-  struct GNUNET_PeerIdentity *next_peer;
+  struct GNUNET_TIME_Relative congestion_timeout;
+  struct GNUNET_HashCode trail_id;
+  struct GNUNET_PeerIdentity next_destination;
+  struct GNUNET_HashCode new_intermediate_trail_id;
+  struct GNUNET_PeerIdentity next_peer;
   struct GNUNET_PeerIdentity source;
-  struct GNUNET_PeerIdentity current_destination;
-  struct GNUNET_PeerIdentity current_source;
-  uint32_t trail_length;
-  uint32_t finger_map_index;
-  uint64_t destination_finger_value;
+  struct GNUNET_PeerIdentity *next_hop;
+  uint64_t ultimate_destination_finger_value;
+  unsigned int is_predecessor;
   size_t msize;
-  
+
   msize = ntohs (message->size);
+  /* We are passing the trail setup so far. */
   if (msize < sizeof (struct PeerTrailRejectionMessage))
   {
     GNUNET_break_op (0);
     return GNUNET_YES;
   }
-  
-  trail_rejection = (struct PeerTrailRejectionMessage *) message;
-  trail_length = ntohl (trail_rejection->trail_length);
-  
-  if ((msize < sizeof (struct PeerTrailRejectionMessage) +
-               trail_length * sizeof (struct GNUNET_PeerIdentity)) ||
-      (trail_length >
-       GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
+
+  trail_rejection = (const struct PeerTrailRejectionMessage *) message;
+  trail_length = (msize - sizeof (struct PeerTrailRejectionMessage))/
+                  sizeof (struct GNUNET_PeerIdentity);
+  if ((msize - sizeof (struct PeerTrailRejectionMessage)) % 
+      sizeof (struct GNUNET_PeerIdentity) != 0)
   {
     GNUNET_break_op (0);
-    return GNUNET_YES;
-  }
-  
-  if (trail_length > 0)
-    trail_peer_list = (struct GNUNET_PeerIdentity *)&trail_rejection[1];
-  finger_map_index = ntohl (trail_rejection->finger_map_index);
-  memcpy (&destination_finger_value, &(trail_rejection->finger_identity_value), sizeof (uint64_t));
-  memcpy (&source, &(trail_rejection->source_peer), sizeof (struct GNUNET_PeerIdentity));
-  
+    return GNUNET_OK;      
+  }           
+
+  trail_peer_list = (const struct GNUNET_PeerIdentity *)&trail_rejection[1];
+  is_predecessor = ntohl (trail_rejection->is_predecessor);
+  congestion_timeout = trail_rejection->congestion_time;
+  source = trail_rejection->source_peer;
+  trail_id = trail_rejection->trail_id;
+  ultimate_destination_finger_value = 
+          GNUNET_ntohll (trail_rejection->ultimate_destination_finger_value);
+
   /* First set the congestion time of the friend that sent you this message. */
   target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, peer);
-  //FIXME: target_friend->congestion_time ==? 
-  
-  if(0 == (GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &(trail_rejection->source_peer))))
-  {
+  target_friend->congestion_timestamp = 
+          GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
+                                    congestion_timeout);
+
+  /* I am the source peer which wants to setup the trail. Do nothing. 
+   * send_find_finger_trail_task is scheduled periodically.*/
+  if(0 == (GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &source)))
     return GNUNET_OK;
-  }
-  
-  if(GNUNET_YES == GDS_ROUTING_check_threshold())
+
+  /* If I am congested then pass this message to peer before me in trail. */
+  if(GNUNET_YES == GDS_ROUTING_threshold_reached())
   {
     struct GNUNET_PeerIdentity *new_trail;
     unsigned int new_trail_length;
     
+    /* Remove yourself from the trail setup so far. */
     if (trail_length == 1)
     {
       new_trail = NULL;
       new_trail_length = 0;
-      memcpy (&next_hop, &(trail_rejection->source_peer), sizeof (struct GNUNET_PeerIdentity));
+      next_hop = &source;
     }
-    else 
+    else
     {
-      memcpy (&next_hop, &trail_peer_list[trail_length - 2], sizeof (struct GNUNET_PeerIdentity));
+      memcpy (&next_hop , &trail_peer_list[trail_length - 2], 
+              sizeof (struct GNUNET_PeerIdentity));
+      
       /* Remove myself from the trail. */
       new_trail_length = trail_length -1;
       new_trail = GNUNET_malloc (new_trail_length * sizeof (struct GNUNET_PeerIdentity));
       memcpy (new_trail, trail_peer_list, new_trail_length * sizeof (struct GNUNET_PeerIdentity));
     }
-    GDS_NEIGHBOURS_send_trail_rejection (&(trail_rejection->source_peer), 
-                                         destination_finger_value,
-                                         &my_identity, &next_hop,finger_map_index,
-                                         new_trail,new_trail_length);
-    return GNUNET_YES;
-  }
-  
-  {
-  memcpy (&current_destination, &my_identity, sizeof (struct GNUNET_PeerIdentity));
-  memcpy (&current_source, &my_identity, sizeof (struct GNUNET_PeerIdentity));
-  next_peer = find_successor (destination_finger_value,&current_destination,
-                             &current_source, finger_map_index);
-  if (NULL == next_peer)
-  {
-    GNUNET_STATISTICS_update (GDS_stats,
-                                gettext_noop ("# Trail not found in routing table during"
-                                "trail setup request, packet dropped."),
-                                1, GNUNET_NO);
-    return GNUNET_SYSERR;
+
+    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
+    GDS_NEIGHBOURS_send_trail_rejection (source,
+                                         ultimate_destination_finger_value,
+                                         my_identity, is_predecessor,
+                                         new_trail,new_trail_length,trail_id,
+                                         target_friend, CONGESTION_TIMEOUT);
+    GNUNET_free (new_trail);
+    return GNUNET_OK;
   }
-  else if (0 == (GNUNET_CRYPTO_cmp_peer_identity (next_peer, &my_identity)))/* This means I am the final destination */
-  {
-    if (trail_length == 0)
-    {
-      memcpy (&next_hop, &source, sizeof (struct GNUNET_PeerIdentity));
-    }
+
+  /* Look for next_hop to pass the trail setup message */
+  next_hop = find_successor (ultimate_destination_finger_value,
+                             &next_destination,
+                             &new_intermediate_trail_id,
+                             is_predecessor);
+  
+  /* Am I the final destination? */
+  if (0 == (GNUNET_CRYPTO_cmp_peer_identity (next_hop, &my_identity)))
+  {
+    /* Add an entry in routing table only 
+     * 1. If I am not the original source which sent the request for trail setup 
+     * 2. If trail length > 0. 
+     * NOTE: In case trail length > 0 and source is my friend, then also I add
+     *       an entry in routing table,as we will send a trail compression message
+     *       later.
+     */
+    if ((0 != GNUNET_CRYPTO_cmp_peer_identity (&source, &my_identity)) ||
+        (trail_length > 0))
+      GNUNET_assert (GNUNET_YES == GDS_ROUTING_add (trail_id, *peer, my_identity));
+    
+    if (0 == trail_length)
+      next_peer = source;
     else
-    {
-      memcpy (&next_hop, &trail_peer_list[trail_length-1], sizeof (struct GNUNET_PeerIdentity));
-    }
-    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop);
-    GDS_NEIGHBOURS_send_trail_setup_result (&source,
-                                            &(my_identity),
+      next_peer = trail_peer_list[trail_length-1];
+    
+    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_peer);
+    GDS_NEIGHBOURS_send_trail_setup_result (source,
+                                            my_identity,
                                             target_friend, trail_length,
                                             trail_peer_list,
-                                            finger_map_index);
-    return GNUNET_OK;
+                                            is_predecessor, 
+                                            ultimate_destination_finger_value,
+                                            trail_id);
   }
   else
   {
-    /* Now add yourself to the trail. */
     struct GNUNET_PeerIdentity peer_list[trail_length + 1];
-    if (trail_length != 0)
-      memcpy (peer_list, trail_peer_list, trail_length * sizeof (struct GNUNET_PeerIdentity));
+
+    memcpy (peer_list, trail_peer_list, trail_length * sizeof (struct GNUNET_PeerIdentity));
     peer_list[trail_length] = my_identity;
-    trail_length++;
-    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop);
-    GDS_NEIGHBOURS_send_trail_setup (&source,
-                                     destination_finger_value,
-                                     &current_destination, &current_source,
-                                     target_friend, trail_length, peer_list, 
-                                     finger_map_index);
-     return GNUNET_OK;
-  }
-  }
-  
+
+    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
+    GDS_NEIGHBOURS_send_trail_setup (source,
+                                     ultimate_destination_finger_value,
+                                     next_destination,
+                                     target_friend, trail_length + 1, peer_list,
+                                     is_predecessor, trail_id,
+                                     &new_intermediate_trail_id);
+  }
+  GNUNET_free (next_hop);
+  return GNUNET_OK;
 }
 
 
-/* FIXME: there is a loop between in call from notify new successor to this function
- * check why and fix it. 
- * Core handle for p2p trail tear down messages.
+/*
+ * If you are the new first friend, then update prev hop to source of this message
+ * else get the next hop and pass this message forward to ultimately reach
+ * new first_friend.
+ * Core handle for p2p trail tear compression messages.
  * @param cls closure
  * @param message message
  * @param peer peer identity this notification is about
  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
  */
-static
-int handle_dht_p2p_trail_teardown (void *cls, const struct GNUNET_PeerIdentity *peer,
-                                   const struct GNUNET_MessageHeader *message)
+static int
+handle_dht_p2p_trail_compression (void *cls, const struct GNUNET_PeerIdentity *peer,
+                                  const struct GNUNET_MessageHeader *message)
 {
-  struct PeerTrailTearDownMessage *trail_teardown;
-  struct GNUNET_PeerIdentity *discarded_trail;
-  struct GNUNET_PeerIdentity next_hop;
+  const struct PeerTrailCompressionMessage *trail_compression;
+  struct GNUNET_PeerIdentity *next_hop;
   struct FriendInfo *target_friend;
-  uint32_t discarded_trail_length;
+  struct GNUNET_HashCode trail_id;
   size_t msize;
-  int my_index;
-  
+
   msize = ntohs (message->size);
-  if (msize < sizeof (struct PeerTrailTearDownMessage))
+  /* Here we pass only the trail id. */
+  if (msize != sizeof (struct PeerTrailCompressionMessage))
   {
     GNUNET_break_op (0);
     return GNUNET_OK;
   }
   
-  trail_teardown = (struct PeerTrailTearDownMessage *) message;
-  discarded_trail_length = ntohl (trail_teardown->trail_length);
+  trail_compression = (const struct PeerTrailCompressionMessage *) message;
+  trail_id = trail_compression->trail_id;
+  //FIXME: again check if peer is the correct peer. same logic as 
+  //trail teardown make a generic function. 
   
-  if ((msize < sizeof (struct PeerTrailTearDownMessage) +
-               discarded_trail_length * sizeof (struct GNUNET_PeerIdentity)) ||
-      (discarded_trail_length >
-       GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
+  /* Am I the new first friend to reach to finger of this trail. */
+  if (0 == (GNUNET_CRYPTO_cmp_peer_identity (&(trail_compression->new_first_friend),
+                                             &my_identity)))
   {
-    GNUNET_break_op (0);
+    /* Update your prev hop to source of this message. */
+    GDS_ROUTING_update_trail_prev_hop (trail_id,
+                                       trail_compression->source_peer);
     return GNUNET_OK;
   }
   
-  if (discarded_trail_length > 0)
-  discarded_trail = (struct GNUNET_PeerIdentity *) &trail_teardown[1];
+  /* Pass the message to next hop to finally reach to new_first_friend. */
+  next_hop = GDS_ROUTING_get_next_hop (trail_id, GDS_ROUTING_SRC_TO_DEST);
+  if (NULL == next_hop)
+  {
+    GNUNET_break (0); 
+    return GNUNET_OK;
+  }
   
-  /* SUPU TEST CODE */
-  struct GNUNET_PeerIdentity print_peer;
-  int k = 0;
-  while ( k < discarded_trail_length)
+  GNUNET_assert (GNUNET_YES == GDS_ROUTING_remove_trail (trail_id));
+  target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
+  GDS_NEIGHBOURS_send_trail_compression (trail_compression->source_peer,
+                                         trail_id,
+                                         trail_compression->new_first_friend,
+                                         target_friend);
+  return GNUNET_OK;
+}
+
+
+/**
+ * Remove entry from your own routing table and pass the message to next
+ * peer in the trail. 
+ * Core handler for trail teardown message.
+ * @param cls closure
+ * @param message message
+ * @param peer sender of this messsage. 
+ * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
+ */
+static int
+handle_dht_p2p_trail_teardown (void *cls, const struct GNUNET_PeerIdentity *peer,
+                               const struct GNUNET_MessageHeader *message)
+{
+  const struct PeerTrailTearDownMessage *trail_teardown;
+  enum GDS_ROUTING_trail_direction trail_direction;
+  struct GNUNET_HashCode trail_id;
+  struct GNUNET_PeerIdentity *prev_hop;
+  struct GNUNET_PeerIdentity *next_hop;
+  size_t msize;
+  msize = ntohs (message->size);
+  /* Here we pass only the trail id. */
+  if (msize != sizeof (struct PeerTrailTearDownMessage))
   {
-    memcpy (&print_peer, &discarded_trail[k], sizeof (struct GNUNET_PeerIdentity));
-    FPRINTF (stderr,_("\nSUPU %s, %s, %d,discarded_trail[%d]=%s"),
-    __FILE__, __func__,__LINE__,k,GNUNET_i2s(&print_peer));
-    k++;
+    GNUNET_break_op (0);
+    return GNUNET_OK;
   }
-  /* SUPU TEST CODE ENDS*/
-  if (0 == (GNUNET_CRYPTO_cmp_peer_identity (&(trail_teardown->new_first_friend),
-                                             &my_identity)))
+  
+  trail_teardown = (const struct PeerTrailTearDownMessage *) message;
+  trail_direction = ntohl (trail_teardown->trail_direction);
+  trail_id = trail_teardown->trail_id;
+  
+  /* Check if peer is the real peer from which we should get this message.*/
+  /* Get the prev_hop for this trail by getting the next hop in opposite direction. */
+  /* FIXME: is using negation of trail direction correct. */
+  prev_hop = GDS_ROUTING_get_next_hop (trail_id, !trail_direction);
+  if (0 != GNUNET_CRYPTO_cmp_peer_identity (prev_hop, peer))
   {
-     if(0 == (GNUNET_CRYPTO_cmp_peer_identity (&(trail_teardown->destination_peer), 
-                                              &my_identity)))
-     {
-       return GNUNET_OK;
-     }
-     else
-     {
-        /* FIXME: 
-         * I am the new first hop in the trail to reach from source to destination.
-           Update the trail in routing table with prev_hop == source peer. */
-       return GDS_ROUTING_trail_update (&(trail_teardown->source_peer),
-                                        &(trail_teardown->destination_peer), peer);
-     }
+    GNUNET_break (0);
+    return GNUNET_SYSERR;
   }
-  else
+  GNUNET_free_non_null (prev_hop);
+  
+  next_hop = GDS_ROUTING_get_next_hop (trail_id, trail_direction);
+  if (NULL == next_hop)
   {
-    /* This should always be the case. */
-    if (discarded_trail_length > 0)
-    {
-      my_index = search_my_index (discarded_trail, discarded_trail_length);
-      if(GNUNET_SYSERR == my_index)
-        return GNUNET_SYSERR;
-    }
-    else
-    {
-      GNUNET_break (0);
-      return GNUNET_SYSERR;
-    }
-    GDS_ROUTING_print();
-    if (GNUNET_NO == GDS_ROUTING_remove_trail (&(trail_teardown->source_peer),
-                                               &(trail_teardown->destination_peer),peer))
-    {
-      /* Here we get GNUNET_NO, only if there is no matching entry found in routing
-         table. */
-      GNUNET_break (0);
-      return GNUNET_YES;
-    }  
-    
-    /* In case we got this message when we removed an entry from finger table,
-     then we need to send the message to destination. */
-    if (my_index != (discarded_trail_length - 1))
-      memcpy (&next_hop, &discarded_trail[my_index + 1], sizeof (struct GNUNET_PeerIdentity));
-    else
-      memcpy (&next_hop, &(trail_teardown->destination_peer), sizeof (struct GNUNET_PeerIdentity));
-    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop); 
-   
-    GDS_NEIGHBOURS_send_trail_teardown (&(trail_teardown->source_peer), 
-                                        &(trail_teardown->destination_peer),
-                                        discarded_trail, discarded_trail_length, 
-                                        target_friend, &(trail_teardown->new_first_friend));
-    return GNUNET_YES;
+    GNUNET_break (0);
+    return GNUNET_SYSERR;
   }
-  return GNUNET_SYSERR;
+  
+  GNUNET_assert (GNUNET_YES == GDS_ROUTING_remove_trail (trail_id));
+  
+  /* If next_hop is my_identity, it means I am the final destination. */
+  if (0 == GNUNET_CRYPTO_cmp_peer_identity (next_hop, &my_identity))
+    return GNUNET_OK;
+  
+  /* If not final destination, then send a trail teardown message to next hop.*/
+  GDS_NEIGHBOURS_send_trail_teardown (trail_id, trail_direction, next_hop);
+  GNUNET_free (next_hop);
+  return GNUNET_OK;
 }
 
+
 /**
- * Core handle for p2p routing table add messages.
+ * Add an entry in your routing table. If you are destination of this message
+ * then next_hop in routing table should be your own identity. If you are NOT
+ * destination, then get the next hop and forward message to it.
+ * Core handle for p2p add trail message. 
  * @param cls closure
  * @param message message
  * @param peer peer identity this notification is about
  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
  */
-static int 
+static int
 handle_dht_p2p_add_trail (void *cls, const struct GNUNET_PeerIdentity *peer,
-                                  const struct GNUNET_MessageHeader *message)
+                          const struct GNUNET_MessageHeader *message)
 {
-  /* This function is called in case when we update our predecessor as a new peer
-   claims to be our successor. In that case as we did not do a trail setup, 
-   intermediate nodes don't know about this trail. our predecessor has added 
-   that trail but not we. So, we need to add it. Its only in case of predecessor
-   and succcessor that we have a symmetric relation. */
-  struct PeerAddTrailMessage *add_trail;
-  struct GNUNET_PeerIdentity *trail;
+  const struct PeerAddTrailMessage *add_trail;
+  const struct GNUNET_PeerIdentity *trail;
+  struct GNUNET_HashCode trail_id;
+  struct GNUNET_PeerIdentity destination_peer;
+  struct GNUNET_PeerIdentity source_peer;
   struct GNUNET_PeerIdentity next_hop;
-  struct FriendInfo *target_friend;
+  unsigned int trail_length;
+  unsigned int my_index;
   size_t msize;
-  uint32_t trail_length;
-  int my_index;
-  
+
   msize = ntohs (message->size);
+  /* In this message we pass the whole trail from source to destination as we
+   * are adding that trail.*/
   if (msize < sizeof (struct PeerAddTrailMessage))
   {
     GNUNET_break_op (0);
     return GNUNET_OK;
   }
-  
-  add_trail = (struct PeerAddTrailMessage *) message;
-  trail_length = ntohl (add_trail->trail_length);
-  
-  if ((msize < sizeof (struct PeerAddTrailMessage) +
-               trail_length * sizeof (struct GNUNET_PeerIdentity)) ||
-      (trail_length >
-       GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
+
+  add_trail = (const struct PeerAddTrailMessage *) message;
+  trail_length = (msize - sizeof (struct PeerAddTrailMessage))/
+                  sizeof (struct GNUNET_PeerIdentity);
+  if ((msize - sizeof (struct PeerAddTrailMessage)) % 
+      sizeof (struct GNUNET_PeerIdentity) != 0)
   {
     GNUNET_break_op (0);
-    return GNUNET_OK;
-  }
-  
-  if (trail_length > 0)
-    trail = (struct GNUNET_PeerIdentity *)&add_trail[1];
-  
-  my_index = search_my_index (trail, trail_length);
-  if (GNUNET_SYSERR == my_index)
-  {
-    GNUNET_break (0);
-    return GNUNET_SYSERR;
-  }
-  if (my_index == 0)
-    memcpy(&next_hop, &(add_trail->source_peer), sizeof (struct GNUNET_PeerIdentity));
-  else
-    memcpy (&next_hop, &trail[my_index - 1], sizeof (struct GNUNET_PeerIdentity));
+    return GNUNET_OK;      
+  }           
+
+  trail = (const struct GNUNET_PeerIdentity *)&add_trail[1];
+  destination_peer = add_trail->destination_peer;
+  source_peer = add_trail->source_peer;
+  trail_id = add_trail->trail_id;
+
+  //FIXME: add a check that sender peer is not malicious. Make it a generic
+  // function so that it can be used in all other functions where we need the
+  // same functionality.
   
-  if (GNUNET_YES == GDS_ROUTING_add (&(add_trail->source_peer), &(add_trail->destination_peer),
-                                     peer,&next_hop))
+  /* I am not the destination of the trail. */
+  if (0 != GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &destination_peer))
   {
-    if (my_index != 0)
+    struct FriendInfo *target_friend;
+
+    /* Get my location in the trail. */
+    my_index = search_my_index (trail, trail_length);
+    if (GNUNET_SYSERR == my_index)
     {
-      target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop); 
-      GDS_NEIGHBOURS_send_add_trail_message (&(add_trail->source_peer), 
-                                             &(add_trail->destination_peer),
-                                             trail, trail_length,target_friend);
+      GNUNET_break_op (0);
+      return GNUNET_SYSERR;
     }
+
+    if (0 == my_index)
+      next_hop = source_peer;
+    else
+      next_hop = trail[trail_length - 1];
+    
+    /* Add in your routing table. */
+    GNUNET_assert (GNUNET_OK == GDS_ROUTING_add (trail_id, next_hop, *peer));
+    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop);
+    GDS_NEIGHBOURS_send_add_trail (source_peer, destination_peer, trail_id,
+                                   trail, trail_length, target_friend);
     return GNUNET_OK;
   }
-  else
-  {
-    /* FIXME: there is not space in routing table to add the trail. What should 
-     be done. */
-    return GNUNET_SYSERR;
-  }
+  
+  /* I am the destination. Add an entry in routing table. */
+  GNUNET_assert (GNUNET_OK == GDS_ROUTING_add (trail_id, *peer, my_identity));
+  return GNUNET_OK;
 }
 
 
 /**
- * FIXME: Adapt the code for List of trails. 
- * Iterate over finger_peermap, and remove entries with peer as the first element
- * of their trail.  
- * @param cls closure
- * @param key current public key
- * @param value value in the hash map
- * @return #GNUNET_YES if we should continue to
- *         iterate,
- *         #GNUNET_NO if not.
+ * Send trail teardown and free the finger trail in which the first
+ * friend to reach to a finger is disconnected_friend 
+ * @param disconnected_friend PeerIdentity of friend which got disconnected
+ * @param remove_finger Finger whose trail we need to check if it has 
+ *                      disconnected_friend as the first hop.
+ * @return Total number of trails in which disconnected_friend was the first
+ *         hop.
  */
 static int
-remove_matching_finger (void *cls,
-                        const struct GNUNET_PeerIdentity *key,
-                        void *value)
+remove_matching_trails (const struct GNUNET_PeerIdentity *disconnected_friend,
+                        struct FingerInfo *remove_finger)
 {
-  struct FingerInfo *remove_finger = value;
-  const struct GNUNET_PeerIdentity *disconnected_peer = cls;
+  unsigned int matching_trails_count;
+  int i;
   
-  if (remove_finger->first_trail_length > 0)
+  /* Number of trails with disconnected_friend as the first hop in the trail
+   * to reach from me to remove_finger, NOT including endpoints. */
+  matching_trails_count = 0;
+
+  /* Iterate over all the trails of finger. */
+  for (i = 0; i < remove_finger->trails_count; i++)
   {
-    if (0 == GNUNET_CRYPTO_cmp_peer_identity (&remove_finger->first_trail_head->peer, disconnected_peer))
+    struct Trail *trail;
+    trail = &remove_finger->trail_list[i];
+    
+    if (GNUNET_NO == trail->is_present)
+      continue;
+    
+    /* First friend to reach to finger is disconnected_peer. */
+    if (0 == GNUNET_CRYPTO_cmp_peer_identity (&trail->trail_head->peer,
+                                              disconnected_friend))
     {
-      GNUNET_assert (GNUNET_YES ==
-                   GNUNET_CONTAINER_multipeermap_remove (finger_peermap,
-                                                         key, 
-                                                         remove_finger));
-      free_finger (remove_finger);
+      matching_trails_count++;
+      send_trail_teardown (remove_finger, trail);
+      if (trail->trail_length > 0)
+      free_trail (trail);
     }
-  }
-  else if (0 == GNUNET_CRYPTO_cmp_peer_identity (&(remove_finger->finger_identity), 
-                                                 disconnected_peer))
-  {
-    GNUNET_assert (GNUNET_YES ==
-                   GNUNET_CONTAINER_multipeermap_remove (finger_peermap,
-                                                         key, 
-                                                         remove_finger));
-    free_finger (remove_finger);
-  }
+  }  
+  return matching_trails_count;
+}
+
+
+/**
+ * Iterate over finger_table entries. 
+ * 0. Ignore finger which is my_identity or if no valid entry present at 
+ *    that finger index. 
+ * 1. If disconnected_friend is a finger, then free that entry. Don't send trail
+ *    teardown message, as there is no trail to reach to a finger which is a friend. 
+ * 2. Check if disconnected_friend is the first friend in the trail to reach to a finger.
+ *   2.1 Send trail teardown message across all the trails in which disconnected
+ *       friend is the first friend in the trail. If disconnected_friend is the 
+ *       first friend in all the trails to reach finger, then remove the finger. 
+ * @param disconnected_friend Peer identity of friend which got disconnected.
+ */
+static void
+remove_matching_fingers (const struct GNUNET_PeerIdentity *disconnected_friend)
+{
+  struct FingerInfo *remove_finger;
+  int removed_trails_count;
+  int i;
   
-  return GNUNET_YES;
+  /* Iterate over finger table entries. */
+  for (i = 0; i < MAX_FINGERS; i++)
+  {  
+    remove_finger = &finger_table[i];
+
+    /* No finger stored at this trail index. */
+    if (GNUNET_NO == remove_finger->is_present)
+      continue;
+    
+    /* I am my own finger, then ignore this finger. */
+    if (0 == GNUNET_CRYPTO_cmp_peer_identity (&remove_finger->finger_identity,
+                                              &my_identity))
+      continue;
+    
+    /* Is disconnected friend a finger? */
+    if (0 == GNUNET_CRYPTO_cmp_peer_identity (disconnected_friend,
+                                              &remove_finger->finger_identity))
+    {
+      /* No trail to reach this finger as it is a friend, don't send 
+       * trail_teardown message. */
+      remove_finger->is_present = GNUNET_NO;
+      memset ((void *)&finger_table[i], 0, sizeof (finger_table[i]));
+      continue;
+    }
+    
+    /* Iterate over the list of trails to reach remove_finger. Check if 
+     * disconnected_friend is the first friend in any of the trail. */
+    removed_trails_count = remove_matching_trails (disconnected_friend, 
+                                                   remove_finger);
+    
+    /* All the finger trails had disconnected_friend as the first friend,
+     * so free the finger. */
+    if (removed_trails_count == remove_finger->trails_count)
+    {
+      remove_finger->is_present = GNUNET_NO;
+      memset ((void *)&finger_table[i], 0, sizeof (finger_table[i]));
+    }
+  }
 }
 
 
@@ -4326,28 +5174,23 @@ handle_core_disconnect (void *cls,
                                          const struct GNUNET_PeerIdentity *peer)
 {
   struct FriendInfo *remove_friend;
-  
-  /* Check for self message. */
+
+  /* If disconnected to own identity, then return. */
   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
     return;
+
+  GNUNET_assert (NULL != (remove_friend =
+                          GNUNET_CONTAINER_multipeermap_get (friend_peermap, peer)));
   
-  /* Search for peer to remove in your friend_peermap. */
-  remove_friend =
-      GNUNET_CONTAINER_multipeermap_get (friend_peermap, peer);
+  /* Remove fingers with peer as first friend or if peer is a finger. */
+  remove_matching_fingers (peer);
   
-  if (NULL == remove_friend)
-  {
-    GNUNET_break (0);
-    return;
-  }
-
-  /* Remove fingers for which this peer is the first element in the trail or if
-   * the friend is a finger.  */
-  GNUNET_CONTAINER_multipeermap_iterate (finger_peermap,
-                                         &remove_matching_finger, (void *)peer);
-  GDS_ROUTING_remove_entry (peer);
+  /* Remove any trail from routing table of which peer is a part of. This function
+   * internally sends a trail teardown message in the direction of which
+   * disconnected peer is not part of. */
+  GDS_ROUTING_remove_trail_by_peer (peer);
   
-  /* Remove the peer from friend_peermap. */
+  /* Remove peer from friend_peermap. */
   GNUNET_assert (GNUNET_YES ==
                  GNUNET_CONTAINER_multipeermap_remove (friend_peermap,
                                                        peer,
@@ -4355,7 +5198,9 @@ handle_core_disconnect (void *cls,
   
   if (0 != GNUNET_CONTAINER_multipeermap_size (friend_peermap))
     return;
-  
+
+  /* If there are no more friends in friend_peermap, then don't schedule
+   * find_finger_trail_task. */
   if (GNUNET_SCHEDULER_NO_TASK != find_finger_trail_task)
   {
       GNUNET_SCHEDULER_cancel (find_finger_trail_task);
@@ -4363,6 +5208,7 @@ handle_core_disconnect (void *cls,
   }
   else
     GNUNET_break (0);
+
 }
 
 
@@ -4380,29 +5226,30 @@ handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer_identity)
   /* Check for connect to self message */
   if (0 == memcmp (&my_identity, peer_identity, sizeof (struct GNUNET_PeerIdentity)))
     return;
-  
+
   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connected to %s\n", GNUNET_i2s (peer_identity));
-  
+
   /* If peer already exists in our friend_peermap, then exit. */
-  if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (friend_peermap, peer_identity))
+  if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (friend_peermap, 
+                                                            peer_identity))
   {
     GNUNET_break (0);
     return;
   }
-  
+
   GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# peers connected"), 1,
                             GNUNET_NO);
 
   friend = GNUNET_new (struct FriendInfo);
   friend->id = *peer_identity;
-  friend->trails_count = 0;
-  
+
   GNUNET_assert (GNUNET_OK ==
                  GNUNET_CONTAINER_multipeermap_put (friend_peermap,
                                                     peer_identity, friend,
                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
 
-  /* got a first connection, good time to start with FIND FINGER TRAIL requests... */
+
+  /* got a first connection, good time to start with FIND FINGER TRAIL requests...*/ 
   if (GNUNET_SCHEDULER_NO_TASK == find_finger_trail_task)
     find_finger_trail_task = GNUNET_SCHEDULER_add_now (&send_find_finger_trail_message, NULL);
 }
@@ -4419,6 +5266,30 @@ core_init (void *cls,
            const struct GNUNET_PeerIdentity *identity)
 {
   my_identity = *identity;
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+              "my_indentity = %s\n",GNUNET_i2s(&my_identity));
+   FPRINTF (stderr,_("\nSUPU %s, %s, %d, my_identity = %s"),
+   __FILE__, __func__,__LINE__, GNUNET_i2s (&my_identity));
+}
+
+
+/**
+ * Initialize finger table entries.
+ */
+static void
+finger_table_init ()
+{
+  int i;
+  int j;
+  
+  for(i = 0; i < MAX_FINGERS; i++)
+  {
+    finger_table[i].is_present = GNUNET_NO;
+    for (j = 0; j < MAXIMUM_TRAILS_PER_FINGER; j++)
+      finger_table[i].trail_list[j].is_present = GNUNET_NO;
+    memset ((void *)&finger_table[i], 0, sizeof (finger_table[i]));
+    
+  }
 }
 
 
@@ -4432,27 +5303,30 @@ GDS_NEIGHBOURS_init (void)
   static struct GNUNET_CORE_MessageHandler core_handlers[] = {
     {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
     {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
-    {&handle_dht_p2p_get_result, GNUNET_MESSAGE_TYPE_DHT_P2P_GET_RESULT, 0},   
+    {&handle_dht_p2p_get_result, GNUNET_MESSAGE_TYPE_DHT_P2P_GET_RESULT, 0},
     {&handle_dht_p2p_trail_setup, GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP, 0},
     {&handle_dht_p2p_trail_setup_result, GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP_RESULT, 0},
     {&handle_dht_p2p_verify_successor, GNUNET_MESSAGE_TYPE_DHT_P2P_VERIFY_SUCCESSOR, 0},
     {&handle_dht_p2p_verify_successor_result, GNUNET_MESSAGE_TYPE_DHT_P2P_VERIFY_SUCCESSOR_RESULT, 0},
     {&handle_dht_p2p_notify_new_successor, GNUNET_MESSAGE_TYPE_DHT_P2P_NOTIFY_NEW_SUCCESSOR, 0},
-    {&handle_dht_p2p_trail_rejection, GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_REJECTION, 0},
-    {&handle_dht_p2p_trail_teardown, GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_TEARDOWN, 0},
+    {&handle_dht_p2p_trail_setup_rejection, GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP_REJECTION, 0},
+    {&handle_dht_p2p_trail_compression, GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_COMPRESSION, 
+                                        sizeof (struct PeerTrailCompressionMessage)},
+    {&handle_dht_p2p_trail_teardown, GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_TEARDOWN, 
+                                     sizeof (struct PeerTrailTearDownMessage)},
     {&handle_dht_p2p_add_trail, GNUNET_MESSAGE_TYPE_DHT_P2P_ADD_TRAIL, 0},
     {NULL, 0, 0}
   };
-  
+
   core_api =
     GNUNET_CORE_connect (GDS_cfg, NULL, &core_init, &handle_core_connect,
                          &handle_core_disconnect, NULL, GNUNET_NO, NULL,
                          GNUNET_NO, core_handlers);
   if (NULL == core_api)
     return GNUNET_SYSERR;
-  
+
   friend_peermap = GNUNET_CONTAINER_multipeermap_create (256, GNUNET_NO);
-  finger_peermap = GNUNET_CONTAINER_multipeermap_create (MAX_FINGERS * 4/3, GNUNET_NO);
+  finger_table_init ();
   
   return GNUNET_OK;
 }
@@ -4466,17 +5340,13 @@ GDS_NEIGHBOURS_done (void)
 {
   if (NULL == core_api)
     return;
-  
+
   GNUNET_CORE_disconnect (core_api);
   core_api = NULL;
-  
+
   GNUNET_assert (0 == GNUNET_CONTAINER_multipeermap_size (friend_peermap));
   GNUNET_CONTAINER_multipeermap_destroy (friend_peermap);
   friend_peermap = NULL;
-  
-  GNUNET_assert (0 == GNUNET_CONTAINER_multipeermap_size (finger_peermap));
-  GNUNET_CONTAINER_multipeermap_destroy (finger_peermap);
-  finger_peermap = NULL;
 
   if (GNUNET_SCHEDULER_NO_TASK != find_finger_trail_task)
   {
@@ -4492,11 +5362,8 @@ GDS_NEIGHBOURS_done (void)
  *
  * @return my identity
  */
-struct GNUNET_PeerIdentity 
+struct GNUNET_PeerIdentity
 GDS_NEIGHBOURS_get_my_id (void)
 {
   return my_identity;
 }
-
-
-/* end of gnunet-service-xdht_neighbours.c */
\ No newline at end of file