################################################################################
# initialization
################################################################################

# detect os
OS := $(shell uname -s | tr [:upper:] [:lower:])

# detect bit size
UNAME_M := $(shell uname -m)
ifeq ($(UNAME_M),x86_64)
	ARCH := 64
else
	ARCH := 32
endif

# aliases
FC := gfortran
MV := mv
RM := rm -rf
ifeq ($(OS),darwin)
	# MacOS
	LIBEXT := dylib
else
	# linux
	LIBEXT := so
endif

# color definitions
blue := $(shell tput setaf 6)
sgr0 := $(shell tput sgr0)


################################################################################
# compilation parameters
################################################################################

# define output file
OUT := slbmtestfort
OUTDIR := ../bin

# includes
INC := -I../GeoTessCPP/include -I../SLBM/include -I../SLBM_Fort_shell/include

# libraries
LIBDIR := ../lib
LIBS := -lm -lstdc++ -L$(LIBDIR) -lgeotesscpp -lslbm -lslbmFshell

# compiling parameters
FFLAGS = -march=native -D$(OS) -m$(ARCH) -O1 -fno-underscoring -cpp -ffree-line-length-none

# list of objects to compile
OBJS = src/slbmtestfort.o


################################################################################
# recipes
################################################################################

# recipe to make everything
all: initialize slbmtest finalize

# command that tells us which recipes don't build source files
.PHONY: all initialize msg_intro slbmtest finalize clean cleanall


# initialize compilation script
initialize: msg_intro

# print intro message
msg_intro:
	@echo "$(blue)------------------------------------------------------------$(sgr0)"
	@echo "$(blue)Making RSTT Fortran test...$(sgr0)"
	@echo "$(blue)------------------------------------------------------------$(sgr0)"


# to build any *.o file, compile its corresponding *.cc file
%.o: %.f90
	@printf "$(blue)(Building obj) $(sgr0)"
	$(FC) $(FFLAGS) $(INC) -o $@ -c $<


# build library after building each prerequisite in $(OBJS)
slbmtest: initialize $(OUT)

# MacOS
ifeq ($(OS),darwin)
$(OUT): $(OBJS)
	@printf "$(blue)(Building lib) $(sgr0)"
	$(FC) $(FFLAGS) -Wl,-rpath,"@executable_path/$(LIBDIR)" -o $(OUT) $^ $(LIBS)

# linux
else
$(OUT): $(OBJS)
	@printf "$(blue)(Building lib) $(sgr0)"
	$(FC) $(FFLAGS) -Wl,-rpath,'$$ORIGIN/$(LIBDIR)' -o $(OUT) $^ $(LIBS)

endif


# move files and clean up
finalize:
	@printf "$(blue)(Moving files) $(sgr0)"
	$(MV) $(OUT) $(OUTDIR)

clean:
	@printf "$(blue)(Clean *.o) $(sgr0)"
	$(RM) src/*.o *.mod

cleanall: clean
	@printf "$(blue)(Clean bin) $(sgr0)"
	$(RM) $(OUTDIR)/$(OUT)
