#!/bin/ksh
#
# Fetch one ore more karopapier maps and dump them in a human-readable
# ASCII format.
#
# Sample usage for fetching all maps:
#
#	jot 89 | sed 's@.*@fetchmap & > &.map@' | sh

me=${0##*/}
mappreview=http://karopapier.beididi.de/mappreview.php
fetchcmd="ftp -o -"

usage() {
	echo "usage: $me map-id ..." >&2
	exit 1
}

# NOTE: this function currently relies on the following XPM
# color mapping:
#
#	  c #000000
#	. c #808080
#	X c #646464
#	o c #FFFFFF
#	O c #00C800
#	+ c #00B400
#	@ c #0066FF
#	# c None
fetchmap() {
	$fetchcmd "${mappreview}?MID=$1&pixel=2&karoborder=0" |
	pngtopnm |
	ppmtoxpm |
	# Order is important here!
	sed	-e '1,/pixels/d;$d'	\
		-e 's/[",]//g'		\
		-e 's/@./!/g'		\
		-e 's/ ./@/g'		\
		-e 's/[.X]./ /g'	\
		-e 's/[O+]./X/g'	\
		-e 's/o./#/g'		\
		-e 's/^ /=/g'		|
	awk 'NR % 2'
}

[ $# -gt 0 ] || usage

for i; do
	case $i in
	--)	break;;
	-*)	usage;;
	esac
done

for i; do
	case $i in
	--)	;;
	*)	fetchmap "$i";;
	esac
done
