-fix time assertion introduce in last patch
[oweals/gnunet.git] / src / dht / gnunet-service-xdht_neighbours.c
index ef19beed8360f8fded8afd93fe39ffbdf1d3dc15..a0b1c378fd2c539fcc6e9a8f1a163be2ae76dd2b 100644 (file)
 #include <fenv.h>
 #include "dht.h"
 
+/**
+ * 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 (including predecessor) of a peer 
  */
@@ -60,7 +71,7 @@
 #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)
 
 /**
  * Maximum number of trails stored per finger.
  */
-#define MAXIMUM_TRAILS_PER_FINGER 2
+#define MAXIMUM_TRAILS_PER_FINGER 1
 
 /**
- * Finger map index for predecessor entry in finger peermap.
+ * Finger map index for predecessor entry in finger table.
  */
 #define PREDECESSOR_FINGER_ID 64
 
 /**
  * Wrap around in peer identity circle. 
- * FIXME: not used anywhere, should be used in
- * find_successor() while comparing two peers.
  */
 #define PEER_IDENTITES_WRAP_AROUND pow(2, 64) - 1
 
 /**
+ * FIXME: Its use only at 3 places check if you can remove it.
  * To check if a finger is predecessor or not. 
  */
 enum GDS_NEIGHBOURS_finger_type
@@ -285,14 +295,14 @@ struct PeerTrailSetupMessage
   struct GNUNET_MessageHeader header;
   
   /**
-   * Is source_peer trying to setup the trail to any finger or predecessor.
+   * Is source_peer trying to setup the trail to a predecessor or any finger.
    */
   uint32_t is_predecessor; 
   
   /**
    * Peer closest to this value will be our finger.
    */
-  uint64_t ultimate_destination_finger_value;
+  uint64_t final_destination_finger_value;
 
   /**
    * Source peer which wants to setup the trail to one of its finger.
@@ -306,7 +316,8 @@ struct PeerTrailSetupMessage
   struct GNUNET_PeerIdentity best_known_destination; 
 
   /**
-   * Trail id of any intermediate trail we may encounter while doing trail setup.
+   * In case best_known_destination is a finger, then trail id of trail to
+   * reach to this finger.
    */
   struct GNUNET_HashCode intermediate_trail_id;
   
@@ -318,7 +329,7 @@ struct PeerTrailSetupMessage
   /* 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_list[]
+   * struct GNUNET_PeerIdentity trail[]
    */
 };
 
@@ -397,10 +408,6 @@ struct PeerVerifySuccessorMessage
 };
 
 /**
- * FIXME: In case you append the trail it may contain the same peer twice.
- * So, when you call search_my_index it can return error. Solution is while
- * appending the entry first check for duplicate entries or may be don't
- * send the current_predecessor at all. 
  * P2P Verify Successor Result Message
  */
 struct PeerVerifySuccessorResultMessage
@@ -418,16 +425,17 @@ struct PeerVerifySuccessorResultMessage
   /**
    * Successor to which PeerVerifySuccessorMessage was sent.
    */
-  struct GNUNET_PeerIdentity source_successor;
+  struct GNUNET_PeerIdentity current_successor;
 
   /**
    * Current Predecessor of source_successor. It can be same as querying peer
-   * or different.
+   * or different. In case it is different then it can be querying_peer's
+   * probable successor. 
    */
-  struct GNUNET_PeerIdentity current_predecessor;
+  struct GNUNET_PeerIdentity probable_successor;
 
   /**
-   * Trail identifier of trail from querying_peer to source_successor.
+   * Trail identifier of trail from querying_peer to current_successor.
    */
   struct GNUNET_HashCode trail_id;
 
@@ -436,8 +444,8 @@ struct PeerVerifySuccessorResultMessage
    */
   uint32_t trail_direction;
 
-  /* In case current_predecessor != querying_peer, then trail to reach from
-   * querying_peer to current_predecessor, NOT including end points.
+  /* In case probable_successor != querying_peer, then trail to reach from
+   * querying_peer to probable_successor, NOT including end points.
    * struct GNUNET_PeerIdentity trail[]
    */
 };
@@ -475,9 +483,6 @@ struct PeerNotifyNewSuccessorMessage
 };
 
 /**
- * FIXME: Check if you can merge trail compression and trail teardown
- * by modifying routing table structure a little bit. PRIORITY: at the end
- * less code. 
  * P2P Trail Compression Message.
  */
 struct PeerTrailCompressionMessage
@@ -492,11 +497,6 @@ struct PeerTrailCompressionMessage
    */
   struct GNUNET_PeerIdentity source_peer;
 
-  /**
-   * Destination 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
@@ -521,20 +521,10 @@ struct PeerTrailTearDownMessage
    */
   struct GNUNET_MessageHeader header;
 
-  /**
-   * Source peer of the trail.
-   */
-  struct GNUNET_PeerIdentity source_peer;
-
-  /**
-   * Destination peer of the trail.
-   */
-  struct GNUNET_PeerIdentity destination_peer;
-
   /**
    * Unique identifier of the trail.
    */
-  struct GNUNET_HashCode TRAIL_ID;
+  struct GNUNET_HashCode trail_id;
 
   /**
    * Direction of trail.
@@ -549,7 +539,7 @@ struct PeerTrailTearDownMessage
 struct PeerTrailRejectionMessage
 {
   /**
-   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_REJECTION
+   * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP_REJECTION
    */
   struct GNUNET_MessageHeader header;
 
@@ -656,7 +646,6 @@ struct P2PPendingMessage
 
 };
 
-
 /**
  *  Entry in friend_peermap.
  */
@@ -748,10 +737,15 @@ struct Trail
    * Length of trail pointed
    */
   unsigned int trail_length;
