#!/bin/sh
set -e
LC_ALL=C
export LC_ALL
echo
echo Generating code page translation tables.
codepages=`cat index.txt|sed 's/
//g'`
if [ -n "$codepages" ]; then
(
n=0
echo '/* Automatically generated by gen-cp */'
for i in $codepages; do
	printf $i' ' 1>&2
	echo
	echo 'static_const struct table_entry table_'$i' [] = {'
	tail -n +3 $i.cp | sed 's/#.*$//' | grep '^0x[89a-fA-F]' | sed 's/[ 	][ 	]*/ /g' | sed 's/[ 	]*$/ },/' | sed 's/ /, /' | sed 's/^[ 	]*/	{ /' | grep '.*, .*,' | grep -v ', 0x0*[89][0-9a-fA-F] ' || true
	echo '	{ 0, 0 }'
	echo '};'
	echo
	echo 'static_const const_char_ptr aliases_'$i' [] = {'`head -2 $i.cp | tail -n +2`', NULL };'
	n=`expr $n + 1`
done
echo
echo 'static_const struct codepage_desc codepages [] = {'
for i in $codepages; do
	echo '	{ "'`head -1 $i.cp`'", aliases_'$i', table_'$i' },'
done
echo '	{ NULL, NULL, NULL }'
echo '};'
echo '#define N_CODEPAGES '$n | sed 's/
//g' > codepage.h
if cmp -s ../codepage.h codepage.h; then
	rm -f codepage.h
else
	mv codepage.h ../codepage.h
fi
) | sed 's/
//g' > ../codepage.inc
echo
echo Done.
fi
echo