RequireVersion ("0.9920060424");

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;
		}
	}
	
	
	chosenTree = treeChoices[chosenTree][0];
	
	mxTreeSpec = {5,1};
	mxTreeSpec [0] = chosenTree;
	mxTreeSpec [1] = "8240";
	mxTreeSpec [2] = "10,50,-10,-300,1";
	mxTreeSpec [3] = "EXPECTED_NUMBER_OF_SUBSTITUTIONS";
	mxTreeSpec [4] = "";
	OpenWindow (TREEWINDOW, mxTreeSpec);	
	
	
	ExecuteCommands ("nodeNames = BranchName(`chosenTree`,-1)");
	
	nodeCount = Columns (nodeNames)-1;
	choiceMatrix = {nodeCount,2};
	
	for (bc=0; bc<nodeCount; bc=bc+1)
	{
		choiceMatrix[bc][0] = nodeNames   [bc];
		choiceMatrix[bc][1] = choiceMatrix[bc][0];
	}
	
	ChoiceList  (stOption,"Choose branches to test",1,NO_SKIP,choiceMatrix);

	if (stOption < 0)
	{
		return -1;
	}

	chosenBranch = choiceMatrix[stOption][0];

	lf_Count						    = Rows ("LikelihoodFunction");
	if (lf_Count > 0)
	{
		for (lf_ID = 0; lf_ID < lf_Count; lf_ID = lf_ID + 1)
		{
			GetString (treeID, LikelihoodFunction,lf_ID);
			ExecuteCommands ("GetString(lfInfo,`treeID`,-1);");
			lfTrees = lfInfo["Trees"];
			for (k = 0; k<Columns(lfTrees); k=k+1)
			{
				if (lfTrees[k] == chosenTree)
				{
					break;
				}
			}
			if (k < Columns(lfTrees))
			{
				fprintf (stdout, "\nTree ",Columns(lfTrees)," is a part of likelihood function ", treeID, "\n");
				global			TreeScalerParameter = 1;
				ExecuteCommands	("ClearConstraints(`chosenTree`);");
				
				cte = "ReplicateConstraint (\"this1.`chosenBranch`.?:=TreeScalerParameter*this2.`chosenBranch`.?__\",`chosenTree`,`chosenTree`);";
				ExecuteCommands(cte);

				COVARIANCE_PRECISION = 0.95;
				COVARIANCE_PARAMETER = "TreeScalerParameter";
				ExecuteCommands ("CovarianceMatrix(cmx,"+treeID+");");
				fprintf (stdout, "\nMultiplicative range ", cmx[0], "-", cmx[2], "\n");
				ExecuteCommands ("bl = BranchLength (`chosenTree`,stOption)");
				fprintf (stdout, "\n", chosenBranch, " has a branch length of ", bl, " (", bl*cmx[0],",",bl*cmx[2],")\n");
				
			}
		}
	}
	
}