+  
+  /**
+   * Is there a valid trail entry. 
+   */
+  unsigned int is_present;
 };
 
 /**
- * An entry in finger_hashmap.
+ * An entry in finger_table
  */
 struct FingerInfo
 {
@@ -760,10 +754,15 @@ struct FingerInfo
    */
   struct GNUNET_PeerIdentity finger_identity;
 
+  /**
+   * Is any finger stored at this finger index. 
+   */
+  unsigned int is_present;
+  
   /**
    * Index in finger peer map
    */
-  uint32_t finger_map_index;
+  uint32_t finger_table_index;
 
   /**
    * Number of trails setup so far for this finger.
@@ -777,17 +776,22 @@ struct FingerInfo
   struct Trail trail_list[MAXIMUM_TRAILS_PER_FINGER]; 
 };
 
+
 /**
- * FIXME: Need to check if we need all the fields or not. 
  * Data structure to keep track of closest peer seen so far in find_successor()
  */
 struct Closest_Peer
 {
   /**
-   * 64 bit value of the peer
+   * Destination finger vaule. 
    */
-  uint64_t value;
-
+  uint64_t destination_finger_value;
+  
+  /**
+   * Is finger value predecessor or any other finge 
+   */
+  unsigned int is_predecessor;
+  
   /**
    * Trail id to reach to peer.
    */
@@ -845,15 +849,9 @@ static struct GNUNET_PeerIdentity my_identity;
 static struct GNUNET_CONTAINER_MultiPeerMap *friend_peermap;
 
 /**
- * Hash map of all the fingers of a peer
- */
-static struct GNUNET_CONTAINER_MultiHashMap32 *finger_hashmap;
-
-/**
- * FIXME: Check if you can replace finger_hashmap by an array of fingers. 
  * Array of all the fingers. 
- *
-static struct FingerInfo finger_table [MAX_FINGERS];*/
+ */
+static struct FingerInfo finger_table [MAX_FINGERS];
 
 /**
  * Handle to CORE.
@@ -972,6 +970,21 @@ process_friend_queue (struct FriendInfo *peer)
 }
 
 
+/**
+ * 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
@@ -1025,7 +1038,7 @@ GDS_NEIGHBOURS_send_trail_setup (struct GNUNET_PeerIdentity source_peer,
   pending->msg = &tsm->header;
   tsm->header.size = htons (msize);
   tsm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_SETUP);
-  tsm->ultimate_destination_finger_value = GNUNET_htonll (ultimate_destination_finger_value);
+  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);
@@ -1118,7 +1131,7 @@ GDS_NEIGHBOURS_send_trail_setup_result (struct GNUNET_PeerIdentity querying_peer
 
 
 /**
- * Send trail rejection message to next_hop
+ * 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
@@ -1169,7 +1182,7 @@ GDS_NEIGHBOURS_send_trail_rejection (struct GNUNET_PeerIdentity source_peer,
   trm = (struct PeerTrailRejectionMessage *)&pending[1];
   pending->msg = &trm->header;
   trm->header.size = htons (msize);
-  trm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_REJECTION);
+  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;
@@ -1204,7 +1217,7 @@ GDS_NEIGHBOURS_send_trail_rejection (struct GNUNET_PeerIdentity source_peer,
 void
 GDS_NEIGHBOURS_send_verify_successor_message (struct GNUNET_PeerIdentity source_peer,
                                               struct GNUNET_PeerIdentity successor,
-                                              const struct GNUNET_HashCode trail_id,
+                                              struct GNUNET_HashCode trail_id,
                                               struct GNUNET_PeerIdentity *trail,
                                               unsigned int trail_length,
                                               struct FriendInfo *target_friend)
@@ -1252,23 +1265,23 @@ GDS_NEIGHBOURS_send_verify_successor_message (struct GNUNET_PeerIdentity source_
 
 
 /**
- * FIXME: check if we can merge send_trail_teardown and trail_compression
- * Construct a trail teardown message and send it to target_friend
- * @param source_peer Source of the trail.
- * @param destination_peer Destination of the trail.
+ * 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_trail_teardown (struct GNUNET_PeerIdentity source_peer,
-                                    struct GNUNET_PeerIdentity destination_peer,
-                                    struct GNUNET_HashCode trail_id,
-                                    enum GDS_ROUTING_trail_direction trail_direction,
-                                    struct FriendInfo *target_friend)
+GDS_NEIGHBOURS_send_trail_teardown (struct GNUNET_HashCode trail_id,
+                                    unsigned int trail_direction,
+                                    struct GNUNET_PeerIdentity *peer)
 {
   struct PeerTrailTearDownMessage *ttdm;
   struct P2PPendingMessage *pending;
+  struct FriendInfo *target_friend;
   size_t msize;
 
   msize = sizeof (struct PeerTrailTearDownMessage);
@@ -1278,7 +1291,10 @@ GDS_NEIGHBOURS_send_trail_teardown (struct GNUNET_PeerIdentity source_peer,
     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"),
@@ -1292,12 +1308,11 @@ GDS_NEIGHBOURS_send_trail_teardown (struct GNUNET_PeerIdentity source_peer,
   pending->msg = &ttdm->header;
   ttdm->header.size = htons (msize);
   ttdm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_TEARDOWN);
-  ttdm->source_peer = source_peer;
-  ttdm->destination_peer = destination_peer;
-  ttdm->TRAIL_ID = trail_id;
+  ttdm->trail_id = trail_id;
   ttdm->trail_direction = htonl (trail_direction);
 
   /* 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);
@@ -1321,8 +1336,8 @@ GDS_NEIGHBOURS_send_trail_teardown (struct GNUNET_PeerIdentity source_peer,
  */
 void
 GDS_NEIGHBOURS_send_verify_successor_result (struct GNUNET_PeerIdentity querying_peer,
-                                             struct GNUNET_PeerIdentity source_successor,
-                                             struct GNUNET_PeerIdentity current_predecessor,
+                                             struct GNUNET_PeerIdentity current_successor,
+                                             struct GNUNET_PeerIdentity probable_successor,
                                              struct GNUNET_HashCode trail_id,
                                              const struct GNUNET_PeerIdentity *trail,
                                              unsigned int trail_length,
@@ -1357,8 +1372,8 @@ GDS_NEIGHBOURS_send_verify_successor_result (struct GNUNET_PeerIdentity querying
   vsmr->header.size = htons (msize);
   vsmr->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_VERIFY_SUCCESSOR_RESULT);
   vsmr->querying_peer = querying_peer;
-  vsmr->source_successor = source_successor;
-  vsmr->current_predecessor = current_predecessor;
+  vsmr->current_successor = current_successor;
+  vsmr->probable_successor = probable_successor;
   vsmr->trail_direction = htonl (trail_direction);
   vsmr->trail_id = trail_id;
   
@@ -1390,7 +1405,7 @@ GDS_NEIGHBOURS_send_verify_successor_result (struct GNUNET_PeerIdentity querying
 void
 GDS_NEIGHBOURS_send_notify_new_successor (struct GNUNET_PeerIdentity source_peer,
                                           struct GNUNET_PeerIdentity successor,
-                                          struct GNUNET_PeerIdentity *successor_trail,
+                                          const struct GNUNET_PeerIdentity *successor_trail,
                                           unsigned int successor_trail_length,
                                           struct GNUNET_HashCode succesor_trail_id,
                                           struct FriendInfo *target_friend)
@@ -1455,7 +1470,7 @@ void
 GDS_NEIGHBOURS_send_add_trail (struct GNUNET_PeerIdentity source_peer,
                                struct GNUNET_PeerIdentity destination_peer,
                                struct GNUNET_HashCode trail_id,
-                               struct GNUNET_PeerIdentity *trail,
+                               const struct GNUNET_PeerIdentity *trail,
                                unsigned int trail_length,
                                struct FriendInfo *target_friend)
 {
@@ -1490,11 +1505,8 @@ GDS_NEIGHBOURS_send_add_trail (struct GNUNET_PeerIdentity source_peer,
   adm->destination_peer = destination_peer;
   adm->trail_id = trail_id;
 
-  if (trail_length > 0)
-  {
-    peer_list = (struct GNUNET_PeerIdentity *)&adm[1];
-    memcpy (peer_list, trail, sizeof (struct GNUNET_PeerIdentity) * trail_length);
-  }
+  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);
@@ -1505,17 +1517,14 @@ GDS_NEIGHBOURS_send_add_trail (struct GNUNET_PeerIdentity source_peer,
 
 
 /**
- * FIXME: Merge into "teardown", add source and "last/new_first" in message struct.
  * Construct a trail compression message and send it to target_friend.
  * @param source_peer Source of the trail.
- * @param destination_finger Destination of 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.
  */
 void
 GDS_NEIGHBOURS_send_trail_compression (struct GNUNET_PeerIdentity source_peer,
-                                       struct GNUNET_PeerIdentity destination_peer,
                                        struct GNUNET_HashCode trail_id,
                                        struct GNUNET_PeerIdentity first_friend,
                                        struct FriendInfo *target_friend)
@@ -1549,7 +1558,6 @@ GDS_NEIGHBOURS_send_trail_compression (struct GNUNET_PeerIdentity source_peer,
   tcm->source_peer = source_peer;
   tcm->new_first_friend = first_friend;
   tcm->trail_id = trail_id;
-  tcm->destination_peer = destination_peer;
 
   GNUNET_CONTAINER_DLL_insert_tail (target_friend->head, target_friend->tail, pending);
   target_friend->pending_count++;
@@ -1649,6 +1657,7 @@ select_finger_trail (struct FingerInfo *finger)
 
 
 /**
+ * FIXME; not handling the wrap around logic correctly. 
  * Select closest finger to value.
  * @param peer1 First peer
  * @param peer2 Second peer
@@ -1660,31 +1669,60 @@ select_closest_finger (struct GNUNET_PeerIdentity *peer1,
                        struct GNUNET_PeerIdentity *peer2,
                        uint64_t value)
 {
-#if 0
   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) && (value <= peer2_value))
-    return peer2;
-  else if ((peer2_value <= value) && (value <= peer1_value))
-    return peer1;
-  else if ((peer1_value <= peer2_value) && (peer2_value <= value))
-    return peer1;
-  else if ((peer2_value <= peer1_value) && (peer1_value <= value))
-    return peer2;
-  else if ((value <= peer1_value) && (peer1_value <= peer2_value))
+  if (peer1_value == value)
+  {
     return peer1;
-  else /*if ((value <= peer2_value) && (peer2_value <= peer1_value))*/
+  }
+  
+  if (peer2_value == value)
+  {
     return peer2;
-#endif
+  }
+   
+  if (peer2_value < peer1_value)
+  {
+    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 (peer1_value < peer2_value)
+  {
+    if ((peer1_value < value) && (value < peer2_value))
+    {
+      return peer2;
+    }
+    else if (((peer2_value < value) && (value < PEER_IDENTITES_WRAP_AROUND)) ||
+             ((0 < value) && (value < peer1_value)))
+    {
+      return peer1;
+    }
+  }
   return NULL;
 }
 
 
 /**
+ * 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
@@ -1696,38 +1734,81 @@ select_closest_predecessor (struct GNUNET_PeerIdentity *peer1,
                             struct GNUNET_PeerIdentity *peer2,
                             uint64_t value)
 {
-  #if 0
   uint64_t peer1_value;
   uint64_t peer2_value;
-
+  
   memcpy (&peer1_value, peer1, sizeof (uint64_t));
   memcpy (&peer2_value, peer2, sizeof (uint64_t));
-
-#endif
+  
+  if (peer1_value == value)
+    return peer1;
+  
+  if (peer2_value == value)
+    return peer2;
+  
+  if (peer1_value < peer2_value)
+  {
+    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 (peer2_value < peer1_value)
+  {
+    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. 
+
+ */
 /**
  * Select the closest peer among two peers (which should not be same)
- * with respect to value and finger_map_index
+ * 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_map_index Index in finger map. If equal to PREDECESSOR_FINGER_ID,
+ * @param finger_table_index Index in finger map. If equal to PREDECESSOR_FINGER_ID,
  *                         then we use different logic than other
- *                         finger_map_index
+ *                         finger_table_index
  * @return Closest peer among two peers.
  */
 static struct GNUNET_PeerIdentity *
 select_closest_peer (struct GNUNET_PeerIdentity *peer1,
                      struct GNUNET_PeerIdentity *peer2,
                      uint64_t value,
-                     unsigned int finger_map_index)
+                     unsigned int finger_table_index)
 {
   struct GNUNET_PeerIdentity *closest_peer;
-
-  if (PREDECESSOR_FINGER_ID == finger_map_index)
+  /* 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);
@@ -1737,81 +1818,65 @@ select_closest_peer (struct GNUNET_PeerIdentity *peer1,
 
 
 /**
- * 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 next_destination [out] 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 we finger is the @a next_destination,
- *                                then we updated the field with trail id to reach
- *                                to that finger.
- * @param finger_map_index Index in finger peermap for which we are
- *                         looking for a finger, to discern between
- *                         IS_PREDECESSOR or not.
- * @return Closest successor for value. 
+ * 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 struct GNUNET_PeerIdentity *
-find_successor (uint64_t destination_finger_value,
-                struct GNUNET_PeerIdentity *best_known_destination,
-                struct GNUNET_HashCode *new_intermediate_trail_id,
-                unsigned int finger_map_index)
+static struct Closest_Peer *
+compare_finger_and_current_successor (struct Closest_Peer *current_closest_peer)
 {
-  struct Closest_Peer *current_successor;
-  struct GNUNET_PeerIdentity *next_hop;
-  struct GNUNET_CONTAINER_MultiPeerMapIterator *friend_iter;
-  struct GNUNET_CONTAINER_MultiHashMap32Iterator *finger_iter;
-  struct Selected_Finger_Trail *finger_trail;
-  struct FriendInfo *friend;
   struct FingerInfo *finger;
+  struct FriendInfo *friend;
+  struct GNUNET_PeerIdentity *closest_peer;
   int i;
   
-  /* Initialize current_successor to my_identity. */
-  current_successor = GNUNET_new (struct Closest_Peer);
-  memcpy (&current_successor->value, &my_identity, sizeof (uint64_t));
-  memset (&current_successor->trail_id, 0, sizeof (current_successor->trail_id)); 
-  current_successor->next_hop = my_identity;
-  current_successor->best_known_destination = my_identity;
-  
-  /* Iterate over friend_peermap and compare each friend with current_successor.*/
-  friend_iter = GNUNET_CONTAINER_multipeermap_iterator_create (friend_peermap);
-  for (i= 0; i < GNUNET_CONTAINER_multipeermap_size (friend_peermap); i++)
+  for (i = 0; i < MAX_FINGERS; i++)
   {
-    GNUNET_assert (GNUNET_YES ==
-      GNUNET_CONTAINER_multipeermap_iterator_next (friend_iter, NULL,
-                                                  (const void **)&friend));
+    struct Selected_Finger_Trail *finger_trail;
+    finger = &finger_table[i];
     
-    if (GNUNET_YES == is_friend_congested (friend))
+    if (GNUNET_NO == finger->is_present)
       continue;
     
-    /* 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.*/
-  }
-  
-  /* Iterate over finger_hashmap and compare each finger with current_successor.*/
-  finger_iter = GNUNET_CONTAINER_multihashmap32_iterator_create (finger_hashmap);
-  for (i = 0; i < GNUNET_CONTAINER_multihashmap32_size (finger_hashmap); i++)
-  {
-    GNUNET_assert (GNUNET_YES ==
-      GNUNET_CONTAINER_multihashmap32_iterator_next (finger_iter, NULL,
-                                                     (void *)&finger));
+    /* 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))
+                                              &my_identity))
       continue;
     
     /* If finger is friend. */
-    if(GNUNET_CONTAINER_multipeermap_get (friend_peermap, &finger->finger_identity))
+    if (NULL != (friend = GNUNET_CONTAINER_multipeermap_get 
+                (friend_peermap, &finger->finger_identity)))
     {
-      /* If not congested then compare it with current_successor. */
-      if (GNUNET_NO == is_friend_congested (friend))
+      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))
       {
-        //compare it with current successor.   
+        current_closest_peer->best_known_destination = finger->finger_identity;
+        current_closest_peer->next_hop = finger->finger_identity;
       }
+      continue;
     }
+    
     /* Choose one of the trail to reach to finger. */
     finger_trail = select_finger_trail (finger);
     
@@ -1819,22 +1884,140 @@ find_successor (uint64_t destination_finger_value,
     if (NULL == finger_trail)
       continue;
     
-    /* 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. */
+     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;
+}
+
+
+/**
+ * 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 int
+compare_friend_and_current_closest_peer (void *cls,
+                                         const struct GNUNET_PeerIdentity *key,
+                                         void *value)
+{
+  struct FriendInfo *friend = value;
+  struct Closest_Peer *current_closest_peer = cls;
+  struct GNUNET_PeerIdentity *closest_peer;
+  
+  if (GNUNET_YES == is_friend_congested (friend))
+    return GNUNET_YES;
+  
+  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))
+  {
+    current_closest_peer->best_known_destination = friend->id;
+    current_closest_peer->next_hop = friend->id;
   }
   
-  best_known_destination = &current_successor->best_known_destination;
-  new_intermediate_trail_id = &current_successor->trail_id;
-  next_hop = &current_successor->next_hop;
+  return GNUNET_YES;
+}
+
+/**
+ * Initialize current_successor to my_identity.
+ * @param my_identity My peer identity
+ * @return current_successor
+ */
+static struct Closest_Peer *
+init_current_successor (struct GNUNET_PeerIdentity my_identity,
+                        uint64_t destination_finger_value,
+                        unsigned int is_predecessor)
+{
+  struct Closest_Peer *current_closest_peer;
+  
+  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;
+  
+  return current_closest_peer;
+}
+
+
+/**
+ * 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 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)
+{
+  struct Closest_Peer *current_closest_peer;
+  struct GNUNET_PeerIdentity *next_hop;
 
+   /* 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));
+  
+  /* Compare each finger entry with current_successor and update current_successor
+   * with finger if its closest. */
+  compare_finger_and_current_successor (current_closest_peer);
+  
+  *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;
+  
   return next_hop;
 }
 
@@ -1874,6 +2057,7 @@ GDS_NEIGHBOURS_send_put (const struct GNUNET_HashCode *key,
   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 +
@@ -1899,9 +2083,11 @@ GDS_NEIGHBOURS_send_put (const struct GNUNET_HashCode *key,
     struct GNUNET_PeerIdentity *next_hop;
    
     memcpy (&key_value, key, sizeof (uint64_t));
-    next_hop = find_successor (key_value, best_known_dest, 
+    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(next_hop, &my_identity)) 
+    if (0 == GNUNET_CRYPTO_cmp_peer_identity (local_best_known_dest, &my_identity)) 
     {
       /* I am the destination but we have already done datacache_put in client file.  */
       return;
@@ -1909,7 +2095,10 @@ GDS_NEIGHBOURS_send_put (const struct GNUNET_HashCode *key,
     else
       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->timeout = expiration_time;
   ppm = (struct PeerPutMessage *) &pending[1];
@@ -1922,7 +2111,10 @@ 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);
-  ppm->best_known_destination = *best_known_dest;
+  if (NULL == best_known_dest)
+    ppm->best_known_destination = *local_best_known_dest;
+  else
+    ppm->best_known_destination = *best_known_dest;
   ppm->key = *key;
   if (NULL == intermediate_trail_id)
     memset (&ppm->intermediate_trail_id, 0, sizeof (ppm->intermediate_trail_id));
@@ -1972,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;
 
@@ -1991,11 +2184,11 @@ GDS_NEIGHBOURS_send_get (const struct GNUNET_HashCode *key,
     
     memcpy (&key_value, key, sizeof (uint64_t));
        // FIXME: endianess of key_value!?
-     /* FIXME: Here you should use enum GDS_NEIGHBOURS_FINGER_TYPE in place of 0. */
-    next_hop = find_successor (key_value, best_known_dest,
+    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)) 
+    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);
@@ -2006,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 */
@@ -2015,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->best_known_destination = *best_known_dest;
-  pgm->intermediate_trail_id = *intermediate_trail_id;
+  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)
@@ -2063,7 +2267,7 @@ GDS_NEIGHBOURS_send_get_result (const struct GNUNET_HashCode *key,
   struct FriendInfo *target_friend;
   int current_path_index;
   size_t msize;
-  
+
   msize = get_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size +
           sizeof (struct PeerPutMessage);
  
@@ -2102,12 +2306,10 @@ GDS_NEIGHBOURS_send_get_result (const struct GNUNET_HashCode *key,
   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? */
@@ -2166,8 +2368,8 @@ select_random_friend ()
                                                              &key_ret,
                                                              (const void **)&friend));
 
-
-    if ((TRAILS_THROUGH_FRIEND_THRESHOLD == friend->trails_count) &&
+    /* 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;
@@ -2182,39 +2384,38 @@ select_random_friend ()
 
 
 /**
- * FIXME: pass current_search_finger_index as parameter
- * Compute finger_identity to which we want to setup the trail
- * @return finger_identity
- */
-static uint64_t
-compute_finger_identity_value ()
-{
-  uint64_t my_id64;
-
-  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));
-}
-
-
-/**
- * Compute immediate predecessor identity in the network.
- * @return peer identity of immediate predecessor.
+ * 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_predecessor_identity_value ()
+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);
-  return (my_id64 -1);
+  
+  /* 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 and start looking for the trail to reach to
- * finger identity through this random friend.
+ * 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
@@ -2229,6 +2430,7 @@ send_find_finger_trail_message (void *cls,
   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,
@@ -2237,23 +2439,24 @@ send_find_finger_trail_message (void *cls,
       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)
-  {
-    finger_id_value = compute_predecessor_identity_value();
-    is_predecessor = 0;
-  }
-  else
-  {
-    finger_id_value = compute_finger_identity_value();
     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,
@@ -2314,20 +2517,16 @@ select_and_replace_trail (struct FingerInfo *existing_finger,
 
   /* Send trail teardown message across the replaced trail. */
   struct Trail *replace_trail = &existing_finger->trail_list[largest_trail_index];
-  struct FriendInfo *target_friend =
-      GNUNET_CONTAINER_multipeermap_get (friend_peermap,
-                                         &replace_trail->trail_head->peer);
-
-  GDS_NEIGHBOURS_send_trail_teardown (my_identity,
-                                      existing_finger->finger_identity,
-                                      replace_trail->trail_id,
-                                      GDS_ROUTING_SRC_TO_DEST, target_friend);
+
+  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 (trail_element);
+    GNUNET_free_non_null (trail_element);
   }
 
   /* Add new trial at that location. */
@@ -2439,73 +2638,74 @@ add_new_trail (struct FingerInfo *existing_finger,
 
 
 /**
- * Send trail teardown message on all trails associated with finger.
- * @param finger_to_be_removed
+ * 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)
+send_trail_teardown (struct FingerInfo *finger,
+                     struct Trail *trail)
 {
-  struct Trail *trail_list_iterator;
-  struct FriendInfo *target_friend;
-  int i;
+  /* 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);
+}
 
-  if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger->finger_identity, &my_identity)
-     || (NULL != GNUNET_CONTAINER_multipeermap_get (friend_peermap,
-                                                    &finger->finger_identity)))
-    return;
+
+/**
+ * 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_list_iterator = &finger->trail_list[i];
-    if (trail_list_iterator->trail_length > 0)
+    trail = &finger->trail_list[i];
+    if (trail->trail_length > 0)
     {
-      target_friend =
-              GNUNET_CONTAINER_multipeermap_get (friend_peermap,
-                                                 &trail_list_iterator->trail_head->peer);
-      // check target_friend
-      GDS_NEIGHBOURS_send_trail_teardown (my_identity, finger->finger_identity,
-                                          trail_list_iterator->trail_id,
-                                          GDS_ROUTING_SRC_TO_DEST,
-                                          target_friend);
+     /* decerement the friend trails count. */
+     send_trail_teardown (finger, trail);
     }
   }
 }
 
 
 /**
- * Decrement the trail count of the first friend to reach the finger
- * In case finger is the friend, then decrement its trail count.
- * @param finger
+ * Free a specific trail
+ * @param trail List of peers to be freed. 
  */
 static void
-decrement_friend_trail_count (struct FingerInfo *finger)
+free_trail (struct Trail *trail)
 {
-  struct Trail *trail_list_iterator;
-  struct FriendInfo *target_friend;
-  int i = 0;
-
-  if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger->finger_identity,
-                                            &my_identity))
-    return;
+  struct Trail_Element *trail_element;
 
