#!/bin/bash

function usage() {
cat >&2 <<EOF

	Usage: 
		$0 src.enc result.enc [ src.kmap [ result.kmap ] ]
	or
		$0 --help
	
This cool script converts keysyms in a console keymap 
from one encoding into another :-).

Cyril Slobin's <slobin@iname.com> encoding tables from
console-tools-cyrillic-0.8 package can be used.
	
If source or result keymap file is not given, the keymaps are 
read/written to std{in,out}.

Warning: it won't work fine of the source encoding contains some 
keysyms that are not defined in the resulting one and if the source 
keymap contains those keysyms.
It won't work well if the source file contains keysyms represented in a 
format other than 0xNN or 0x00NN -- they won't be converted.

To sum up, this script isn't intended for being used regularly 
-- just a temporary substitute before a better solution is found.
Don't use this script!

Dec 2000 Ivan Zakharyaschev <vanyaz@mccme.ru>

EOF
}

if [[ "$1" == '--help' ]]; then
	usage
	exit 0
fi

if ! [ -r "$1" ]; then
	echo "Can't read source encoding file $1!" >&2
	usage
	exit 1
fi

if ! [ -r "$2" ]; then
	echo "Can't read result encoding file $2!" >&2
	usage
	exit 1
fi

CPP=/usr/bin/cpp
if [ ! -x "$CPP" ]; then
	echo "${0##*/}: $CPP not found"
	exit 1
fi

{
	echo "# This keymap is a result of a convertion done by a script."
	echo "# Cyril Slobin's <slobin@iname.com> encoding tables from "
	echo "# console-tools-cyrillic-0.8 package were used."
#	echo "# "
#	echo "# Script by"
#	echo "# 	Ivan Zakharyaschev <vanyaz@mccme.ru>"
#	echo "# 	IPLabs Linux Team <http://linux.iplabs.ru/>"
	echo
	{
		{
			cat "$1"
			cat <<-EOF
				COMM The keysyms in the source keymap read from ${3:-<stdin>}
				COMM were written to ${4:-<stdout>}
				COMM being converted from/to encoding:
			EOF
			echo -n "COMM "
			cat "$2" | sed -e 's/^#define //'
		} | "$CPP" -P | sed -e '1,2d' \
		| sed -e '/^COMM /!s/^/#define /' | sed -e 's/0x/ox/;t p;b;: p p;s/ox/ox00/'
		cat "${3:--}" | sed -e 's/^#/COMM /' | sed -e ': b s/0x/ox/;t b'
	} | "$CPP" -traditional -P | sed -e ': b s/ox/0x/;t b' | sed -e 's/^#.*$//;s/^COMM /# /'| sed 's,+U+0,U+0,g'
} | cat --squeeze-blank \
| if [[ -z "$4" ]]; then
	cat
else
	cat > "$4"
fi
