#!/bin/bash
set -h
function comma() {
    local X=`echo $1 | rev`
    declare -i N=4
    while [ `echo -n $X | wc -c` -ge $N ]; do
	X=`echo $X | cut -b 1-$[$N-1]`,`echo $X | cut -b $N-`
	N=$N+4
    done
    echo $X | rev
}
function commas() {
    local TYPE X Y
    read TYPE X Y
    echo $TYPE `comma $X` `comma $Y`
}
function order() {
    size "$@" | sort -n +0 +1 +2 | cut -d ' ' -f 4
}
function size() {
    local F S T X

    for F do
	echo $F | tr '.-' '  ' | while read X T S X ; do
	    case $T in
		fill)	T=1	;;
		line)	T=2	;;
		*)	T=0	;;
	    esac
	    echo $T `echo $S | tr 'x' ' '` $F
	done
    done
}
cd include
if [ -L world.xbm ]; then
    DEFAULT=`ls -l world.xbm | rev | cut -d ' ' -f 1 | rev`
else
    DEFAULT=`ls -1 world-line-*x*.xbm | head -1`
fi
DEFTYPE=`echo $DEFAULT | cut -d - -f 2`
DEFSIZE=`echo $DEFAULT | tr . - | cut -d - -f 3`
echo
echo "Maps of type 'fill' have all land areas filled in solid, whereas maps"
echo "of type 'line' just have the land outlined to indicate its location."
echo
echo 'Which map do you want?'
MAPLIST="`order \`ls -1r world-*-*x*.xbm\` | tr '\n' ' '`"
declare -i N=0
DETAILS='x-x '
VALID=''
for MAP in $MAPLIST ; do
    echo $MAP | grep "^world-`echo ${DETAILS} | cut -d ' ' -f 1`-" > /dev/null || echo
    DETAILS="`echo $MAP | tr -- '-.x' '   ' | cut -d ' ' -f 2-4 | commas`"
    N=$N+1
    ME=`echo 123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ | cut -b $N`
    if [ "$MAP" = "$DEFAULT" ]; then
	DEFMAP='(Default)'
    else
	DEFMAP=''
    fi
    printf '    %s  %-5s  %7s x %7s  %s\n' $ME $DETAILS "$DEFMAP"
    VALID=$VALID$ME
    if [ "$ME" = Z ]; then
	echo
	echo '(Too many maps, others are not selectable)'
	break
    fi
done
echo
echo "or  0  Default."
echo
echo -n "Your choice: "
ME=' '
while ! echo 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ | grep "$ME" > /dev/null ; do
    read ME
    if [ `echo -n $ME | wc -c` -ne 1 ]; then
	ME=' '
    fi
done
echo
if [ $ME != 0 ]; then
    POS=`echo 123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ | sed 's/\(.\)/\1#/g'	\
		| tr '#' '\n' | grep "$ME" | cut -d : -f 1`
    if [ -f world.xbm ]; then
	rm -f world.xbm || exit 1
    fi
    ln -s `echo $MAPLIST | cut -d ' ' -f $POS` world.xbm || exit 1
    touch updated.map
else
    if [ ! -f updated.map ]; then
	touch -r world.xbm updated.map
    fi
fi
echo
exit 0
