#! /usr/local/bin/bash

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

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

atom_id=0

function 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=$[ atom_id + 1 ]
}

function atom2define () {
    echo -n `echo ATOM_$1 | tr -- -a-z _A-Z | sed 's/*/STAR/'`
}

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
	    echo -n '#define '
	    atom2define "$atom"
	    echo ' ' $atom_id
	done
	echo '#define NUMBER_OF_ATOMS' $[ atom_id + 1 ]
	;;
    gperf)
	echo '%{'
	header
	echo '%}'

	echo 'struct atom_assoc { const char *name; int id; };'
	echo '%%'
	    
	while getatom; do
	    echo -n "$atom, "
	    atom2define "$atom"
	    echo
	done
	;;
    table)
	header
	echo -n '{ { "UNKNOWN", 0 }'
	while getatom; do
	    echo ','
	    # FIXME: We could replace ${#atom} with `expr $atom :'.*'`
	    echo -n '  {' \""$atom"\", ${#atom} '}'
	done
	echo ' }'
	;;
    help)
	help
	exit 0
	;;
    *)
	help
	exit 1
	;;
esac
