root_dir=$(pwd)

for f in $(find -name '*.re'); do
    cd $(dirname $f)

    mlfile="$(basename ${f%.re}.ml)"
    mltest="example.ml"

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

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

    # for header test ocamlopt needs include path and topologically sorted module paths
    extra_args=`egrep -o -- '--header [^ ]+' "$mltest" | sed -E 's/--header ([^\/]*)(.*)/-I \1 \1\2/'`

    echo "$f"
    ocamlopt $extra_args "$mltest" -o example && ./example || { echo "*** error ***"; exit 1; }

    rm -f "$mltest" example $(find -name '*.o' -o -name '*.cmx' -o -name '*.cmi')
    cd $root_dir
done

echo "All good."
