echo "Deleting old gf2x files."
rm -f "$SAGE_LOCAL"/lib/libgf2x*
rm -rf "$SAGE_LOCAL"/include/gf2x*

cd src

# Use newer version of config.guess and config.sub (see Trac #19727)
cp "$SAGE_ROOT"/config/config.* config

# As config/acinclude.m4 is patched, we need to touch some files to prevent
# autotools to invoke black magic.
touch aclocal.m4 configure Makefile.in gf2x/gf2x-config.h.in

if [ "$SAGE_DEBUG" = "yes" ]; then
    echo "Building a debug version of gf2x."
    export CFLAGS="-O0 -g $CFLAGS"
elif $CC --version 2>/dev/null |grep 'gcc.* 5[.][12]' >/dev/null; then
    echo "Using compiler flags to work around problems with GCC 5.1/5.2 (Trac #18580,#18978)"
    export CFLAGS="-O2 -fno-forward-propagate -g $CFLAGS"
else
    export CFLAGS="-O2 -g $CFLAGS"
fi

if [ "$SAGE64" = "yes" ]; then
    echo "Building a 64-bit version of gf2x."
    export ABI=64
    CFLAGS="-m64 $CFLAGS"
fi

if [ "$SAGE_FAT_BINARY" = "yes" ]; then
    echo "Building a generic gf2x library."
    GF2X_CONFIGURE="--disable-hardware-specific-code $GF2X_CONFIGURE"
    SAGE_TUNE_GF2X="no"
fi

sdh_configure $GF2X_CONFIGURE
sdh_make

case "$SAGE_TUNE_GF2X" in
    "full")
        echo "Complete tuning of gf2x."
        $MAKE tune-lowlevel && $MAKE tune-toom && $MAKE tune-fft
        if [ $? -ne 0 ]; then
            echo >&2 "Error: Failed to tune gf2x."
            exit 1
        fi
        ;;
    "no")
        echo "Skipping tuning of gf2x."
        echo "You can set SAGE_TUNE_GF2X to yes or full to turn it on."
        ;;
    *)
        echo "Fast tuning of gf2x."
        echo "You can set SAGE_TUNE_GF2X to full to run a complete tuning."
        $MAKE tune-lowlevel && $MAKE tune-toom
        if [ $? -ne 0 ]; then
            echo >&2 "Error: Failed to tune gf2x."
            exit 1
        fi
        ;;
esac

sdh_make_install
