root_dir=$(pwd)

for f in $(find -name '*.re'); do
    grep -q -E 'main|assert|throw' $f || continue # skip incomplete tests

    cd $(dirname $f)

    jsfile="$(basename ${f%.re}.js)"
    jstest="example.js"

    cat "$jsfile" \
        | egrep -v 'warning: rule .*matches empty string \[-Wmatch-empty-string\]' \
        | egrep -v 'warning: tag .* degree of nondeterminism \[-Wnondeterministic-tags\]' \
        > "$jstest"

    # If the autogenerated message appears more than once in the file, then
    # it must have autogenerated header appended at the end. Cut it off.
    msg='Generated by re2c'
    if [ $(grep -c "$msg" "$jstest") -gt 1 ]; then
        # Get the line of the second message occurrence.
        l=$(grep -n "$msg" "$jstest" | tail -n +2 | cut -d : -f 1)
        # Cut off everything past that line.
        head -n $l "$jstest" > "$jstest".mod && mv "$jstest".mod "$jstest"
    fi

    echo "$f"
    node --trace-uncaught "$jstest" || { echo "*** error ***"; exit 1; }

    rm -f "$jstest"
    cd $root_dir
done

echo "All good."
