# Parse variables passed from HTML form, using reasonable defaults if
# they are out of range.
#
let maxZoomlevel=5
if ZOOMLEVEL eq '' or ZOOMLEVEL < 0
then
	let ZOOMLEVEL=0
elif ZOOMLEVEL > maxZoomlevel
then
	let ZOOMLEVEL=maxZoomlevel
endif

if LABELS ne 'on' and LABELS ne 'off'
then
	let LABELS='off'
endif

# Create temporary PNG file containing map display for this HTTP request.
#
let imageFile = tempname("PNG")
newpage "png", imageFile, 100, 100

# Display part of dataset, zooming in on centre based on zoom level.
#
dataset "shapefile", "coastline.shp", "dbffields="
let x1 = Mapyrus.dataset.min.x + Mapyrus.dataset.width * (ZOOMLEVEL / (maxZoomlevel * 2 + 1))
let y1 = Mapyrus.dataset.min.y + Mapyrus.dataset.height * (ZOOMLEVEL / (maxZoomlevel * 2 + 1))
let x2 = Mapyrus.dataset.max.x - Mapyrus.dataset.width * (ZOOMLEVEL / (maxZoomlevel * 2 + 1))
let y2 = Mapyrus.dataset.max.y - Mapyrus.dataset.height * (ZOOMLEVEL / (maxZoomlevel * 2 + 1))

worlds x1, y1, x2, y2
while Mapyrus.fetch.more
do
	clearpath
	fetch
	addpath GEOMETRY
	color '#40ff40'
	fill
	color '#7f7f7f'
	stroke
done
let recordCount = Mapyrus.fetch.count

if LABELS eq 'on'
then
	# Display point map containing labels.
	#
	dataset "textfile", "aust_cities.dat", "comments=#"
	color "black"
	font "Helvetica", 3
	justify "right"
	while Mapyrus.fetch.more
	do
		clearpath
		fetch
		let placeName = $0
		fetch
		move $1, $2
		fetch
		fetch
		label placeName
	done
	let recordCount = recordCount + Mapyrus.fetch.count
endif

httpresponse "HTTP/1.0 200 OK
Content-Type: text/html; charset=UTF-8"

print '<html>'
print '<img src="' . imageFile . '">'

# Generate HTML form offering options for changing map display,
# giving current values as defaults.
#
print '<form method=get action="' . Mapyrus.filename . '">'
print 'Zoom level'
print '<select name=ZOOMLEVEL size=1>'
let i = 0
while i <= maxZoomlevel
do
	print '<option value=' . i
	if i == ZOOMLEVEL
	then
		# Select current zoom factor in pop-up list.
		#
		print ' selected'
	endif

	print '>' . i
	let i=i+1
done
print '</select>'

# Add toggle button for labels on/off.
#
print '&nbsp;<input type=checkbox name=LABELS value=on'
if LABELS eq 'on'
then
	print ' checked'
endif
print '> Display Labels'
print '&nbsp;<input type="submit" name="SUBMIT" value="Redisplay">'
print '</form>'

print '<br>Record count ' . recordCount
