likelihoodFnChoice = 0;

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

LIKELIHOOD_FUNCTION_OUTPUT = response;
GetString(LF_NAME,LikelihoodFunction,likelihoodFnChoice);

GetString(paramName, LF_NAME, 0);

ExecuteCommands ("DataSet   simmedData = SimulateDataSet ("+LF_NAME+",,myRates,myCatVars);");

if (Rows(myCatVars) != 2)
{
	fprintf (stdout, "ERROR: the likelihood function should depend on two rate category variables\n");
	return 0;
}

catVar1 = myCatVars[0]; /* first cat. variable */
catVar2 = myCatVars[1]; /* second cat. variable */

/* 
	decide which one is for dN and which one is for dS; the one with dN is going to end with "Categ_beta"
	and the one for dS will end with "Categ_alpha" (filter name will serve as a prefix)
	do this by matching regular expressions
*/

regExp1 = "(.+)_Categ_beta$";
regExp2 = "(.+)_Categ_alpha$";

regExpMatch1 = catVar1 $ regExp1;
regExpMatch2 = catVar2 $ regExp2;

site_count = Columns (myRates);

if (regExpMatch1[0] < 0 || regExpMatch2[0] < 0)
{
	regExpMatch1 = catVar1 $ regExp2;
	regExpMatch2 = catVar2 $ regExp1;
	if (regExpMatch1[0] < 0 || regExpMatch2[0] < 0)
	{
		fprintf (stdout, "ERROR: the likelihood function uses an unsupported model\n");
		return 0;
	}
	startAt = regExpMatch1[2];
	endAt   = regExpMatch1[3];
	Rvar	= catVar2[startAt][endAt];
	
	for (k = 0; k<site_count; k=k+1)
	{
		temp = myRates[0][k];
		myRates[0][k] = myRates[1][k];
		myRates[1][k] = temp;
	}	
}
else
{
	startAt = regExpMatch1[2];
	endAt   = regExpMatch1[3];
	Rvar	= catVar1[startAt][endAt];
}

/* dN-dS will actually be of the form dN*R-dS, because of model parameterization 
   get the filterName_Shared_R variable value now */
   

ExecuteCommands ("rval = " + Rvar + "_Shared_R;");
dNdSSimmedRateMatrix = {site_count, 3};

for (k=0; k<site_count;k=k+1)
{
	dNdSSimmedRateMatrix[k][0] = rval*myRates[0][k];
	dNdSSimmedRateMatrix[k][1] = myRates[1][k];
	dNdSSimmedRateMatrix[k][2] = dNdSSimmedRateMatrix[k][0] - dNdSSimmedRateMatrix[k][1];
}

columnHeaders = {{"dN","dS","dN-dS"}};

OpenWindow (CHARTWINDOW,{{"Simulated dN-dS"}
		{"columnHeaders"}
		{"dNdSSimmedRateMatrix"}
		{"Contrast Bars"}
		{"Index"}
		{"dN;dS"}
		{"Codon"}
		{"dS"}
		{"dN"}
		{"0"}
		{""}
		{"-1;-1"}
		{"10;1.309;0.785398"}
		{"Times:12:0;Times:10:0;Times:12:2"}
		{"0;0;13816530;16777215;0;0;6579300;11842740;13158600;14474460;0;3947580;16777215;15670812;6845928;16771158;2984993;9199669;7018159;1460610;16748822;11184810;14173291"}
		{"16,0,0"}
		},
		"725;562;70;70");
		
DataSetFilter simmedFilter = CreateFilter (simmedData,1);
SetDialogPrompt ("Save simulated data to:");
fprintf (PROMPT_FOR_FILE,CLEAR_FILE,simmedFilter);
