root_dir=$(pwd)

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

    dfile="$(basename ${f%.re}.d)"
    dtest="example.d"

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

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

    # add -debug to print debug logs
    dmd -g -wi -ofexample  "$dtest" \
        && ./example 2>/dev/null || { echo "*** error ***"; exit 1; }

    rm -f "$dtest" example example.o
    cd $root_dir
done

echo "All good."
