# Copyright (C) 2010 Jelmer Ypma. All Rights Reserved.
# This code is published under the L-GPL.
#
# File:   Makevars.in
# Author: Jelmer Ypma
# Date:   10 June 2010
#
# 16-01-2011: Changed --disable-shared to --enable-shared to compile with -fPIC
# 16-06-2011: Updated version number
# 09-07-2011: Download and untar NLopt code using Rscript
# 01-09-2011: Added check on empty SRCDIR
#             Added CC, CFLAGS, etc. to NLopt ./configure

# define NLopt version
NLOPT_VERSION = 2.2.4

# C Compiler options
NLOPT_CFLAGS = 

# additional C Compiler options for linking
NLOPT_CLINKFLAGS = 

# Libraries necessary to link with NLopt
NLOPT_LIBS = -lm nlopt-${NLOPT_VERSION}/lib/libnlopt.a

# Necessary Include dirs 
NLOPT_INCL = -I./nlopt-${NLOPT_VERSION}/include

# Get R compilers and flags
CC=`"${R_HOME}/bin/R" CMD config CC`
CFLAGS=`"${R_HOME}/bin/R" CMD config CFLAGS`

CPP=`"${R_HOME}/bin/R" CMD config CPP`
CPPFLAGS=`"${R_HOME}/bin/R" CMD config CPPFLAGS`

CXX=`"${R_HOME}/bin/R" CMD config CXX`
CXXFLAGS=`"${R_HOME}/bin/R" CMD config CXXFLAGS`

CXXCPP=`"${R_HOME}/bin/R" CMD config CXXCPP`


# Define objects for R to build
OBJECTS = nloptr.o

# Convert to R macros
PKG_LIBS=${NLOPT_CLINKFLAGS} ${NLOPT_LIBS}
PKG_CFLAGS=${NLOPT_CFLAGS} ${NLOPT_INCL}

# Define location of source code
SRCDIR = ${CURDIR}

# Check to see if SRCDIR is empty
# If SRCDIR is empty use current directory, i.e. use .
ifeq ("${SRCDIR}", "")
	SRCDIR = .
endif



.PHONY: all
     
all: $(SHLIB)

$(SHLIB): nlopt-${NLOPT_VERSION}/lib/libnlopt.a ${OBJECTS}

nloptr.o: nlopt-${NLOPT_VERSION}/include/nlopt.h
  
# Compile NLopt source code and clean up
nlopt-${NLOPT_VERSION}/include/nlopt.h nlopt-${NLOPT_VERSION}/lib/libnlopt.a: nlopt-${NLOPT_VERSION}/configure
	echo "Installing library to: ${SRCDIR}/nlopt-${NLOPT_VERSION}"
	cd nlopt-${NLOPT_VERSION}; \
	./configure --prefix=${SRCDIR}/nlopt-${NLOPT_VERSION} --enable-shared --enable-static --without-octave --without-matlab --without-guile --without-python CC="${CC}" CFLAGS="${CFLAGS}" CPP="${CPP}" CPPFLAGS="${CPPFLAGS}" CXX="${CXX}" CXXFLAGS="${CXXFLAGS}" CXXCPP="${CXXCPP}"; \
	make; \
	make install; \
	ls | grep -v ^include$$ | grep -v ^lib$$ | xargs rm -rf; \
    rm -rf .libs;

# Extract NLopt source code and remove .tar.gz
# tar -xzvf nlopt-${NLOPT_VERSION}.tar.gz
nlopt-${NLOPT_VERSION}/configure: nlopt-${NLOPT_VERSION}.tar.gz
	$(shell "${R_HOME}/bin/Rscript" -e "untar(tarfile='nlopt-${NLOPT_VERSION}.tar.gz')")
	rm -rf nlopt-${NLOPT_VERSION}.tar.gz


# Download NLopt source code
# curl -O http://ab-initio.mit.edu/nlopt/nlopt-${NLOPT_VERSION}.tar.gz
nlopt-${NLOPT_VERSION}.tar.gz:
	$(shell "${R_HOME}/bin/Rscript" -e "download.file(url='http://ab-initio.mit.edu/nlopt/nlopt-${NLOPT_VERSION}.tar.gz', destfile='nlopt-${NLOPT_VERSION}.tar.gz')")

clean:
	rm -rf *.so
	rm -rf *.o
	rm -rf nlopt-${NLOPT_VERSION}
	