-  for (i = 0; i < finger->trails_count; i++)
+  while (NULL != (trail_element = trail->trail_head))
   {
-    trail_list_iterator = &finger->trail_list[i];
-    if (trail_list_iterator->trail_length > 0)
-      target_friend =
-              GNUNET_CONTAINER_multipeermap_get (friend_peermap,
-                                                 &trail_list_iterator->trail_head->peer);
-    else
-     target_friend =
-              GNUNET_CONTAINER_multipeermap_get (friend_peermap,
-                                                 &finger->finger_identity);
-
-    // check target_friend for NULL
-    /* FIXME: we have removed first_friend_trail_count field. */
-   target_friend->trails_count--;
-    //trail_list_iterator->first_friend_trail_count--;
-  }
-  return;
+    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;
 }
 
 
@@ -2514,91 +2714,101 @@ decrement_friend_trail_count (struct FingerInfo *finger)
  * @param finger Finger to be freed.
  */
 static void
-free_finger (struct FingerInfo *finger)
+free_finger (struct FingerInfo *finger, unsigned int finger_table_index)
 {
-  struct Trail *trail_list_iterator;
-  struct Trail_Element *trail_element;
+  struct Trail *trail;
   unsigned int i;
 
   for (i = 0; i < finger->trails_count; i++)
   {
-    trail_list_iterator = &finger->trail_list[i];
-    while (NULL != (trail_element = trail_list_iterator->trail_head))
-    {
-      GNUNET_CONTAINER_DLL_remove (trail_list_iterator->trail_head,
-                                   trail_list_iterator->trail_tail,
-                                   trail_element);
-      GNUNET_free (trail_element);
-    }
+    trail = &finger->trail_list[i];
+    if (GNUNET_NO == trail->is_present)
+      continue;
+    
+    if (trail->trail_length > 0)
+      free_trail (trail);
   }
-  GNUNET_free (finger);
+  
+  finger->is_present = GNUNET_NO;
+  memset ((void *)&finger_table[finger_table_index], 0, sizeof (finger_table[finger_table_index]));
 }
 
 
 /**
- * Add a new entry in finger hashmap at finger_map_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_map_index Index in finger hashmap.
- * @return #GNUNET_OK if new entry is added
- *         #GNUNET_NO -- FIXME: need to check what value does hahsmap put
- *                       returns on failure.
+ * @param finger_table_index Index in finger table.
  */
