#!/usr/bin/ksh
# arrows - example how to use cursor keys in ksh scripts
# Heiner Steven (heiner.steven@odn.de)

# Reset terminal mode at exit
trap "stty echo -cbreak" 0
trap "exit 2" 1 2 3 15

GetKey () {
    readchar=`dd bs=1 count=1 2>/dev/null`
    case "$readchar" in
	'')			# Escape sequence? Read second char.
	    second=`dd bs=1 count=1 2>/dev/null`
	    case "$second" in
		'[')		# ESC '[' - seems to be escape sequence
		    third=`dd bs=1 count=1 2>/dev/null`
		    case "$third" in
			'A')	readchar=CURS_UP;;
			'B')	readchar=CURS_DOWN;;
			'C')	readchar=CURS_RIGHT;;
			'D')	readchar=CURS_LEFT;;
			*)	readchar="$readchar$second$third";;
		    esac;;
		*)		# No escape sequence
		    readchar="$readchar$second";;
	    esac ;;
    esac
    echo "$readchar"
}

stty -echo cbreak		# Will be restored at exit
echo 'Type any key (^d to end)' >&2
while :
do
    Key=`GetKey`
    case "$Key" in
	CURS_UP)	echo "up";;
	CURS_DOWN)	echo "down";;
	CURS_RIGHT)	echo "right";;
	CURS_LEFT)	echo "left";;
	)		exit 0;;
	*)	 echo "Key=$Key, `echo \"$Key\" | hd `";;
    esac
done
