int NNI( double[][] avgDistArray, int count )
	{
	  edge e, centerEdge;
	  edge[] edgeArray;
	  direction[] location;
	  heap p,q;
	  int i;
	  int possibleSwaps;
	  double[] weights;
	  p = new heap(size+1);
	  q = new heap(size+1);
	  edgeArray = new edge[size+1];
	  weights = new double[size+1];
	  location = new direction[size+1];
	  for (i=0;i<size+1;i++)
	  {
	      weights[i] = 0.0;
	      location[i] = direction.NONE;
	  }
	  e = root.leftEdge.findBottomLeft(); 
	  /* *count = 0; */
	  while ( null != e )
	  {
	      edgeArray[e.head.index+1] = e;
	      location[e.head.index+1] = 
	    	  NNIEdgeTest( e,avgDistArray,weights,e.head.index+1 );
	      e = depthFirstTraverse( e );
	  } 
	  possibleSwaps = p.makeThreshHeap(q,weights,size+1,0.0);
	  p.permInverse( q,size+1 );
	  /*we put the negative values of weights into a heap, indexed by p
	    with the minimum value pointed to by p[1]*/
	  /*p[i] is index (in edgeArray) of edge with i-th position 
	    in the heap, q[j] is the position of edge j in the heap */
	  while ( weights[p.p[1]] < 0)
	  {
	      centerEdge = edgeArray[p.p[1]];
	      count++;
	      weight += weights[p.p[1]];
	      NNItopSwitch( edgeArray[p.p[1]], location[p.p[1]], avgDistArray );
	      location[p.p[1]] = direction.NONE;
	      weights[p.p[1]] = 0.0;  /*after the NNI, this edge is in optimal
				      configuration*/
	      p.popHeap(q,weights,possibleSwaps--,1);
	      /*but we must retest the other four edges*/
	      e = centerEdge.head.leftEdge;
	      possibleSwaps = NNIRetestEdge( p,q,e,avgDistArray,weights,
	    	  location,possibleSwaps );
	      e = centerEdge.head.rightEdge;
	      possibleSwaps = NNIRetestEdge( p,q,e,avgDistArray,weights,
	    	  location,possibleSwaps );     
	      e = centerEdge.siblingEdge();
	      possibleSwaps = NNIRetestEdge( p,q,e,avgDistArray,weights,
	    	  location,possibleSwaps );
	      e = centerEdge.tail.parentEdge;
	      possibleSwaps = NNIRetestEdge( p,q,e,avgDistArray,weights,
	    	  location,possibleSwaps );
	    }
	  return count;
	}