root_dir=$(pwd)

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

    cd $(dirname $f)

    jfile="$(basename ${f%.re}.java)"
    jtest="example.java"

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

    # 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" "$jtest") -gt 1 ]; then
        # Get the line of the second message occurrence.
        l=$(grep -n "$msg" "$jtest" | tail -n +2 | cut -d : -f 1)
        # Cut off everything past that line.
        head -n $l "$jtest" > "$jtest".mod && mv "$jtest".mod "$jtest"
    fi

    echo "$f"
    # header test requires special handling to satisfy Java class hierarchy
    if $(grep -q -- '--header' "$jtest"); then
        ln -s "$jtest" Header.java \
            && ln -s state.java lexer/State.java \
            && javac lexer/State.java \
            && java -cp .. -ea Header.java \
            || { echo "*** error ***"; exit 1; }
        rm Header.java lexer/State.java lexer/State.class
    else
        java -ea "$jtest" || { echo "*** error ***"; exit 1; }
    fi

    rm -f "$jtest"
    cd $root_dir
done

echo "All good."
