// globals
var dodensity_plot;

function preprocess () {
		dodensity_plot = (getValue ("plot_type") == "density_plot");

	if (!dodensity_plot) { 
echo ('require(hdrcde)\n');
	}
}


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

function printout () {
	doPrintout (true);
}

function doPrintout (final) {
		adjust = getValue ("adjust");
	x = getValue ("x");
	resolution = getValue ("n");
	narm = getValue ("narm");
	kern = getValue ("kern");
	if (kern == "gaussian") {
		bw = getValue ("bw");
	}
	dorug = getValue ("rug");

	density_call = "density(" + x;
	if (!empty (bw)) density_call += ", bw=\"" + bw + "\"";
	density_call += ", adjust=" + adjust + ", kern=\"" + kern + "\", n=" + resolution + ", " + narm + ")";

	if (dodensity_plot) title = "Density Plot";
	else title = "Highest density regions";

	if (final) { 
echo ('rk.header ("' + title + '", list ("Variable", rk.get.description (' + x + ')'); if (!empty (bw)) { echo (', "Band Width", "' + bw + '"'); } echo (', "Adjust", ' + adjust) echo (', "Remove Missing Values", ' + narm) echo (', "Length", length (' + x + '), "Resolution", ' + resolution + ', "Smoothing Kernel", "' + kern + '"))\n');
echo ('\n');
echo ('rk.graph.on ()\n');
	}
		
echo ('try ({\n');
	if (dodensity_plot) { 
echo ('	plot(' + density_call + getValue ("plotoptions.code.printout") + ')\n');
	} else { 
echo ('	hdr.den(den=' + density_call + getValue ("plotoptions.code.printout") + ')\n');
	}
	if (dorug) { 
echo ('	rug(' + x + ', ' + getValue ("rug_ticksize") + ', ' + getValue ("rug_lwd") + ', ' + getValue ("rug_side") + getValue ("rug_col.code.printout") + ')\n');
	} 
echo ('})\n');
	if (final) { 
echo ('rk.graph.off ()\n');
	}
}

