#!/bin/sh

echo
echo Generating code page translation tables.

codepages=`cat index.txt`

if [ -n "$codepages" ]; then

(

n=0

echo '/* Automatically generated by gen-cp */'
echo '/* DO NOT EDIT THIS FILE! EDIT Unicode/<whatever> INSTEAD! */'
echo

for i in $codepages; do
	echo -n $i' ' 1>&2
	echo

	echo
	echo "/*** $i ***/"
	echo

	echo 'struct table_entry table_'$i' [] = {'

	# TODO: Comments inside of the structure are ugliness in a pure clean
	# form, and my aesthetical feeling shivers upon glancing at it. However
	# we should handle commentless records. A loop with read inside would
	# be ideal, I suppose. --pasky
	tail -n +3 $i.cp | sed 's/# *\(.*\) *$/\/* \1 *\/ /' | grep '^0x[89a-zA-Z]' \
	| sed 's/[ 	][ 	]*/ /g' | sed 's/[ 	]*$/ },/' | sed 's/ /, /' \
	| sed 's/^[ 	]*/	{/' | grep '.*,.*,'

	echo '	{0, 0}'
	echo '};'
	echo

	echo 'unsigned char *aliases_'$i' [] = {'
	head -n 2 $i.cp | tail -n +2 | sed 's/ \+/ /g; s/ $//; s/\", /\",£/g; s/$/,/' | tr "£" "\n" \
	| sed 's/^/£/g' | tr "£" "\t" 
	echo '	NULL
};'
	n=`expr $n + 1`
done

echo
echo 'struct codepage_desc codepages [] = {'

for i in $codepages; do
	echo '	{"'`head -n 1 $i.cp`'", aliases_'$i', table_'$i'},'
done

echo '	{NULL, NULL, NULL}'
echo '};'

echo
echo '#define N_CODEPAGES '$n | sed 's/
//g'

) | sed 's/
//g' > ../src/intl/codepage.inc

echo
echo Done.

fi

echo