import(canvas)

create_emf = canvas.create_emf

Item = struct(x:iterator, y:iterator, style:symbol)

draw(c, items+:Item) {block?:inside_scope} = {
	xCollect = items::x::eval()
	yCollect = items::y::eval()
	[xMax, xMin] = [max(max(xCollect)), min(min(xCollect))]
	[yMax, yMin] = [max(max(yCollect)), min(min(yCollect))]
	#printf("xMin = %f, xMax = %f\n", xMin, xMax)
	#printf("yMin = %f, yMax = %f\n", yMin, yMax)
	[wdMgn, htMgn] = [c.width() * .1, c.height() * .05]
	[wdGraph, htGraph] = [c.width() - wdMgn * 2, c.height() - htMgn * 2]
	[xOff, yOff] = [wdMgn, htMgn]
	nScales = [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000]
	xRange = xMax - xMin
	yRange = yMax - yMin
	if (xRange == 0) { xRange = 1 }
	if (yRange == 0) { yRange = 1 }
	screen_x(x):map = (x - xMin) * wdGraph / xRange + xOff
	screen_y(y):map = (y - yMin) * htGraph / yRange + yOff
	DrawText(x, y, str) = c.moveto(screen_x(x), screen_y(y)).text(str)
	DrawTicks(tMin:number, tMax:number, tRange:number, DrawTick:function) = {
		tStepBase = 10 ** (int(math.log10(tRange)) - 2)
		for (nScale in nScales) {
			tStep = tStepBase * nScale
			if (tRange / tStep < 20) { break() }
		}
		if (tMin > 0) {
			DrawTick(range(math.floor(tMin / tStep) * tStep, tMax, tStep))
		} elsif (tMax < 0) {
			DrawTick(range(math.floor(tMax / tStep) * tStep, tMin, -tStep))
		} else {
			if (tMax > 0) {
				DrawTick(range(tStep, tMax, tStep))
			}
			if (tMin < 0) {
				DrawTick(range(-tStep, tMin, -tStep))
			}
		}
	}
	DrawTickX(x:number, str:string = nil):map:void = {
		if (str == nil) { str = tostring(x) }
		c.moveto(screen_x(x), screen_y(0) - 1).text(str):n
		c.line(screen_x(x), screen_y(0) - 1, screen_x(x), screen_y(0) + 1)
	}
	DrawTickY(y:number, str:string = nil):map:void = {
		if (str == nil) { str = tostring(y) }
		c.moveto(screen_x(0) - 1, screen_y(y)).text(str):e
		c.line(screen_x(0), screen_y(y), screen_x(0) + 1, screen_y(y))
	}
	DrawTicksX() = DrawTicks(xMin, xMax, xRange, DrawTickX)
	DrawTicksY() = DrawTicks(yMin, yMax, yRange, DrawTickY)
	DrawAxis() = {
		c.setpen(`black, 1, `solid)
		c.line(screen_x(0), yOff, screen_x(0), yOff + htGraph)
		c.line(xOff, screen_y(0), xOff + wdGraph, screen_y(0))
	}
	for (item in items) {
		c.setpen(`black, 1, item.style)
		c.polyline(screen_x(item.x):list, screen_y(item.y):list)
	}
	c.setfont(c.height() / 30, family => `swiss)
	if (block != nil) { block(c) }
	c.close()
}
