/* modified MapSubstitutions to produce a matrix of the number of subs in each nuc subs class 
Wayne Delport 30 April 2009
*/

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);
	
	for (k = 0; k < fd[0]; k=k+1)	{
		temparray = _substitutionsBySite ( aid, k );
		if ( k == 0 ) {
			sumArrays = { Columns(temparray["CHARS"]), Columns(temparray["CHARS"]) };
			for ( r = 0; r < Columns(temparray["CHARS"]); r = r + 1 ) { /* better way to initialize? */
				for ( c = 0; c < Columns(temparray["CHARS"]); c = c + 1 ) {
					sumArrays [ r ][ c ] = 0;
				}
			}
		}
		/* fprintf ( stdout, temparray["COUNTS"], "\n" ); */
		sumArrays = sumArrays + temparray["COUNTS"];
	}
	
	fprintf ( stdout, "Inferred number of substitutions\n" );
	fprintf ( stdout, "--------------------------------\n\t" );
	alphabet = temparray["CHARS"];
	for ( i = 0; i < Columns(alphabet); i = i + 1 ) {
		fprintf ( stdout, alphabet[i], "\t");
	}
	fprintf ( stdout, "\n" );
	for ( i = 0; i < Columns(alphabet); i = i + 1 ) {
		for ( j = 0; j < Columns(alphabet); j = j + 1 ) {
			if ( j == 0 ) {
				fprintf ( stdout, alphabet [ i ], "\t" );
			}
			if ( i != j ) {
				fprintf ( stdout, sumArrays [ i ][ j ], "\t" );
			}
			else {
				fprintf ( stdout, "*\t" );
			}
		}
		fprintf ( stdout, "\n" );
	}
	
	/* fprintf ( stdout, sumArrays, "\n" ); */
	SetDialogPrompt ("Save to:");
	fprintf (PROMPT_FOR_FILE, CLEAR_FILE, KEEP_OPEN);
	fprintf ( LAST_FILE_PATH, temparray["CHARS"] );
	fprintf ( LAST_FILE_PATH, sumArrays, "\n" );
	fprintf (LAST_FILE_PATH,CLOSE_FILE);
	_destroyAncestralCache (aid);
}
