SRCMAKE=$(lastword $(MAKEFILE_LIST))
SRC=$(realpath $(dir $(SRCMAKE)))

# this creates a makefile including the source dir makefile in the current directory
makefile:
	@echo "include $(SRC)/Makefile" > makefile

BASE=/usr/local
FLAGS+=-I$(BASE)/include -L$(BASE)/lib -I$(SRC)/../CImg $(CPPFLAGS) $(CXXFLAGS) -Wno-deprecated-declarations

ifdef flags
	FLAGS+=$(flags)
endif

ifdef debug
	FLAGS+=-g -std=c++14
else

ifdef static
	FLAGS+=-g -std=c++14 -O3 -DNDEBUG=1 -mtune=generic -DDLIB_HAVE_SSE41
else
	FLAGS+=-g -std=c++14 -O3 -DNDEBUG=1 -mtune=native -DDLIB_HAVE_SSE41
endif

endif

ifdef static
	FLAGS+=-static -fPIC
endif

ifndef no_openmp
	FLAGS+=-fopenmp -lgomp -lpthread
endif

SUITESPARSEFLAGS=-lumfpack -lbtf -lccolamd -lcxsparse -lklu -lspqr -lamd -lcholmod -lamd -lcolamd -lcamd -lccolamd -lmetis -lsuitesparseconfig -lblas -llapack -lgfortran -lquadmath

CERESFLAGS+=-I/usr/include/eigen3 -I$(BASE)/include/ceres/internal/miniglog -lceres -DINCLUDE_CERES $(SUITESPARSEFLAGS)

GDALFLAGS+=-I/usr/include/gdal -lgdal

ifdef use_fluex
	FLUEXFLAGS+=-I$(SRC)/../fluex/ -lfftw3 
endif

LFLAGS+=-lboost_filesystem -lboost_system -lboost_regex -lboost_program_options -lboost_iostreams -lpthread -lz

pluriel_mca.o: $(SRC)/pluriel_mca.cpp
	$(CXX) $(FLAGS) -DHAVE_FFT -c $(SRC)/pluriel_mca.cpp -I$(SRC)/../fluex/ -o pluriel_mca.o

pluriel_gradient.o: $(SRC)/pluriel_gradient.cpp
	$(CXX) $(FLAGS) -c $(SRC)/pluriel_gradient.cpp -o pluriel_gradient.o

pluriel_stochadiff.o: $(SRC)/pluriel_stochadiff.cpp
	$(CXX) $(FLAGS) -c $(SRC)/pluriel_stochadiff.cpp -I/usr/include/eigen3 -DHAVE_FFT -I$(SRC)/../fluex/ -o pluriel_stochadiff.o

pluriel.o: $(SRC)/pluriel.cpp $(SRC)/pluriel.hpp
	$(CXX) $(FLAGS) -I$(SRC)/../fluex/ -c $(SRC)/pluriel.cpp -o pluriel.o

MODULES=pluriel_stochadiff.o pluriel_mca.o pluriel_gradient.o

pluriel: $(MODULES) pluriel.o
	$(CXX) $(FLAGS) -I$(SRC)/../fluex/ $(MODULES) pluriel.o -lgomp $(LFLAGS) -lpng -ljpeg -lfftw3 -o pluriel

field_maker: $(SRC)/field_maker.cpp
	$(CXX) $(FLAGS) $(SRC)/field_maker.cpp -I/usr/include/eigen3 $(LFLAGS) $(CERESFLAGS) -o field_maker

process_gradient: $(SRC)/process_gradient.cpp
	$(CXX) $(FLAGS) $(SRC)/process_gradient.cpp -lopencv_core -lopencv_imgproc -lopencv_highgui -lz -lrt -o process_gradient

reconstruct: $(SRC)/reconstruct.cpp
	$(CXX) $(FLAGS) -DUF_long=long -I/usr/include/eigen3 $(SRC)/reconstruct.cpp -o reconstruct $(FLUEXFLAGS) $(CERESFLAGS) $(LFLAGS) -lpng -ljpeg -lz -llapack -lblas -lrt -lgfortran -lquadmath

rkhs_reconstruct: $(SRC)/rkhs_reconstruct.cpp
	$(CXX) $(FLAGS) -DUF_long=long -I/usr/include/eigen3 $(SRC)/rkhs_reconstruct.cpp -o rkhs_reconstruct $(CERESFLAGS) $(LFLAGS) -lpng -ljpeg -lz -lrt 

clean:
	rm -f pluriel $(MODULES) field_maker process_gradient reconstruct rkhs_reconstruct
