#!/bin/sh

(
cat <<EOF
/* Autogenerated from kw.def, don't edit. */
typedef enum {
	kw__error,
EOF
grep -v '^#' $1/keyword.def | sed 's/.*/	kw_&,/'
cat <<EOF
	kw__LAST
} keyword_t;
EOF
) > $2/keyword.h

(
cat <<EOF
%{
/* Autogenrated. */
#include "ksi.h"
%}
struct ksi_keyword { const char *name; keyword_t id; };
#ifdef __GNUC__
__inline
#endif
static unsigned int hash(register const char *, 
			 register unsigned int);
#ifdef __GNUC__
__inline
#endif
static const struct ksi_keyword *in_word_set(register const char *, 
					     register unsigned int);
%%
EOF
grep -v '^#' $1/keyword.def | sed 's/.*/&, kw_&/'
cat <<EOF
%%

static const char *keyword_names[] = {
	"ERROR",
EOF

grep -v '^#' $1/keyword.def | sed 's/.*/	"&",/'

cat <<EOF
	0
};

const char *keyword_name(keyword_t kw)
{
	int k = (int)kw;

	if (k <= kw__error || k >= kw__LAST)
		return keyword_names[0];
	else
		return keyword_names[kw];
}

keyword_t lookup_keyword(const char *ptr, int len)
{
	const struct ksi_keyword *w;

	w = in_word_set(ptr, len);

	if (w)
		return w->id;
	else
		return kw__error;
}
EOF
) > $2/keyword.gperf
gperf -C -c -S 1 -D -k 1,3,5,$ -t $2/keyword.gperf > $2/keyword.c || exit 1
rm $2/keyword.gperf
