treeCount = Rows ("Tree");

if (treeCount > 0)
{
	treeChoices = {treeCount,2};
	for (k=0; k<treeCount; k=k+1)
	{
		GetString (treeID, Tree, k);
		treeChoices [k][0] = treeID;
		treeChoices [k][1] = "Tree " + treeID;
	}
	
	chosenTree = 0;
	if (treeCount > 1)
	{
		ChoiceList (chosenTree, "Which tree?", 1, SKIP_NONE, treeChoices);
		if (chosenTree < 0)
		{
			return;
		}
	}
	
	ExecuteCommands ("treeAVL2 = "+treeChoices[chosenTree][0] + " ^ 0;leafCount=TipCount("+treeChoices[chosenTree][0]+");"); 
	
	multFactors = {};
	for (k=1; k<Abs(treeAVL2); k=k+1)
	{
		aNode = treeAVL2[k];
		aNodeName = aNode["Name"];
		parentIndex = aNode["Parent"];
		k2 = Abs(aNode["Children"]);
		if (k2)
		{
			currentDepth = aNode["Below"];
			multFactors[aNodeName] = currentDepth;		
			if (parentIndex > 0)
			{
				pInfo = treeAVL2[parentIndex];
				pInfo ["Below"] = pInfo ["Below"] + currentDepth;
				treeAVL2[parentIndex] = pInfo;
			}
		}
		else
		{
			multFactors[aNodeName] = 1;
			pInfo = treeAVL2[parentIndex];
			pInfo ["Below"] = pInfo ["Below"] + 1;
			treeAVL2[parentIndex] = pInfo;
		}
		
	}

	pKeys 			= Rows(multFactors);

	for (k=0; k<Columns(pKeys); k=k+1)
	{
		aNodeName = pKeys[k];
		multFactors[aNodeName] = multFactors[aNodeName] * (leafCount-multFactors[aNodeName]);
	}

	treeAVL2 		= 2*computeTotalDivergence (treeChoices[chosenTree][0])/leafCount/(leafCount-1);
	fprintf (stdout, "Mean pairwise divergence for ",treeChoices[chosenTree][0], " is ", treeAVL2, "\n");
}

/*---------------------------------------------------------*/

function computeTotalDivergence (treeID)
{
	ExecuteCommands ("bNames = BranchName   ("+treeID+",-1);");
	ExecuteCommands ("bLen   = BranchLength ("+treeID+",-1);");
	
	sum = 0;
	
	for (k=0; k<Columns(bNames); k=k+1)
	{
		aNodeName = bNames[k];
		sum = sum + bLen[k]*multFactors[aNodeName];
	}	
	return sum;
}

