#!/bin/sh

# this is wrapper script to run convgen.awk

    file=find_handlers.c
    list=handlers_list
    conv="../tools/convgen.awk"


#> $file
cat $list | grep -v '^default ' | awk '{print $1"@@"$0}' >$file
echo "  " >>$file

space=""

while $conv -v SPACE="$space" $file >$file.tmp && mv -f $file.tmp $file ; do 
echo "Working" >&2 ; 
space="$space  ";
done


# add 'header' and 'footer'
>$file
echo "/* File generated by ./convgen script - DO NOT EDIT! */" >>$file
echo "" >>$file
echo "" >>$file
echo "#include <stdio.h>" >>$file
echo "#include \"handlers.h\"" >>$file
echo "void find_handlers(const char *name, Handlers *handlers)" >>$file
echo "{" >>$file
echo "  int use_default_handler;" >>$file
echo "  use_default_handler = 1;" >>$file

cat $file.tmp >>$file

# add default clause
cat $list | awk '/^default / \
{ \
    start = $2; \
    end = $3; \
    data = $4; \
    print  "  if (use_default_handler) {"; \
    printf "    handlers->starthandler = "; \
    if (!start) print "NULL;"; else print "default_start_handler;"; \
    printf "    handlers->endhandler = "; \
    if (!end) print "NULL;"; else print "default_end_handler;"; \
    printf "    handlers->datahandler = "; \
    if (!data) print "NULL;"; else print "default_data_handler;"; \
    print  "  }"; \
}' >>$file

echo "}" >>$file
