#!/bin/ksh

USAGE="$0 mapname width height [style]"

GATEHEIGHT=128

if (( $# != 3 )) && (( $# != 4 ))
then
	print -u2 "Usage: $USAGE"
	print -u2 "style is for example 'metal' (this is the default)"
	exit 2
fi

if [[ ! -d data ]]
then
	print -u2 "Run from top level directory."
	#exit 1
fi

mapname=$1
integer width=$2
integer height=$3
style=${4:-metal}

if [[ "$mapname" = @(*).map ]]
then
	print -u2 "Please leave off .map extension."
	exit
fi

mapfile=data/maps/${mapname}.map

if [[ -f $mapfile ]]
then
	print -u2 "$mapname: map already exists"
	exit 1
fi

exec >$mapfile || exit $?

# The Y coordinate of the top of the gate (center it along the vertical extent of the map)
(( gate_start_y = height / 2 - GATEHEIGHT / 2 ))
# The Y coordinate of the bottom of the gate
(( gate_end_y = gate_start_y + GATEHEIGHT ))

# Map header
print "$mapname"
print "$width $height"

# Background
cat <<-EOF
# Background
SPRITE	0,0	TB	${style}_bgtile	${width}	${height}
SPRITE	-64,${gate_start_y}	TB	${style}_bgtile	64	${GATEHEIGHT}
SPRITE	${width},${gate_start_y}	TB	${style}_bgtile	64	${GATEHEIGHT}

EOF

# Walls
cat <<-EOF
# Walls
SPRITE	0,${height}	TB	${style}_wall_s32	${width}	32
SPRITE	0,-32	TB	${style}_wall_n32	${width}	32
SPRITE	${width},0	TB	${style}_wall_e32	32	${gate_start_y}
SPRITE	${width},${gate_start_y}	B	${style}_gate_e
SPRITE	${width},${gate_end_y}	TB	${style}_wall_e32	32	${gate_start_y}
SPRITE	-32,0	TB	${style}_wall_w32	32	${gate_start_y}
SPRITE	-64,${gate_start_y}	B	${style}_gate_w
SPRITE	-32,${gate_end_y}	TB	${style}_wall_w32	32	${gate_start_y}

# Wall Corners
SPRITE	${width},-32	B	${style}_wall_ne32
SPRITE	-32,-32	B	${style}_wall_nw32
SPRITE	-32,${height}	B	${style}_wall_sw32
SPRITE	${width},${height}	B	${style}_wall_se32
EOF

# Gates
cat <<-EOF
# Gates
GATE	-15,$((gate_start_y + 8))	A
GATE	$((width + 7)),$((gate_start_y + 8))	B

EOF

# Sample Objects
cat <<-EOF
# SAMPLE Spawnpoints (make your own, each team should have 8)
#SPAWN	0,50	A
#SPAWN	${width},50	B

# SAMPLE obstacles (make your own)
# Look in data/sprites to see what sprites are available
# This is a 64x64 obstacle:
#SPRITE	64,256	O	${style}_obstacle64
# This is a 128x128 obstacle:
#SPRITE	128,256	O	${style}_obstacle128
EOF

exec >&-

#svn add $mapfile >/dev/null

print -u2 "Done writing map file to ${mapfile}"
print -u2 "The background, wall, and gate sprites have been laid out."
print -u2 "You need to add spawnpoints and obstacles where appropriate."
