ExecuteAFile(HYPHY_LIB_DIRECTORY + "TemplateBatchFiles" + DIRECTORY_SEPARATOR + "Utility" + DIRECTORY_SEPARATOR + "AncestralMapper.bf");

likelihoodFnChoice = 0;

if (Rows("LikelihoodFunction")>1)
{
	ChoiceList  (likelihoodFnChoice,"Choose a Likelihood Function",1,NO_SKIP,LikelihoodFunction);
}		

if (likelihoodFnChoice<0)
{
	return;
} 
	
GetString 		(LF_NAME,LikelihoodFunction,likelihoodFnChoice);

ExecuteCommands ("GetString(_lfInfo,"+LF_NAME+",-1);");
_lfPart			= Columns (_lfInfo["Datafilters"]);

if (_lfPart > 1)
{
	choices = {_lfPart, 2};
	for (k = 0; k < _lfPart; k = k+1)
	{
		choices [k][0] =  (_lfInfo["Datafilters"])[k];
		choices [k][1] =  "Associated tree " + (_lfInfo["Trees"])[k];
	}
	ChoiceList  (_lfPart,"Which data filter?",1,NO_SKIP,choices);
}
else
{
	_lfPart = 0;
}

if (_lfPart >= 0)
{
	aid = _buildAncestralCacheInternal (LF_NAME, _lfPart, 0);
	fd  = _filterDimensions (aid);
	
	ChoiceList  (formatChoice,"Output format",1,NO_SKIP,"Newick","Generate a list of annotated Newick trees",
							  "PostScript","Generate a PostScript file with mapped substitutions for each site");
							  
	
	if (formatChoice>=0)
	{
		ChoiceList  (labelChoice,"Label with",1,NO_SKIP,"Inferred character states","Each node is annotated with the observed or inferred character",
								 					    "Substitutions","Branches where substitutions were inferred are annotated as X->Y.",
								 					    "Syn/NS","[FOR CODON DATA] Color branches by whether they have synonymous or non-synonymous substitutions");
		if (labelChoice>=0)
		{
			SetDialogPrompt ("Save to:");
			fprintf (PROMPT_FOR_FILE, CLEAR_FILE, KEEP_OPEN);
			
			if (labelChoice == 2)
			{
				LoadFunctionLibrary ("chooseGeneticCode");
				LoadFunctionLibrary ("CodonTools.def");
			}
			
			for (k = 0; k < fd[0]; k += 1)
			{

				if (labelChoice == 0)
				{
					if (formatChoice == 0)
					{
						fprintf (LAST_FILE_PATH, "Tree T_", (k+1), " = ", _mapCharactersBySiteNewick (aid, k, 1), ";\n");
					}
					else
					{
						fprintf (LAST_FILE_PATH, _mapCharactersBySite (aid, k, 1), "\n");			
					}				
				}
				else
				{
					if (formatChoice == 0)
					{
						fprintf (LAST_FILE_PATH, "Tree T_", (k+1), " = ", _mapSubstitutionsBySiteNewick (aid, k, 1), ";\n");
					}
					else
					{
						if (labelChoice == 1)
						{
							fprintf (LAST_FILE_PATH, _mapSubstitutionsBySite (aid, k, 1), "\n");		
						}
						else
						{
							fprintf (LAST_FILE_PATH, _mapSNSBySite (aid, k, 1), "\n");								
						}	
					}
				}
			}
			fprintf (LAST_FILE_PATH,CLOSE_FILE);
		}
	}
	_destroyAncestralCache (aid);
}
