var raster = null;
var dot = null;
var sel = null;

function initRaster() {
	sel = activeDocument.getSelectedItems();
	for (var i = 0; i < sel.length; i++) {
		obj = sel[i];
		if (raster == null && obj instanceof Raster) raster = obj;
		else if (dot == null) dot = obj;
		if (raster != null && dot != null) break;
	}
	return (raster != null && dot != null);
}

function executeRaster(createDot) {
	activeDocument.deselectAll();
	var group = new Group();
	// create a copy of the dot that is moved to the origin so 
	// rasters that scale the dot are simple to realize:
	dot = dot.clone();
	var move = dot.bounds.center;
	dot.translate(move.multiply(-1));
//	var img = raster.getImage();
	for (var y = 0; y < raster.height; y++) {
		for (var x = 0; x < raster.width; x++) {
//			var c = new java.awt.Color(img.getRGB(x, y));
//			var col = 1 - (0.3 * c.red + 0.59  * c.green + 0.11 * c.blue) / 255;
			var c = raster.getPixel(x, y);
			var radius = raster.getPixel(x, y).convert(Color.TYPE_GRAY).gray;
			var obj = createDot(x, raster.height - y, dot, c, radius);
			if (obj) {
				obj.translate(move);
				group.appendChild(obj);
			}
		}
		activeDocument.redraw();
	}
	dot.remove();
	return group;
}

function setColor(art, color) {
	if (art instanceof Path) {
		if (art.style.stroke.color != null) art.style.stroke.color = color;
		if (art.style.fill.color != null) art.style.fill.color = color;
	}
	var child = art.firstChild;
	while (child != null) {
		setColor(child, color);
		child = child.nextSibling;
	}
}

function createDot(x, y, dot, col, radius) {
	if (radius > 0.1) {
		var art = dot.clone();
		setColor(art, col);
		var m = new Matrix();
		m.translate(x * size, y * size);
		m.scale(radius * scale);
		art.transform(m); 
		return art;
	}
	return null;
}

if (initRaster()) {
	values = Dialog.prompt("Enter Raster Values:", [
		{ value: 10, description: "Grid Size:", width: 40 },
		{ value: 100, description: "Object Scale (%):", width: 40 }
	]);
	if (values) {
		var size = values[0], scale = values[1] / 100.0;
		executeRaster(createDot);
	}
}