-static int
-add_new_entry (struct GNUNET_PeerIdentity finger_identity,
-               const struct GNUNET_PeerIdentity *finger_trail,
-               unsigned int finger_trail_length,
-               struct GNUNET_HashCode trail_id,
-               unsigned int finger_map_index)
+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 *first_trail;
+  struct Trail *trail;
   int i = 0;
-
+  
   new_entry = GNUNET_new (struct FingerInfo);
   new_entry->finger_identity = finger_identity;
-  new_entry->finger_map_index = finger_map_index;
+  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;
-
-  if (0 != GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &finger_identity))
+  first_trail_hop->trails_count++;
+   
+  /* Copy the finger trail into trail. */
+  trail = GNUNET_new (struct Trail);
+  while (i < finger_trail_length)
   {
-    if (finger_trail_length > 0)
-    {
-      first_trail_hop = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
-                                                           &finger_trail[0]);
-    }
-    else
-    {
-      first_trail_hop = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
-                                                           &finger_identity);
-    }
-
-    first_trail_hop->trails_count++;
-    first_trail = &new_entry->trail_list[0];
-    /* FIXME: We have removed this field. */
-    //first_trail->first_friend_trail_count = first_trail_hop->trails_count;
+    struct Trail_Element *element = GNUNET_new (struct Trail_Element);
 
-    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 (first_trail->trail_head,
-                                        first_trail->trail_tail,
-                                        element);
-      i++;
-    }
+    element->next = NULL;
+    element->prev = NULL;
+    element->peer = finger_trail[i];
+    GNUNET_CONTAINER_DLL_insert_tail (trail->trail_head,
+                                      trail->trail_tail,
+                                      element);
+    i++;
   }
-
-  return GNUNET_CONTAINER_multihashmap32_put (finger_hashmap,
-                                              new_entry->finger_map_index,
-                                              new_entry,
-                                              GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
+  
+  /* 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;
 }
 
 
@@ -2625,28 +2835,39 @@ scan_and_compress_trail (struct GNUNET_PeerIdentity finger_identity,
   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]);
-      GDS_NEIGHBOURS_send_trail_compression (my_identity, finger_identity,
+                                                         &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);
-      *new_trail_length = 0;
     }
     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;
@@ -2654,13 +2875,13 @@ scan_and_compress_trail (struct GNUNET_PeerIdentity finger_identity,
 
       target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
                                                          &trail[0]);
-      GDS_NEIGHBOURS_send_trail_compression (my_identity, finger_identity,
+      GDS_NEIGHBOURS_send_trail_compression (my_identity, 
                                              trail_id, trail[i],
                                              target_friend);
 
     
-      /* Copy the trail from index i to index trail_length -1 and change
-       trail length and return */
+      /* 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)
       {
@@ -2669,154 +2890,320 @@ scan_and_compress_trail (struct GNUNET_PeerIdentity finger_identity,
         i++;
       }
       *new_trail_length = j+1;
-      break;
       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, new_trail, trail_length * sizeof (struct GNUNET_PeerIdentity));
+  memcpy (new_trail, trail, trail_length * sizeof (struct GNUNET_PeerIdentity));
   return new_trail;
 }
 
 
 /**
- * FIXME: Ensure that we add trail in succession in the trail list.
- * There are no free spots within the trail list. 
- * Send verify successor message to your successor on all trails to reach
- * the successor.
- * @param successor My current successor
+ * 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)
 {
-  struct Trail *trail_list_iterator;
-  struct GNUNET_HashCode trail_id;
-  struct GNUNET_PeerIdentity next_hop;
+  /*
+   * 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_PeerIdentity *trail;
-  unsigned int trail_length;
+  struct GNUNET_HashCode trail_id;
   int i;
-  int j;
-
+  
+  /* 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++)
   {
-    trail_list_iterator = &successor->trail_list[i];
-    GNUNET_assert (NULL != trail_list_iterator->trail_head);
-
-    if (trail_list_iterator->trail_length > 0)
-    {
-      struct Trail_Element *element;
-
-      trail_length = trail_list_iterator->trail_length;
-      trail = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity)
-                             * trail_length);
-      element = trail_list_iterator->trail_head;
-      for (j = 0; j < trail_length; j++, element = element->next)
-        trail[j] = element->peer;
-      next_hop = trail_list_iterator->trail_head->peer;
-    }
-    else
+    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)
     {
-      trail = NULL;
-      trail_length = 0;
-      next_hop = successor->finger_identity;
+      peer_list[j] = element->peer;
+      element = element->next;
+      j++;
     }
-    trail_id = trail_list_iterator->trail_id;
+   
     GNUNET_assert (NULL != (target_friend = 
-                           GNUNET_CONTAINER_multipeermap_get (friend_peermap, &next_hop)));
-    
+                           GNUNET_CONTAINER_multipeermap_get (friend_peermap, 
+                                                              &peer_list[0])));
     GDS_NEIGHBOURS_send_verify_successor_message (my_identity,
                                                   successor->finger_identity,
-                                                  trail_id, trail, trail_length,
+                                                  trail_id, peer_list, trail_length,
                                                   target_friend);
-    GNUNET_free_non_null (trail);
+    
   }
 }
 
 
 /**
- * FIXME: Is it safe to assume that current_search_finger_index == finger_map_index?
+ * 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 new_finger_identity)
+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 = GNUNET_CONTAINER_multihashmap32_get (finger_hashmap, 0);
-  
+  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 (0 != GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &new_finger_identity))
+    /* 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);
+      send_verify_successor_message (successor);
     }
+    return;
   }
-  else if (0 == GNUNET_CRYPTO_cmp_peer_identity (&new_finger_identity,
-                                                  &(successor->finger_identity)))
-  {
-     current_search_finger_index = 0;
-  }
-  else
-     current_search_finger_index = current_search_finger_index - 1;
+  
+  current_search_finger_index = current_search_finger_index - 1;
+  return;
 }
 
+
 /**
- * FIXME: Is it sage to assume that finger_map_index == current_search_finger_index
- * Calculate finger_map_index from initial value that we send in trail setup
- * message. 
+ * 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_map_index.
- * @param is_predecessor Is the entry for predecessor or not
- * @return finger_map_index which is a value between 0 <= finger_map_index <= 64
- *         -1, if no valid finger_map_index is found. 
+ *                                          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 int
-get_finger_map_index (uint64_t ultimate_destination_finger_value,
-                      unsigned int is_predecessor)
+static unsigned int
+get_finger_table_index (uint64_t ultimate_destination_finger_value,
+                        unsigned int is_predecessor)
 {
   uint64_t my_id64;
-  unsigned int finger_map_index;
-  
-  finger_map_index = -1;
+  int diff;
+  unsigned int finger_table_index;
+
   memcpy (&my_id64, &my_identity, sizeof (uint64_t));
+  my_id64 = GNUNET_ntohll (my_id64);
   
-  if (is_predecessor)
+  /* Is this a predecessor finger? */
+  if (1 == is_predecessor)
   {
-    if(1 == (my_id64 - ultimate_destination_finger_value))
-      finger_map_index = PREDECESSOR_FINGER_ID;
+    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
+  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_map_index = log (ultimate_destination_finger_value - my_id64);
+    finger->is_present = GNUNET_NO;
+    memset ((void *)&finger_table[finger_table_index], 0, sizeof (finger_table[finger_table_index]));
+    return;
   }
   
-  if ((finger_map_index > PREDECESSOR_FINGER_ID) ||
-      (finger_map_index == current_search_finger_index))
-    finger_map_index = -1;
+  /* 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);
   
-  return finger_map_index;
+  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);
+    }
+  }
 }
 
 
 /**
- * Check if there is already an entry in finger peermap for given finger map index.
- * If yes, then select the closest finger. If new and existing finger are same,
- * the 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, add it.
- * Then, update current_search_finger_index.
- * @param new_finger_identity Peer Identity of new finger
- * @param new_finger_trail Trail to reach the new finger
- * @param new_finger_length Total number of peers in @a new_finger_trail.
- * @param is_predecessor Is this entry for predecessor in finger_peermap. 
- * @param new_finger_trail_id Unique identifier of @new_finger_trail.
- * @return #GNUNET_YES if the new entry is added
- *         #GNUNET_NO if new entry is not added, either it was discarded or
- *                    it was same as existing finger at finger map index.
+ * This is a test function, to print all the entries of finger table.
  */
-static int
+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,
@@ -2826,37 +3213,55 @@ finger_table_add (struct GNUNET_PeerIdentity finger_identity,
 {
   struct FingerInfo *existing_finger;
   struct GNUNET_PeerIdentity *closest_peer;
-  int updated_finger_trail_length; 
   struct GNUNET_PeerIdentity *updated_trail;
-  unsigned int finger_map_index;
-  unsigned int new_entry_added;
-  
-  new_entry_added = GNUNET_NO;
+  struct FingerInfo *successor;
+  int updated_finger_trail_length; 
+  unsigned int finger_table_index;
   
-  finger_map_index = get_finger_map_index (finger_value,
-                                           is_predecessor);
+  //test_friend_peermap_print();
+  //test_finger_table_print();
   
-  if (-1 == finger_map_index)
+  /* 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 GNUNET_SYSERR;
+    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 = GNUNET_CONTAINER_multihashmap32_get (finger_hashmap,
-                                                         finger_map_index);
+  existing_finger = &finger_table[finger_table_index];
   
-  /* No entry present in finger hashmap for given finger map index. */
-  if (NULL == existing_finger)
+  /* No entry present in finger_table for given finger map index. */
+  if (GNUNET_NO == existing_finger->is_present)
   {
-    add_new_entry (finger_identity, updated_trail, updated_finger_trail_length,
-                   finger_trail_id, finger_map_index);
-    update_current_search_finger_index (finger_identity);
-    return GNUNET_YES;
+    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. */
@@ -2865,20 +3270,14 @@ finger_table_add (struct GNUNET_PeerIdentity finger_identity,
   {
     closest_peer = select_closest_peer (&existing_finger->finger_identity,
                                         &finger_identity,
-                                        finger_value, finger_map_index);
+                                        finger_value, finger_table_index);
     
     /* If the new finger is the closest peer. */
     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger_identity, closest_peer))
     {
-      GNUNET_assert (0 != GNUNET_CRYPTO_cmp_peer_identity (&my_identity,
-                                                           &finger_identity));
-
-      send_trail_teardown (existing_finger);
-      decrement_friend_trail_count (existing_finger);
-      free_finger (existing_finger);
-      add_new_entry (finger_identity, updated_trail, updated_finger_trail_length,
-                     finger_trail_id, finger_map_index);
-      new_entry_added = GNUNET_YES;
+      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
@@ -2886,15 +3285,14 @@ finger_table_add (struct GNUNET_PeerIdentity finger_identity,
     /* 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 GNUNET_NO;
-    }
+      return;
     
     /* If the existing finger is not a friend. */
     if (NULL ==
         GNUNET_CONTAINER_multipeermap_get (friend_peermap,
-                                            &(existing_finger->finger_identity)))
+                                           &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);
@@ -2902,11 +3300,9 @@ finger_table_add (struct GNUNET_PeerIdentity finger_identity,
         select_and_replace_trail (existing_finger, updated_trail,
                                   finger_trail_length, finger_trail_id);
     }
-    new_entry_added = GNUNET_NO;
   }
-  
-  update_current_search_finger_index (finger_identity);
-  return new_entry_added;
+  update_current_search_finger_index (finger_identity, finger_table_index);
+  return;
 }
 
 
@@ -3031,7 +3427,6 @@ handle_dht_p2p_put (void *cls, const struct GNUNET_PeerIdentity *peer,
   }
   else
   {
-     /*FIXME: Here you should use enum GDS_NEIGHBOURS_FINGER_TYPE in place of 0. */
     next_hop = find_successor (key_value, &best_known_dest, 
                                &intermediate_trail_id, GDS_FINGER_TYPE_NON_PREDECESSOR); 
   }
@@ -3111,8 +3506,7 @@ handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
   get_length = ntohl (get->get_path_length);
   best_known_dest = get->best_known_destination;
   intermediate_trail_id = get->intermediate_trail_id;
-  if (get_length > 0)
-    get_path = (struct GNUNET_PeerIdentity *)&get[1];
+  get_path = (struct GNUNET_PeerIdentity *)&get[1];
   
   if ((msize <
        sizeof (struct PeerGetMessage) +
@@ -3123,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));
@@ -3138,7 +3532,6 @@ handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
   }
   else
   {
-     /*FIXME: Here you should use enum GDS_NEIGHBOURS_FINGER_TYPE in place of 0. */
     next_hop = find_successor (key_value, &best_known_dest, 
                                &intermediate_trail_id, GDS_FINGER_TYPE_NON_PREDECESSOR);  
   }
@@ -3260,6 +3653,77 @@ handle_dht_p2p_get_result (void *cls, const struct GNUNET_PeerIdentity *peer,
 }
 
 
+/**
+ * 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 
+ */
+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 *next_hop_to_local_best_known_dest;
+  
+ /* 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;
+    }
+  }
+  
+  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
@@ -3272,13 +3736,13 @@ handle_dht_p2p_trail_setup (void *cls, const struct GNUNET_PeerIdentity *peer,
 {
   const struct PeerTrailSetupMessage *trail_setup;
   const struct GNUNET_PeerIdentity *trail_peer_list;
-  struct GNUNET_PeerIdentity local_best_known_destination
-  struct GNUNET_PeerIdentity current_destination;
-  struct GNUNET_PeerIdentity *next_hop;
+  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 ultimate_destination_finger_value;
+  uint64_t final_dest_finger_val;
   struct GNUNET_HashCode new_intermediate_trail_id;
   struct GNUNET_HashCode intermediate_trail_id;
   struct GNUNET_HashCode trail_id;
@@ -3287,7 +3751,6 @@ handle_dht_p2p_trail_setup (void *cls, const struct GNUNET_PeerIdentity *peer,
   size_t msize;
 
   msize = ntohs (message->size);
-  /* There are PeerId's appended to the end of the message! */
   if (msize < sizeof (struct PeerTrailSetupMessage))
   {
     GNUNET_break_op (0);
@@ -3305,18 +3768,19 @@ handle_dht_p2p_trail_setup (void *cls, const struct GNUNET_PeerIdentity *peer,
   }           
   
   trail_peer_list = (const struct GNUNET_PeerIdentity *)&trail_setup[1];
-  current_destination = trail_setup->best_known_destination;
+  current_dest = trail_setup->best_known_destination;
   trail_id = trail_setup->trail_id;
-  ultimate_destination_finger_value = 
-          GNUNET_ntohll (trail_setup->ultimate_destination_finger_value);
+  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, ultimate_destination_finger_value,
+    GDS_NEIGHBOURS_send_trail_rejection (source, final_dest_finger_val,
                                          my_identity, is_predecessor,
                                          trail_peer_list, trail_length,
                                          trail_id, target_friend,
@@ -3324,44 +3788,27 @@ handle_dht_p2p_trail_setup (void *cls, const struct GNUNET_PeerIdentity *peer,
     return GNUNET_OK;
   }
 
+  local_best_known_dest = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
   
-  next_hop = find_successor (ultimate_destination_finger_value,
-                             &local_best_known_destination,
-                             &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_destination)))
+  /* 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)))
   {
-    struct GNUNET_PeerIdentity *closest_peer;
-    
-    /* Select best successor among one found locally and current_destination.*/
-    closest_peer = select_closest_peer (&local_best_known_destination,
-                                        &current_destination,
-                                        ultimate_destination_finger_value,
-                                        is_predecessor);
-    if (0 == GNUNET_CRYPTO_cmp_peer_identity (&current_destination, 
-                                              closest_peer))
+    /* 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))
     {
-      next_hop = GDS_ROUTING_get_next_hop (intermediate_trail_id,
-                                           GDS_ROUTING_SRC_TO_DEST);
-      if (NULL == next_hop) /* 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. */
-      {
-        GNUNET_break_op (0);
-        return GNUNET_SYSERR;
-      }
-      
-      local_best_known_destination =  current_destination;
-      new_intermediate_trail_id = intermediate_trail_id;
+      GDS_ROUTING_add (trail_id, *peer, my_identity);
     }
