// globals
var nAvg;
var nDist;
php


function printout () {
	doPrintout (true);
}

function preview () {
	preprocess ();
	calculate ();
	doPrintout (false);
}

function doPrintout (final) {
	fun = getValue ("function");
	nAvg = getValue ("nAvg"); 
	nDist = getValue ("nDist"); 

	scalenorm = getValue ("scalenorm"); 
	drawnorm = getValue ("drawnorm");


echo ('# parameters:\n');
	doParameters (); 

	if (scalenorm || drawnorm) {

echo ('# mean and variances of the distribution of sample averages:\n');
		doExpVar (); 
	}

	
	if (scalenorm) normMuSigma_tag = ""; 
	else normMuSigma_tag = ", mean = avg.exp, sd = sqrt(avg.var)";

	plotpre = getValue ("plotoptions.code.preprocess");
	plotoptions = getValue ("plotoptions.code.printout");
	plotadds = getValue ("plotoptions.code.calculate");
	if (fun == "hist") {
		normFun = "dnorm"; 
		histcalcoptions = getValue ("histogram_opt.code.calculate"); 
		histplotoptions = getValue ("histogram_opt.code.printout"); 
		histplotoptions += plotoptions; 
	} elseif (fun == "dist") {
		normFun = "pnorm"; 
		plotoptions += getValue ("dist_stepfun.code.printout"); 
	}

	yLim = ""; 


echo ('# generate the entire data:\n');
	doGenerateData (); 


echo ('# get the sample averages:\n');
echo ('avg <- colMeans(data);\n');
	if (scalenorm) {

echo ('# normalise the variables:\n');
echo ('avg <- (avg - avg.exp)/sqrt(avg.var);\n');
	}
	if (drawnorm) {

echo ('# generate random normal samples:\n');
echo ('normX <- seq(from=min(avg), to=max(avg), length=' + nDist + ');\n');
echo ('normY <- ' + normFun + ' (normX' + normMuSigma_tag + ');\n');
	}
	if (fun == "hist") {

echo ('dist.hist <- hist(avg, plot=FALSE' + histcalcoptions + ');\n');
		if (drawnorm) {

echo ('# calculate the ylims appropriately:\n');
echo ('ylim <- c(0,max(c(dist.hist$density, normY)));\n');
			yLim = ', ylim=ylim';
		}
	}
	if (final) {

echo ('rk.graph.on ()\n');
echo ('try ({\n');
	}
	if (!empty (plotpre)) printIndented ("\t", plotpre);
	if (fun == "hist") {

echo ('	plot(dist.hist' + yLim + histplotoptions + ')\n');
	} elseif (fun == "dist") {

echo ('	plot(ecdf(avg)' + plotoptions + ')\n');
	}
	if (drawnorm) {

echo ('	lines (x=normX, y=normY, type="' + getValue ("normpointtype") + '"' + getValue ("normlinecol.code.printout") + ')\n');
	}
	if (!empty (plotadds)) printIndented ("\t", plotadds);
	if (final) {

echo ('})\n');
echo ('rk.graph.off ()\n');
	}
}
