#! /bin/sh

# convert keyboard mapping tables

# from structured format (array of string pairs)
#	struct keymap keymap_ArabicKeyboard [] = {
#		{"q", "ض"},	/* dad (ض) */

# to one of two optimised formats (single string with NUL byte separators),
# either noted in concatenated pairs of strings with explicit NUL separators,
# or as a sequence of bytes with separating NUL bytes.

tostrings () {
	# convert to string format
	#	char * keymap_ArabicKeyboard = 
	#		"q\0ض\0"	/* dad (ض) */
	LC_ALL=C
	export LC_ALL
	sed	-e 's/struct *keymap *\([^ ]*\) .*/char \1 [] =/' \
		-e 's/^	{"\(.*\)", "\(.*\)"},/	"\1\\000\2\\000"/' \
		-e t -e d $1
	echo "	;"
}

tochararr () {
	# convert to char array format
	#	char * keymap_ArabicKeyboard = {
	#		'q', 0, '', '', 0, 
	#		0};
	LC_ALL=C
	export LC_ALL
	sed	-e 's/struct *keymap *\([^ ]*\) .*/char \1 [] = {/' \
		-e t \
		-e '/^	{"/ b entry' -e d \
		-e ': entry' \
		-e 's/^	{"\(.*\)", "\(.*\)"},/\1\2/' \
		-e 's,\\\(.\),\1,g' \
		-e "s/./'&', /g" -e "s,'\\\\','\\\\\\\\',g" -e "s,''','\\\\'',g" \
		-e "s/'',/0,/g" -e "s/^/	/" \
		$1
	echo "	0};"
}

for file in $*
do	case `sed -e "/keymap_.*=/ q" -e d "$file"` in
	char*)	echo copying pre-transformed "$file" >&2
		cat "$file";;
	struct*)
		case "`basename $file`" in
		Radical*)	echo converting "$file" to char array format >&2
				tochararr "$file";;
		*)		echo converting "$file" to string format >&2
				tostrings "$file";;
		esac;;
	*)	echo error unknown format to convert in "$file" >&2;;
	esac
done
