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


/* ADD NEW RATE CLASS MATRICES HERE */
AminoAcidClasses = {{"EX.dat","Stoltzfus and Yampolsky exhangeability acceptance/rejection profile"}
				     {"Custom","Load a custom profile"}};	
				    
/* END ADD NEW RATE CLASS MATRICES HERE */			    

ChoiceList	(aaModelType,"Amino Acid Class Model",1,SKIP_NONE,AminoAcidClasses);

if (aaModelType < 0)
{
	return 0;
}

allowedAACharacters = "FLIMVSPTAYHQNKDECWRG";
if (aaModelType == Rows(AminoAcidClasses)-1)
{
	SetDialogPrompt ("Locate an amino-acid profile matrix file:");
	fscanf (PROMPT_FOR_FILE,"String,Matrix",mapString,aaRateMatrix);
	W_MATRIX_FILE = LAST_FILE_PATH;
}
else
{
	W_MATRIX_FILE = HYPHY_LIB_DIRECTORY+"TemplateBatchFiles"+DIRECTORY_SEPARATOR+"TemplateModels"+DIRECTORY_SEPARATOR+SELECTION_STRINGS;
	fscanf (W_MATRIX_FILE,"String,NMatrix",mapString,aaRateMatrix);
}


if (Abs(mapString) == 20 && Rows(aaRateMatrix) == 20 && Columns(aaRateMatrix) == 20)
{
	/* check to see that all characters have been mapped */
	checkAAMap   = {}; /* associative array */
	for (aaIndex = 0; aaIndex < 20; aaIndex = aaIndex+1)
	{
		aChar = allowedAACharacters[aaIndex];
		checkAAMap[aChar] = aaIndex+1;
	
	}

	AAMap = {};
	for (aaIndex = 0; aaIndex < 20; aaIndex = aaIndex+1)
	{
		aChar = mapString[aaIndex];
		daIndex = checkAAMap[aChar];
		if (daIndex==0)
		{
			fprintf (stdout, "\nAmino-acid ordering provided in the file is invalid - could be duplicate or missing characters\n");
			return 0;
		}
		else
		{
			if (daIndex>10)
			{
				AAMap[aaIndex] = daIndex;
			}
			else
			{
				AAMap[aaIndex] = daIndex-1;			
			}
			checkAAMap[aChar] = 0;
		}
	}
	
	/*symmetrize the matrix*/
	
	for (aaIndex = 0; aaIndex < 19; aaIndex = aaIndex+1)
	{
		for (aaIndex2 = aaIndex+1; aaIndex2 < 20; aaIndex2 = aaIndex2+1)
		{
			aaRateMatrix[aaIndex2][aaIndex] = aaRateMatrix[aaIndex][aaIndex2];
		}
	}
	
	/* reindex the matrix */
	
	aaRateMultipliers = {21,21};
	
	aaRateClassIDs = {};
	
	for (aaIndex = 0; aaIndex < 19; aaIndex = aaIndex+1)
	{
		mappedIndex = AAMap[aaIndex];
		for (aaIndex2 = aaIndex+1; aaIndex2 < 20; aaIndex2 = aaIndex2+1)
		{
			mappedIndex2 								 = AAMap[aaIndex2];
			rateLabel 									 = aaRateMatrix[aaIndex][aaIndex2];
			aaRateMultipliers[mappedIndex][mappedIndex2] = rateLabel;
			aaRateMultipliers[mappedIndex2][mappedIndex] = rateLabel;
			
			if (aaRateClassIDs[rateLabel] == 0)
			{
				aaRateClassIDs[rateLabel] = 1;
			}
		}
	}
	
	aaRateMatrix = 0;
	
}
else
{
	fprintf (stdout, "\nExpected a string of 20 characters followed by a 20x20 matrix\n");
	return 0;
}
