#!/bin/bash
# This file is processes input files to generate lookup tables for strings
# -> ID mappings. All lines beginning with '#' or white space are ignored.
# The first word contains a string, it will be used to generate a C
# identifier which can then be used in the C code to easily identify a given
# string.
#
# The identifier will be named as <prefix>_<translated id>
# The id is translated in the following way:
#   - characters are forced to upper case
#   - anything that cannot be present in a C identifier will be rewritten to '_'
#

usage()
{
	echo "Syntax: $0 <output type> <prefix> <file to process>"
	echo "Options:"
	echo "Output type is: header|revtable|gperf"
	echo "Prefix is: the prefix to be used on C identifiers"
}


getline()
{
	last_id=$[last_id + 1]
	read word dummy
}

gen_header()
{
	echo -e "/* automatically generated by genlutable.sh, do not edit directly */"
	echo -e "#ifndef ${prefix}_NAMES_DEFINED\n#define ${prefix}_NAMES_DEFINED\n\n"
	echo -e "enum\n{\n"
	while getline; do 
		cword=`echo $word | tr [a-z] [A-Z] | sed -r -e 's/"//g' -e 's/([]\.,[]|-)/_/g' -e 's/@/_AT_/' -e 's/_$//'`
		echo "  ${prefix}_${cword}=$last_id,"
	done
	echo -e "  ${prefix}_MAX=$last_id\n"
	echo -e "};\n";

	echo -e "#endif\n\n"
}

gen_revtable()
{
	echo -e "/* automatically generated by genlutable.sh, do not edit directly */"

	array_name="`echo ${prefix} | tr [A-Z] [a-z]`_reverse_map "
	echo -e "const char *${array_name}[] = \n{\n"

	while getline; do 
        cstr=$(echo "$word" | sed -r -e 's/"//g')
		echo -e "  [${last_id}] = \"${cstr}\","
	done
	echo -e "};\n";

}

gen_gperf()
{
	echo -e "/* automatically generated by genlutable.sh, do not edit directly */"
	echo -e "%readonly-tables\n%define initializer-suffix ,0"
	echo -e "struct tagid { char *name; int id; };\n\n%%"
	while getline; do 
		echo "$word, $last_id"
	done
}

if [ $# -lt 3 ]; then
	usage
	exit 1
fi

prefix=$2
last_id=0
word=""

pattern='^["a-zA-Z0-9\-]'

case "$1" in
	header)
		grep "$pattern" $3  | gen_header $prefix
		;;
	revtable)
		grep "$pattern" $3  | gen_revtable $prefix
		;;
	gperf)
		grep "$pattern" $3  | gen_gperf $prefix
		;;
	
esac
