#!/bin/sh

# Move over the GNU makefile to the file 'Makefile'.
# If SAGE64 is set to yes, add an '-m64' using 'sed'

if [ "$SAGE64" != "no" ] ; then
  echo "Creating a 64-bit version of PALP"
  CC="$CC -m64"
fi
mv -f src/GNUmakefile src/Makefile

cd src
mv Global.h Global.h-template

CFLAGS="-O3 -W -Wall $CFLAGS -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE"
# On Cygwin the stack size is ridiculously low by default, so that the nef
# executable which allocates everything on the stack for speed reason blows it
if [ "$UNAME" = "CYGWIN" ] ; then
  CFLAGS="$CFLAGS -Wl,--stack,8000000"
fi

for dim in 4 5 6 11; do
    echo Building PALP optimized for $dim dimensions

    sed "s/^#define[^a-zA-Z]*POLY_Dmax.*/#define POLY_Dmax $dim/" Global.h-template > Global.h

    $MAKE CC="$CC" CFLAGS="$CFLAGS"
    if [ $? -ne 0 ]; then
	echo "Error building PALP."
	exit 1
    fi

    for file in poly class cws nef mori; do
	cp -p ${file}.x "$SAGE_LOCAL"/bin/${file}-${dim}d.x
	if [ $? -ne 0 ]; then
	    echo "Error installing PALP."
	    exit 1
	fi
    done

    # the next step is important to avert races on older file systems
    # for example, ext3 has 1-second timestamp granularity!
    $MAKE cleanall
    if [ $? -ne 0 ]; then
	echo "Error building PALP."
	exit 1
    fi
done

# symlinks for the default dimension
cd "$SAGE_LOCAL"/bin
for file in poly class cws nef mori; do
    ln -sf ${file}-6d.x ${file}.x
done

