if [[ -z $SAGE_LOCAL ]]; then
    echo >&2 "Error: SAGE_LOCAL undefined - exiting..."
    echo >&2 "Maybe run 'sage -sh'?"
    exit 1
fi


PRIME_SIZE=7

CCFLAGS_NO_SSE="-I$SAGE_LOCAL/include -Wall -O2 -fPIC -DRATPOINTS_MAX_BITS_IN_PRIME=$PRIME_SIZE"
CCFLAGS2="-L$SAGE_LOCAL/lib -lgmp -lm $LDFLAGS"
CCFLAGS3="-L. -lratpoints"

if [[ "$UNAME" = "Darwin" ]]; then
    CCFLAGS1="$CCFLAGS_NO_SSE"
    echo "Building without SSE2 instructions (MacOS X)."
else
    CCFLAGS1="$CCFLAGS_NO_SSE -DUSE_SSE"
    echo "Attempting to build ratpoints making use of SSE2 instructions."
fi

# Copy CFLAGS set externally to CCFLAGS.
CCFLAGS="$CFLAGS"

export CCFLAGS1
export CCFLAGS2
export CCFLAGS3
export CCFLAGS

cd src/

#############################
# Build (just) the library: #
#############################

# PLEASE, don't break this again by deleting "libratpoints.a".  See trac 8267.
$MAKE libratpoints.a

if [[ $? -ne 0 ]]; then
    if [[ "$UNAME" = "Darwin" ]]; then
        echo >&2 "Error building ratpoints."
        exit 1
    fi
    echo "Build failed. Trying without SSE2 instructions."
    CCFLAGS1="$CCFLAGS_NO_SSE"
    $MAKE libratpoints.a
    if [[ $? -ne 0 ]]; then
        echo >&2 "Error building ratpoints."
        exit 1
    fi
fi

##############################################
# Install (just) the library and its header: #
##############################################

# cp libratpoints.a "$SAGE_LOCAL"/lib/
# cp ratpoints.h "$SAGE_LOCAL"/include/

# The following requires that the Makefile got patched;
# otherwise one could pass 'INSTALL_DIR=...' on the 'make'
# command line:
export INSTALL_DIR="$SAGE_LOCAL"
$MAKE install-lib
if [[ $? -ne 0 ]]; then
    echo >&2 "Error installing ratpoints library."
    exit 1
fi

# TODO: How about 'make test'? Do we need an spkg-check script?