-  }
-  
-  GNUNET_assert (NULL != next_hop);
-  
-  /* Am I the final destination? */
-  if (0 == (GNUNET_CRYPTO_cmp_peer_identity (next_hop, &my_identity)))
-  {
     if (0 == trail_length)
       memcpy (&next_peer, &source, sizeof (struct GNUNET_PeerIdentity));
     else
@@ -3372,23 +3819,28 @@ handle_dht_p2p_trail_setup (void *cls, const struct GNUNET_PeerIdentity *peer,
                                             my_identity,
                                             target_friend, trail_length,
                                             trail_peer_list,
-                                            ultimate_destination_finger_value,
+                                            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);
+    target_friend = 
+            GNUNET_CONTAINER_multipeermap_get (friend_peermap,
+                                               next_hop_towards_local_best_known_dest);
     GDS_NEIGHBOURS_send_trail_setup (source,
-                                     ultimate_destination_finger_value,
-                                     local_best_known_destination,
+                                     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;
 }
 
@@ -3396,6 +3848,9 @@ handle_dht_p2p_trail_setup (void *cls, const struct GNUNET_PeerIdentity *peer,
 /* 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
@@ -3416,19 +3871,20 @@ is_sender_peer_correct (const struct GNUNET_PeerIdentity *trail_peer_list,
 {
   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)
     {
-      // source, then trail_length > 0, trail_peer_list[0] != peer
       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&trail_peer_list[0],
                                                 sender_peer))
         return GNUNET_NO;
     }
     else
     {
-      // source, trail_length == 0, finger != peer
+      /* Is finger the sender peer? */
       if (0 != GNUNET_CRYPTO_cmp_peer_identity (sender_peer,
                                                 &finger_identity))
         return GNUNET_NO;
@@ -3436,20 +3892,22 @@ is_sender_peer_correct (const struct GNUNET_PeerIdentity *trail_peer_list,
   }
   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;
     
-    // my_index == trail_length -1, finger != peer
+    /* I am the last element in the trail. */
     if ((trail_length - 1) == my_index)
     {
+      /* Is finger the sender_peer? */
       if (0 != GNUNET_CRYPTO_cmp_peer_identity (sender_peer,
                                                 &finger_identity))
         return GNUNET_NO;
     }
     else
     {
-      // FIXME: if trail_peer_list[my_index + 1] != peer
+      /* 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;
@@ -3460,6 +3918,8 @@ is_sender_peer_correct (const struct GNUNET_PeerIdentity *trail_peer_list,
 
 
 /**
+ * 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
@@ -3507,6 +3967,7 @@ handle_dht_p2p_trail_setup_result(void *cls, const struct GNUNET_PeerIdentity *p
   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. */
@@ -3522,12 +3983,19 @@ handle_dht_p2p_trail_setup_result(void *cls, const struct GNUNET_PeerIdentity *p
   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))
+    {
+      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;
   }
   
+  /* Get my location in the trail. */
   my_index = search_my_index(trail_peer_list, trail_length);
   if (-1 == my_index)
   {
@@ -3541,8 +4009,7 @@ handle_dht_p2p_trail_setup_result(void *cls, const struct GNUNET_PeerIdentity *p
     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.
-   */
+   * table as querying peer will discard the trail. */
   if (0 != (GNUNET_CRYPTO_cmp_peer_identity (&(trail_result->querying_peer),
                                              &(trail_result->finger_identity))))
   {
@@ -3572,7 +4039,7 @@ invert_trail (const struct GNUNET_PeerIdentity *trail,
   int i;
   int j;
   struct GNUNET_PeerIdentity *inverted_trail;
-
   inverted_trail = GNUNET_malloc (sizeof(struct GNUNET_PeerIdentity) *
                                   trail_length);
   i = 0;
@@ -3588,159 +4055,220 @@ invert_trail (const struct GNUNET_PeerIdentity *trail,
 
 
 /**
- * FIXME: 
- * my_current_predecessor != source_peer. get the trail to reach to 
- * my_current_predecessor and append it to the trail from source to me.
- * It can contain duplicate elements. Need to get the correct one. 
- * In case the source peer of verify successor message is not my successor,
- * then construct a trail from source peer to my current predecessor.
+ * 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 new_trail_length [out] Total number of peers in updated 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 *new_trail_length)
+                                unsigned int *trail_length)
 {
-  struct GNUNET_PeerIdentity *new_trail;
-  struct Trail *trail_list_iterator;
-  struct Trail_Element *trail_iterator;
+  struct GNUNET_PeerIdentity *trail_me_to_predecessor;
+  struct Trail *trail;
+  struct Trail_Element *trail_element;
   struct FingerInfo *my_predecessor;
   unsigned int i;
-  unsigned int j;
   unsigned int shortest_trail_length = 0;
   unsigned int trail_index = 0;
  
-  my_predecessor = GNUNET_CONTAINER_multihashmap32_get (finger_hashmap,
-                                                        PREDECESSOR_FINGER_ID);
-
+  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_list_iterator = &my_predecessor->trail_list[i];
-    if (trail_list_iterator->trail_length > shortest_trail_length)
+    trail = &my_predecessor->trail_list[i];
+    if (trail->trail_length > shortest_trail_length)
       continue;
-    shortest_trail_length = trail_list_iterator->trail_length;
+    shortest_trail_length = trail->trail_length;
     trail_index = i;
   }
 
-  *new_trail_length = current_trail_length + shortest_trail_length + 1;
-  new_trail = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity) *
-                             *new_trail_length);
-  memcpy (new_trail, current_trail,
-         current_trail_length * sizeof (struct GNUNET_PeerIdentity));
-  new_trail[current_trail_length + 1] = my_identity;
-
+  *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;
-  j = current_trail_length + 1;
-  trail_list_iterator = &my_predecessor->trail_list[trail_index];
-  trail_iterator = trail_list_iterator->trail_head;
+  trail = &my_predecessor->trail_list[trail_index];
+  trail_element = trail->trail_head;
   while ( i < shortest_trail_length)
   {
-    new_trail[j] = trail_iterator->peer;
-    j++;
+    trail_me_to_predecessor[i] = trail_element->peer;
     i++;
-    trail_iterator = trail_iterator->next;
+    trail_element = trail_element->next;
   }
 
-  *new_trail_length = j;
-  return new_trail;
+  return trail_me_to_predecessor;
 }
 
 
 /**
- * FIMXE: IF you update your predecessor with new finger identity or added
- * a new trail, then you should send add_trail message or else the peers
- * which are part of the trail to reach to your new predecessor will not 
- * know its existence.
- * Check if we already have an entry for predecessor in our finger hashmap.
- * If no, then add new predecessor.
- * If yes, then compare new and existing entry. If both are same, and there is
- * place to store more trail, then add entry. If both are different then choose
- * the closest one. 
- * @param finger Peer which claims to be our predecessor.
- * @param trail Trail to reach from @a predecessor to me, NOT including both endpoints
- * @param trail_length Total number of peers in @a trail.
- * @return #GNUNET_YES if we added the new entry.
- *         #GNUNET_NO, if new entry is not the closest predecessor or both new
- *                     and existing entry are same. 
+ * 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 struct GNUNET_PeerIdentity 
-compare_and_update_predecessor (struct GNUNET_PeerIdentity finger_identity,
-                                const struct GNUNET_PeerIdentity *trail,
+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;
-  struct GNUNET_PeerIdentity *inverted_trail;
-  struct GNUNET_HashCode trail_id;
-  uint64_t finger_value;
+  uint64_t predecessor_value;
   
-  current_predecessor = GNUNET_CONTAINER_multihashmap32_get (finger_hashmap,
-                                                             PREDECESSOR_FINGER_ID);
-  inverted_trail = invert_trail (trail, trail_length);
-  
-  /* No predecessor in finger table. Add the new predecessor. */
-  if (NULL == current_predecessor)
+  current_predecessor = &finger_table[PREDECESSOR_FINGER_ID];
+
+  /* No predecessor. Add finger as your predecessor. */
+  if (GNUNET_NO == current_predecessor->is_present) 
   {
-    add_new_entry (finger_identity, inverted_trail, trail_length,
-                   trail_id, PREDECESSOR_FINGER_ID);
-    return finger_identity;
+    update_predecessor (finger, trail, trail_length);
+    return;
   }
   
-  /* If the new predecessor and current predecessor are not same, then choose
-   the closest one. */
-  if (0 != GNUNET_CRYPTO_cmp_peer_identity (&finger_identity, 
-                                            &current_predecessor->finger_identity))
-  {
-    finger_value = compute_predecessor_identity_value();
-    closest_peer = select_closest_peer (&current_predecessor->finger_identity,
-                                        &finger_identity,
-                                        finger_value, PREDECESSOR_FINGER_ID);
-    
-    /* If the finger is the closest predecessor, then add it in finger table
-     * and free resources of current_predecessor. */
-    if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger_identity, closest_peer))
-    {
-      GNUNET_assert (0 != GNUNET_CRYPTO_cmp_peer_identity (&my_identity,
-                                                           &finger_identity));
-
-      send_trail_teardown (current_predecessor);
-      decrement_friend_trail_count (current_predecessor);
-      free_finger (current_predecessor);
-      add_new_entry (finger_identity, inverted_trail, trail_length,
-                     trail_id, PREDECESSOR_FINGER_ID);
-      return finger_identity;
-    }
-  }
+  predecessor_value = compute_finger_identity_value (PREDECESSOR_FINGER_ID);
+  closest_peer = select_closest_peer (&finger, 
+                                      &current_predecessor->finger_identity,
+                                      predecessor_value, PREDECESSOR_FINGER_ID);
   
-  /* If both finger and current_predecessor are same as my_identity, then do nothing. */
-  if (0 == GNUNET_CRYPTO_cmp_peer_identity (&finger_identity, &my_identity))
-      return current_predecessor->finger_identity;
-    
-  /* If the current_predecessor is not a friend. */
-  if (NULL ==
-        GNUNET_CONTAINER_multipeermap_get (friend_peermap,
-                                           &current_predecessor->finger_identity))
+  /* Finger is the closest predecessor. Remove the existing one and add the new
+     one. */
+  if (0 == GNUNET_CRYPTO_cmp_peer_identity (closest_peer, &finger))
   {
-    if (current_predecessor->trails_count < MAXIMUM_TRAILS_PER_FINGER)
-      add_new_trail (current_predecessor, inverted_trail, 
-                     trail_length, trail_id);
-    //FIXME: here you should send add a new trail as you don't have this trail
-    // in the routing table. 
-    else
-      select_and_replace_trail (current_predecessor, inverted_trail,
-                                trail_length, trail_id);
-     //FIXME: here you should send add a new trail as you don't have this trail
-    // in the routing table. 
+    remove_existing_finger (current_predecessor, PREDECESSOR_FINGER_ID);
+    update_predecessor (finger, trail, trail_length);
+    return;
   }
-  return current_predecessor->finger_identity;
+  return;
 }
 
 
-/**
+/* 
+ * 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
@@ -3748,30 +4276,35 @@ compare_and_update_predecessor (struct GNUNET_PeerIdentity finger_identity,
  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
  */
 static int
-handle_dht_p2p_verify_successor(void *cls, const struct GNUNET_PeerIdentity *peer,
+handle_dht_p2p_verify_successor(void *cls, 
+                                const struct GNUNET_PeerIdentity *peer,
                                 const struct GNUNET_MessageHeader *message)
 {
-  struct PeerVerifySuccessorMessage *vsm;
+  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 *trail_to_predecessor;
+  struct FingerInfo *current_predecessor;
   struct FriendInfo *target_friend;
-  struct GNUNET_HashCode trail_id;
-  struct GNUNET_PeerIdentity current_predecessor;
-  struct GNUNET_PeerIdentity *trail;
-  struct GNUNET_PeerIdentity *new_trail;
-  unsigned int trail_length;
-  unsigned int new_trail_length;
+  unsigned int trail_to_predecessor_length;
   size_t msize;
-
+  unsigned int trail_length;
+  
   msize = ntohs (message->size);
-  if (msize != sizeof (struct PeerVerifySuccessorMessage))
+  
+  /* 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;
   }
-
-  vsm = (struct PeerVerifySuccessorMessage *) message;
+  
+  vsm = (const struct PeerVerifySuccessorMessage *) message;
   trail_length = (msize - sizeof (struct PeerVerifySuccessorMessage))/
                   sizeof (struct GNUNET_PeerIdentity);
   if ((msize - sizeof (struct PeerVerifySuccessorMessage)) % 
@@ -3779,13 +4312,19 @@ handle_dht_p2p_verify_successor(void *cls, const struct GNUNET_PeerIdentity *pee
   {
     GNUNET_break_op (0);
     return GNUNET_OK;      
-  }           
+  } 
   
-  trail = (struct GNUNET_PeerIdentity *)&vsm[1];
+  trail_id = vsm->trail_id;
   source_peer = vsm->source_peer;
   successor = vsm->successor;
-  trail_id = vsm->trail_id;
-
+  trail = (struct GNUNET_PeerIdentity *)&vsm[1];
+  
+  //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. 
+  
   /* 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)))
@@ -3797,31 +4336,49 @@ handle_dht_p2p_verify_successor(void *cls, const struct GNUNET_PeerIdentity *pee
       return GNUNET_SYSERR;
     }
     target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, next_hop);
+
     GDS_NEIGHBOURS_send_verify_successor_message (source_peer, successor,
                                                   trail_id, trail, trail_length,
                                                   target_friend);
     return GNUNET_OK;
   }
   
-  target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, peer);
-  current_predecessor = compare_and_update_predecessor (source_peer, 
-                                                        trail, trail_length);
-  /* source_peer is my current_predecessor. */
-  if(0 == (GNUNET_CRYPTO_cmp_peer_identity (&current_predecessor, &source_peer)))
+  /* I am the destination of this message. */
+  
+  /* Check if there is a predecessor or not. */
+  compare_and_update_predecessor (source_peer, trail, trail_length);
+  
+  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)))
   {
-    /* Here we don't need to pass the trail as it is of new use. We can pass
-     NULL and trail length = 0. */
-    new_trail = NULL;
-    new_trail_length = 0;
+    trail_to_predecessor = NULL;
+    trail_to_predecessor_length = 0;
   }
   else
-  { 
-    new_trail = trail_source_to_my_predecessor (trail, trail_length, 
-                                                &new_trail_length);
+  {
+    if (NULL == (GNUNET_CONTAINER_multipeermap_get (friend_peermap, 
+                                                    &current_predecessor->finger_identity)))
+    {
+      /* 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
+    {
+      trail_to_predecessor = NULL;
+      trail_to_predecessor_length = 0;
+    }
   }
+  
+  target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, peer);
   GDS_NEIGHBOURS_send_verify_successor_result (source_peer, my_identity,
-                                               current_predecessor, trail_id,
-                                               new_trail, new_trail_length,
+                                               current_predecessor->finger_identity,
+                                               trail_id, trail_to_predecessor,
+                                               trail_to_predecessor_length,
                                                GDS_ROUTING_DEST_TO_SRC,
                                                target_friend);
   return GNUNET_OK;
@@ -3829,13 +4386,144 @@ handle_dht_p2p_verify_successor(void *cls, const struct GNUNET_PeerIdentity *pee
 
 
 /**
- * Here you may or may not be the predecessor. If you are then also while adding
- * you have to check and if not then notify new successor. But again the trail
- * may be a problem here. 
- * FIXME: I will keep the logic to remove the old trail to reach from me to
- * my old successor here and move adding a new trail from me to new successor to notify
- * new successor. And in case if the new successor also take it as predecessor
- * then call add_trail.
+ * 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 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_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;
+}
+
+
+/**
+ * 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 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)
+{
+  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;
+  
+  current_successor = &finger_table[0];
+  GNUNET_assert (GNUNET_YES == current_successor->is_present);
+  
+  /* 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 probable successor is not a friend, then add an entry in your own
+   routing table. */
+  if (trail_to_new_successor_length > 0)
+  {
+    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
+  {
+    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap, 
+                                                       &probable_successor);
+  }
+  
+  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
@@ -3843,91 +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)
 {
-  struct PeerVerifySuccessorResultMessage *vsrm;
+  const struct PeerVerifySuccessorResultMessage *vsrm;
   enum GDS_ROUTING_trail_direction trail_direction;
-  struct GNUNET_HashCode trail_id;
-  unsigned int new_trail_length;
-  struct GNUNET_PeerIdentity *new_trail;
   struct GNUNET_PeerIdentity querying_peer;
-  struct GNUNET_PeerIdentity current_predecessor;
-  //struct GNUNET_PeerIdentity old_successor;
+  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;
 
   msize = ntohs (message->size);
-  if (msize != sizeof (struct PeerVerifySuccessorResultMessage))
+  /* 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 = (struct PeerVerifySuccessorResultMessage *) message;
-  new_trail_length = (msize - sizeof (struct PeerTrailSetupMessage))/
+  
+  vsrm = (const struct PeerVerifySuccessorResultMessage *) message;
+  trail_length = (msize - sizeof (struct PeerVerifySuccessorResultMessage))/
                       sizeof (struct GNUNET_PeerIdentity);
-  if ((msize - sizeof (struct PeerTrailSetupMessage)) % 
+  
+  if ((msize - sizeof (struct PeerVerifySuccessorResultMessage)) % 
       sizeof (struct GNUNET_PeerIdentity) != 0)
   {
     GNUNET_break_op (0);
     return GNUNET_OK;      
-  }           
+  }  
+  
+  trail = (const struct GNUNET_PeerIdentity *) &vsrm[1];
+  querying_peer = vsrm->querying_peer;
   trail_direction = ntohl (vsrm->trail_direction);
   trail_id = vsrm->trail_id;
-
-  new_trail = (struct GNUNET_PeerIdentity *) &vsrm[1];
-  querying_peer = vsrm->querying_peer;
-  current_predecessor = vsrm->current_predecessor;
-  //old_successor = vsrm->source_successor;
-
+  probable_successor = vsrm->probable_successor;
+  
+  //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)))
   {
-#if 0
-    //Here I am the final quering peer and its verify successor result.
-    // now I know it is for successor and now I don't have any finger_map_index
-    // as parameter in finger_table_add. 
-    // BIG FIX HOW TO ADAPT IT FOR change in finger_table_add
-    struct GNUNET_HashCode new_finger_trail_id;
-    /* FIXME: generate a new trail id. */
-    if (GNUNET_YES == finger_table_add (my_new_successor,
-                                        new_trail,
-                                        new_trail_length,
-                                        PREDECESSOR_FINGER_ID, new_finger_trail_id))
-    {
-      if (new_trail_length > 0)
-        target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
-                                                           &new_trail[0]);
-      else
-        target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
-                                                           peer);
-      GDS_NEIGHBOURS_send_trail_teardown (my_identity, old_successor, trail_id,
-                                          GDS_ROUTING_SRC_TO_DEST, target_friend);
-      GDS_NEIGHBOURS_send_notify_new_successor (my_identity, my_new_successor,
-                                                new_trail,
-                                                new_trail_length,
-                                                new_finger_trail_id, target_friend);
-    }
-#endif
+    compare_and_update_successor (probable_successor, trail, trail_length);
     return GNUNET_OK;
   }
-
+  
+  /*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->source_successor,
-                                               current_predecessor, trail_id,
-                                               new_trail,
-                                               new_trail_length,
+                                               vsrm->current_successor,
+                                               probable_successor, trail_id,
+                                               trail,
+                                               trail_length,
                                                trail_direction, target_friend);
   return GNUNET_OK;
 }
 
 
-/*
- * FIXME: here before adding the peer you again have to call to check 
- * if its correct predecessor or not.
+/* 
+ * 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
@@ -3935,29 +4612,30 @@ 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)
 {
-  struct PeerNotifyNewSuccessorMessage *nsm;
+  const struct PeerNotifyNewSuccessorMessage *nsm;
   struct GNUNET_PeerIdentity *trail;
   struct GNUNET_PeerIdentity source;
   struct GNUNET_PeerIdentity new_successor;
-  struct FriendInfo *target_friend;
-  struct GNUNET_PeerIdentity closest_successor;
   struct GNUNET_HashCode trail_id;
-  unsigned int my_index;
   struct GNUNET_PeerIdentity next_hop;
+  struct FriendInfo *target_friend;
+  int my_index;
   size_t msize;
   uint32_t trail_length;
 
   msize = ntohs (message->size);
-  if (msize != sizeof (struct PeerNotifyNewSuccessorMessage))
+  /* We have the trail to reach from source to new successor. */
+  if (msize < sizeof (struct PeerNotifyNewSuccessorMessage))
   {
     GNUNET_break_op (0);
     return GNUNET_YES;
   }
 
-  nsm = (struct PeerNotifyNewSuccessorMessage *) message;
+  nsm = (const struct PeerNotifyNewSuccessorMessage *) message;
   trail_length = (msize - sizeof (struct PeerNotifyNewSuccessorMessage))/
                   sizeof (struct GNUNET_PeerIdentity);
   if ((msize - sizeof (struct PeerTrailRejectionMessage)) % 
@@ -3965,42 +4643,28 @@ handle_dht_p2p_notify_new_successor(void *cls, const struct GNUNET_PeerIdentity
   {
     GNUNET_break_op (0);
     return GNUNET_OK;      
-  }  
-
-  if ((msize < sizeof (struct PeerNotifyNewSuccessorMessage) +
-               trail_length * sizeof (struct GNUNET_PeerIdentity)) ||
-      (trail_length >
-       GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
-  {
-    GNUNET_break_op (0);
-    return GNUNET_YES;
   }
-
+  
   trail = (struct GNUNET_PeerIdentity *) &nsm[1];
   source  = nsm->source_peer;
   new_successor = nsm->new_successor;
-  trail_id = nsm->trail_id;
-
+  trail_id = nsm->trail_id;  
+  
+  //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))
   {
-    closest_successor = compare_and_update_predecessor (source, trail, trail_length);
-    /* If the source peer is my new predecessor, then add trail in the
-     routing table of all the peers which are part of the trail to reach from 
-     me to source, NOT including endpoints. 
-     FIXME: In case we have same predecessor but we added just a new trail, then
-     we are not sending add a new trail message. Need to update this. */
-    if (0 == GNUNET_CRYPTO_cmp_peer_identity (&closest_successor, &source))
+    /* Add an entry in routing table only if new predecessor is not a friend. */
+    if (NULL == GNUNET_CONTAINER_multipeermap_get(friend_peermap, &source))
     {
-      struct GNUNET_HashCode new_trail_id;
-      target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
-                                                         peer);
-      GDS_NEIGHBOURS_send_add_trail (my_identity, source, new_trail_id,
-                                     trail, trail_length, target_friend);
+      GDS_ROUTING_add (trail_id, *peer, my_identity);
     }
+    compare_and_update_predecessor (source, trail, 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)
   {
@@ -4011,17 +4675,33 @@ handle_dht_p2p_notify_new_successor(void *cls, const struct GNUNET_PeerIdentity
     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: Here you should keep the trail id with you.
+ * 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
@@ -4029,12 +4709,13 @@ handle_dht_p2p_notify_new_successor(void *cls, const struct GNUNET_PeerIdentity
  * @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)
+handle_dht_p2p_trail_setup_rejection (void *cls,
+                                      const struct GNUNET_PeerIdentity *peer,
+                                      const struct GNUNET_MessageHeader *message)
 {
-  struct PeerTrailRejectionMessage *trail_rejection;
+  const struct PeerTrailRejectionMessage *trail_rejection;
   unsigned int trail_length;
-  struct GNUNET_PeerIdentity *trail_peer_list;
+  const struct GNUNET_PeerIdentity *trail_peer_list;
   struct FriendInfo *target_friend;
   struct GNUNET_TIME_Relative congestion_timeout;
   struct GNUNET_HashCode trail_id;
@@ -4048,13 +4729,14 @@ handle_dht_p2p_trail_rejection(void *cls, const struct GNUNET_PeerIdentity *peer
   size_t msize;
 
   msize = ntohs (message->size);
-  if (msize != sizeof (struct PeerTrailRejectionMessage))
+  /* 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_rejection = (const struct PeerTrailRejectionMessage *) message;
   trail_length = (msize - sizeof (struct PeerTrailRejectionMessage))/
                   sizeof (struct GNUNET_PeerIdentity);
   if ((msize - sizeof (struct PeerTrailRejectionMessage)) % 
@@ -4064,30 +4746,32 @@ handle_dht_p2p_trail_rejection(void *cls, const struct GNUNET_PeerIdentity *peer
     return GNUNET_OK;      
   }           
 
-  trail_peer_list = (struct GNUNET_PeerIdentity *)&trail_rejection[1];
+  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 = 
-          trail_rejection->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);
-  target_friend->congestion_timestamp = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
-                                                                 congestion_timeout);
+  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 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;
@@ -4096,7 +4780,9 @@ handle_dht_p2p_trail_rejection(void *cls, const struct GNUNET_PeerIdentity *peer
     }
     else
     {
-      next_hop = &trail_peer_list[trail_length - 2];
+      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));
@@ -4109,7 +4795,8 @@ handle_dht_p2p_trail_rejection(void *cls, const struct GNUNET_PeerIdentity *peer
                                          my_identity, is_predecessor,
                                          new_trail,new_trail_length,trail_id,
                                          target_friend, CONGESTION_TIMEOUT);
-    return GNUNET_YES;
+    GNUNET_free (new_trail);
+    return GNUNET_OK;
   }
 
   /* Look for next_hop to pass the trail setup message */
@@ -4117,14 +4804,26 @@ handle_dht_p2p_trail_rejection(void *cls, const struct GNUNET_PeerIdentity *peer
                              &next_destination,
                              &new_intermediate_trail_id,
                              is_predecessor);
-
-  if (0 == (GNUNET_CRYPTO_cmp_peer_identity (next_hop, &my_identity)))/* This means I am the final destination */
+  
+  /* 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
       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,
@@ -4149,12 +4848,16 @@ handle_dht_p2p_trail_rejection(void *cls, const struct GNUNET_PeerIdentity *peer
                                      is_predecessor, trail_id,
                                      &new_intermediate_trail_id);
   }
+  GNUNET_free (next_hop);
   return GNUNET_OK;
 }
 
 
 /*
- * 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
@@ -4162,46 +4865,48 @@ handle_dht_p2p_trail_rejection(void *cls, const struct GNUNET_PeerIdentity *peer
  */
 static int
 handle_dht_p2p_trail_compression (void *cls, const struct GNUNET_PeerIdentity *peer,
-                               const struct GNUNET_MessageHeader *message)
+                                  const struct GNUNET_MessageHeader *message)
 {
-  struct PeerTrailCompressionMessage *trail_compression;
+  const struct PeerTrailCompressionMessage *trail_compression;
   struct GNUNET_PeerIdentity *next_hop;
-  struct GNUNET_HashCode trail_id;
   struct FriendInfo *target_friend;
+  struct GNUNET_HashCode trail_id;
   size_t msize;
 
   msize = ntohs (message->size);
+  /* Here we pass only the trail id. */
   if (msize != sizeof (struct PeerTrailCompressionMessage))
   {
     GNUNET_break_op (0);
     return GNUNET_OK;
   }
-
-  trail_compression = (struct PeerTrailCompressionMessage *) message;
+  
+  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. 
+  
+  /* 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)))
   {
-     if(0 != (GNUNET_CRYPTO_cmp_peer_identity (&(trail_compression->destination_peer),
-                                               &my_identity)))
-     {
-       GDS_ROUTING_update_trail_prev_hop (trail_id,
-                                          trail_compression->source_peer);
-     }
-     return GNUNET_OK;
+    /* Update your prev hop to source of this message. */
+    GDS_ROUTING_update_trail_prev_hop (trail_id,
+                                       trail_compression->source_peer);
+    return GNUNET_OK;
   }
-
+  
+  /* 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); /*FIXME: How to handle this case.  */
+    GNUNET_break (0); 
     return GNUNET_OK;
   }
+  
   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_compression->destination_peer,
                                          trail_id,
                                          trail_compression->new_first_friend,
                                          target_friend);
@@ -4210,63 +4915,72 @@ handle_dht_p2p_trail_compression (void *cls, const struct GNUNET_PeerIdentity *p
 
 
 /**
+ * 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 peer identity this notification is about
+ * @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)
 {
-  struct PeerTrailTearDownMessage *trail_teardown;
-  struct GNUNET_HashCode trail_id;
+  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))
   {
     GNUNET_break_op (0);
     return GNUNET_OK;
   }
-
-  trail_teardown = (struct PeerTrailTearDownMessage *) message;
+  
+  trail_teardown = (const struct PeerTrailTearDownMessage *) message;
   trail_direction = ntohl (trail_teardown->trail_direction);
-  trail_id = trail_teardown->TRAIL_ID;
-
-  if (0 != GNUNET_CRYPTO_cmp_peer_identity (&my_identity,
-                                            &trail_teardown->destination_peer))
+  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))
   {
-    struct GNUNET_PeerIdentity *next_hop;
-    struct FriendInfo *target_friend;
-
-    next_hop = GDS_ROUTING_get_next_hop (trail_id, trail_direction);
-    if (NULL == next_hop)
-    {
-      GNUNET_break (0);
-      return GNUNET_SYSERR;
-    }
-
-    target_friend = GNUNET_CONTAINER_multipeermap_get (friend_peermap,
-                                                       next_hop);
-    GNUNET_assert (GNUNET_YES == GDS_ROUTING_remove_trail (trail_id));
-    GDS_NEIGHBOURS_send_trail_teardown (trail_teardown->source_peer,
-                                        trail_teardown->destination_peer,
-                                        trail_id, trail_direction,
-                                        target_friend);
+    GNUNET_break (0);
+    return GNUNET_SYSERR;
   }
+  GNUNET_free_non_null (prev_hop);
+  
+  next_hop = GDS_ROUTING_get_next_hop (trail_id, trail_direction);
+  if (NULL == next_hop)
+  {
+    GNUNET_break (0);
+    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;
 }
 
 
 /**
- * Fixme: this function is called only in case in notify new successor, the new
- * successor wants to add the source of the peer as its predecessor. Identify
- * if there is any other use case where it is required and if yes then adapt the
- * code for it.
- * Core handle for p2p add trail message.
+ * 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
@@ -4276,8 +4990,8 @@ static int
 handle_dht_p2p_add_trail (void *cls, const struct GNUNET_PeerIdentity *peer,
                           const struct GNUNET_MessageHeader *message)
 {
-  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;
@@ -4287,13 +5001,15 @@ handle_dht_p2p_add_trail (void *cls, const struct GNUNET_PeerIdentity *peer,
   size_t msize;
 
   msize = ntohs (message->size);
-  if (msize != sizeof (struct PeerAddTrailMessage))
+  /* 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;
+  add_trail = (const struct PeerAddTrailMessage *) message;
   trail_length = (msize - sizeof (struct PeerAddTrailMessage))/
                   sizeof (struct GNUNET_PeerIdentity);
   if ((msize - sizeof (struct PeerAddTrailMessage)) % 
@@ -4303,25 +5019,21 @@ handle_dht_p2p_add_trail (void *cls, const struct GNUNET_PeerIdentity *peer,
     return GNUNET_OK;      
   }           
 
-  if ((msize < sizeof (struct PeerAddTrailMessage) +
-               trail_length * sizeof (struct GNUNET_PeerIdentity)) ||
-      (trail_length >
-       GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
-  {
-    GNUNET_break_op (0);
-    return GNUNET_OK;
-  }
-
-  trail = (struct GNUNET_PeerIdentity *)&add_trail[1];
+  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;
 
-  if (0 != GNUNET_CRYPTO_cmp_peer_identity (&my_identity,
-                                            &destination_peer))
+  //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.
+  
+  /* I am not the destination of the trail. */
+  if (0 != GNUNET_CRYPTO_cmp_peer_identity (&my_identity, &destination_peer))
   {
     struct FriendInfo *target_friend;
 
+    /* Get my location in the trail. */
     my_index = search_my_index (trail, trail_length);
     if (GNUNET_SYSERR == my_index)
     {
@@ -4333,68 +5045,121 @@ handle_dht_p2p_add_trail (void *cls, const struct GNUNET_PeerIdentity *peer,
       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;
   }
+  
+  /* 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; call send_trail_teardown_message on all the trails of the finger that
- * you remove. Also you don't need to decerement friend trail count as that
- * friend is removed. But you can not send trail teardown message as the friend
- * is disconnected. then you don't have any next_hop. and in case there are
- * multiple trails. and friend is the first trail then you remove only the trail.
- * Iterate over finger_hashmap, and remove entries if finger is the disconnected
- * peer or if disconnected peer is the first friend in the trail to reach the
- * finger.
- * @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,
-                        uint32_t 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;
-  struct Trail *trail_list;
+  unsigned int matching_trails_count;
   int i;
+  
+  /* 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;
 
-  if (0 == GNUNET_CRYPTO_cmp_peer_identity (&remove_finger->finger_identity,
-                                            disconnected_peer))
+  /* Iterate over all the trails of finger. */
+  for (i = 0; i < remove_finger->trails_count; i++)
   {
-    GNUNET_assert (GNUNET_YES ==
-                   GNUNET_CONTAINER_multihashmap32_remove (finger_hashmap,
-                                                         key,
-                                                         remove_finger));
-    free_finger (remove_finger);
-    return GNUNET_YES;
-  }
+    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))
+    {
+      matching_trails_count++;
+      send_trail_teardown (remove_finger, trail);
+      if (trail->trail_length > 0)
+      free_trail (trail);
+    }
+  }  
+  return matching_trails_count;
+}
 
-  for (i = 0; i< remove_finger->trails_count; i++)
-  {
-    trail_list = &remove_finger->trail_list[i];
-    if (0 == GNUNET_CRYPTO_cmp_peer_identity (&trail_list->trail_head->peer,
-                                                disconnected_peer))
+
+/**
+ * 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;
+  
+  /* 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)
     {
-      GNUNET_assert (GNUNET_YES ==
-                     GNUNET_CONTAINER_multihashmap32_remove (finger_hashmap,
-                                                           key,
-                                                           remove_finger));
-       free_finger (remove_finger);
+      remove_finger->is_present = GNUNET_NO;
+      memset ((void *)&finger_table[i], 0, sizeof (finger_table[i]));
     }
   }
-
-  return GNUNET_YES;
 }
 
 
@@ -4410,31 +5175,32 @@ handle_core_disconnect (void *cls,
 {
   struct FriendInfo *remove_friend;
 
+  /* If disconnected to own identity, then return. */
   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
     return;
 
-  remove_friend =
-      GNUNET_CONTAINER_multipeermap_get (friend_peermap, peer);
-
-  if (NULL == remove_friend)
-  {
-    GNUNET_break (0);
-    return;
-  }
-
-  GNUNET_assert (GNUNET_SYSERR !=
-                 GNUNET_CONTAINER_multihashmap32_iterate (finger_hashmap,
-                                                          &remove_matching_finger,
-                                                          (void *)peer));
+  GNUNET_assert (NULL != (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);
+  
+  /* 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 peer from friend_peermap. */
   GNUNET_assert (GNUNET_YES ==
                  GNUNET_CONTAINER_multipeermap_remove (friend_peermap,
                                                        peer,
                                                        remove_friend));
-
+  
   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);
@@ -4442,6 +5208,7 @@ handle_core_disconnect (void *cls,
   }
   else
     GNUNET_break (0);
+
 }
 
 
@@ -4463,7 +5230,8 @@ handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer_identity)
   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;
@@ -4480,7 +5248,8 @@ handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer_identity)
                                                     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);
 }
@@ -4497,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]));
+    
+  }
 }
 
 
@@ -4516,9 +5309,11 @@ GDS_NEIGHBOURS_init (void)
     {&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_compression, GNUNET_MESSAGE_TYPE_DHT_P2P_TRAIL_COMPRESSION, 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}
   };
@@ -4531,11 +5326,12 @@ GDS_NEIGHBOURS_init (void)
     return GNUNET_SYSERR;
 
   friend_peermap = GNUNET_CONTAINER_multipeermap_create (256, GNUNET_NO);
-  finger_hashmap = GNUNET_CONTAINER_multihashmap32_create (MAX_FINGERS * 4/3);
-
+  finger_table_init ();
+  
   return GNUNET_OK;
 }
 
+
 /**
  * Shutdown neighbours subsystem.
  */
@@ -4552,10 +5348,6 @@ GDS_NEIGHBOURS_done (void)
   GNUNET_CONTAINER_multipeermap_destroy (friend_peermap);
   friend_peermap = NULL;
 
-  GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap32_size (finger_hashmap));
-  GNUNET_CONTAINER_multihashmap32_destroy (finger_hashmap);
-  finger_hashmap = NULL;
-
   if (GNUNET_SCHEDULER_NO_TASK != find_finger_trail_task)
   {
     GNUNET_break (0);