# The compiler
CC=mpic++

# Flags
CFLAGS=-Wall -larmadillo -std=c++11 -O3 -fopenmp
PROFFLAGS=-pg -fno-inline-functions
DBGFLAGS=-DDBG -g

MKDIR=mkdir -p
RMDIR=rm -rf
INSTRUMENT=scorep

# Directories for binaries
BINDIR=./bin
PROFDIR=./prof
DEBUGDIR=./debug

# Directories for object files
BUILDDIR=./build
BINOBJDIR=$(BUILDDIR)/objs
PROFOBJDIR=$(BUILDDIR)/prof
DEBUGOBJDIR=$(BUILDDIR)/debug

# Directory for latex source
LATEXDIR=./latex

# Source directories
SRC=./src
INCLUDE=./include

# Source files and object file locations
SRCFILES=utils.cpp testlib.cpp data_type.cpp IsingModel.cpp monte_carlo.cpp
SRCS=$(addprefix $(SRC)/, $(SRCS))
BINOBJS=$(addprefix $(BINOBJDIR)/, $(SRCFILES:.cpp=.o))
PROFOBJS=$(addprefix $(PROFOBJDIR)/, $(SRCFILES:.cpp=.o))
DEBUGOBJS=$(addprefix $(DEBUGOBJDIR)/, $(SRCFILES:.cpp=.o))

# Location for Binaries
EXEC=main phase_transition_mpi test_suite time
BINS=$(addprefix $(BINDIR)/, $(EXEC))
PROFBINS=$(PROFDIR)/phase_transition_mpi
DEBUGBINS=$(addprefix $(DEBUGDIR)/, $(EXEC))

# List phony targets
.PHONY: all profile debug latex clean binclean objclean latexclean 

# "Commands"
all: $(BINS)

profile: $(PROFBINS)

debug: $(DEBUGBINS)

# build latex file
latex:
	$(MAKE) -C $(LATEXDIR)

# Rule for binaries
$(BINDIR)/%: $(BINOBJDIR)/%.o $(BINOBJS)
	$(MKDIR) $(BINDIR)
	$(CC) $^ -o $@ $(CFLAGS) -I$(INCLUDE)

# Rule for profiling binaries
$(PROFDIR)/%: $(PROFOBJDIR)/%.o $(PROFOBJS)
	$(MKDIR) $(PROFDIR)
	$(INSTRUMENT) $(CC) $^ -o $@ $(CFLAGS) $(PROFFLAGS) -I$(INCLUDE)

# Rule for debug binaries
$(DEBUGDIR)/%: $(DEBUGOBJDIR)/%.o $(DEBUGOBJS)
	$(MKDIR) $(DEBUGDIR)
	$(CC) $^ -o $@ $(CFLAGS) $(DEBUGFLAGS) -I$(INCLUDE)

# Rule for object files
$(BINOBJDIR)/%.o: $(SRC)/%.cpp
	$(MKDIR) $(BINOBJDIR)
	$(CC) -c $^ -o $@ $(CFLAGS) -I$(INCLUDE)

# Rule for instrumented object files
$(PROFOBJDIR)/%.o: $(SRC)/%.cpp
	$(MKDIR) $(PROFOBJDIR)
	$(INSTRUMENT) $(CC) -c $^ -o $@ $(CFLAGS) $(PROFFLAGS) -I$(INCLUDE)

# Rule for debug object files
$(DEBUGOBJDIR)/%.o: $(SRC)/%.cpp
	$(MKDIR) $(DEBUGOBJDIR)
	$(CC) -c $^ -o $@ $(CFLAGS) $(DBGFLAG) $(DEBUGFLAGS) -I$(INCLUDE)

# Cleaning
clean: objclean binclean latexclean

latexclean:
	$(MAKE) -C $(LATEXDIR) clean

objclean:
	$(RMDIR) $(BUILDDIR)

binclean:
	$(RMDIR) $(BINDIR) $(PROFDIR) $(DEBUGDIR)
