#! /bin/sh

help() {
  echo commands: help header gperf filter table
}

header() {
    echo '/* Automatically generated by process_atoms,' 
    echo ' * ' `date`
    echo ' * Do not edit! */'
    echo
}

atom_id=0

getatom() {
    atom=''
    while [ "x$atom" = x ]; do
	read atom ignored
	if [ x$? != x0 ] ; then
	    return 1
	fi
	case "$atom" in
	    \#*)
		atom=''
		;;
	esac ;
    done
    atom_id=`expr $atom_id + 1`
}

atom2define () {
    printf "%s" "`echo ATOM_$1 | tr [a-z]- [A-Z]_ \
       | sed -e 's/\*/STAR/' -e 's/@.*$/_LOCAL/'`"
}

if [ x$# != x1 ]; then
    help
    exit 1
fi

case $1 in
    filter)
	while getatom; do
	    echo "$atom" $atom_id
	done
	;;
    header)
	header
	while getatom; do
	    printf "%s" '#define '
	    atom2define "$atom"
	    echo ' ' $atom_id
	done
	echo '#define NUMBER_OF_ATOMS' `expr $atom_id + 1`
	;;
    gperf)
	echo '%{'
	header
	echo '%}'

	echo 'struct atom_assoc { const char *name; int id; };'
	echo '%%'
	    
	while getatom; do
	    printf "%s" "$atom, "
	    atom2define "$atom"
	    echo
	done
	;;
    table)
	header
	printf "%s" '{ { "UNKNOWN", 7 },'
	while getatom; do
	    printf '  {"%s", %s},\n' "$atom" "`expr "$atom" : '.*'`"
	done
	echo ' }'
	;;
    help)
	help
	exit 0
	;;
    *)
	help
	exit 1
	;;
esac
