# Calls to 'firstword' are used to strip out
# a possible '-m64' attached to the CC variable
# (or other compiler arguments)
PKG_CPPFLAGS += $(CXX1XSTD) -I../inst/include/

ifeq ($(OS), Windows_NT)

  USE_TBB=Windows
  TBB_COPY_PATTERN=tbb*.dll
  
  MAKEFLAGS = -j1
  MAKE_CMD = CONLY="$(CC)" CPLUS="$(CXX1X)" make

else
  
  UNAME := $(shell uname)
  TBB_COPY_PATTERN=libtbb*.*
  ifeq ($(UNAME), Darwin)
    USE_TBB=Mac
  endif
  ifeq ($(UNAME), Linux)
    USE_TBB=Linux
  endif
  ifeq ($(UNAME), SunOS)
    SUNOS_ARCH = $(shell uname -p)
    ifeq ($(SUNOS_ARCH), i386)
      USE_TBB=SunOS
    endif
  endif

  MAKE_CMD=$(MAKE)
  
endif

ifdef USE_TBB

PKG_CPPFLAGS += -DRCPP_PARALLEL_USE_TBB=1

MAKE_ARGS := CXXFLAGS=-DTBB_NO_LEGACY=1 PIC_KEY=$(CXXPICFLAGS) tbb_release tbbmalloc_release tbb_build_prefix=lib

ifeq ($(USE_TBB),  Windows)

  # rtools: turn on hacks to compensate for make and shell differences rtools<=>MinGW
  # compiler: overwrite default (which is cl = MS compiler)
  MAKE_ARGS += rtools=true compiler=gcc
  ifeq ("$(WIN)", "64")
    MAKE_ARGS += arch=intel64
    ARCH_DIR=x64/
  else
    MAKE_ARGS += arch=ia32
    ARCH_DIR=i386/
  endif

  # Linker needs access to the tbb dll; otherwise you get errors such as:
  # "undefined reference to `tbb::task_scheduler_init::terminate()'"
  PKG_LIBS += -L../inst/lib/$(ARCH_DIR) -ltbb -ltbbmalloc

endif

# For Solaris detect if this is 32-bit R on x86 and if so forward that to TBB
ifeq ($(USE_TBB),  SunOS)
   R_32BIT = $(shell ${R_HOME}/bin/Rscript -e 'cat(.Machine$$sizeof.pointer == 4)')
   ifeq ($(R_32BIT), TRUE)
      MAKE_ARGS += arch=ia32
   endif
endif

.PHONY: all tbb

# Order is important in Windows' case. See PKG_LIBS above
all: tbb $(SHLIB)

tbb:
	mkdir -p ../inst/lib/$(ARCH_DIR); \
	cd tbb/src; \
	if [ -n "$(shell echo $(CC) | grep clang)" ]; then \
	   $(MAKE_CMD) cpp0x=1 compiler=clang $(MAKE_ARGS); \
	elif [ -n "$(shell echo $(CC) | grep gcc)" ]; then \
	   $(MAKE_CMD) cpp0x=1 compiler=gcc $(MAKE_ARGS); \
	else \
	   $(MAKE_CMD) cpp0x=1 $(MAKE_ARGS); \
	fi; \
	cd ../..; \
	cp tbb/build/lib_release/$(TBB_COPY_PATTERN) ../inst/lib/$(ARCH_DIR)

clean:
	(cd tbb/src; make clean)

endif

