# VPATH is common path for cpp files that are not in makefile dir
# EXE_TYPE : 'exe' - executable, 'lib' - dynamic lib (.so), 'static' - static lib (.a)
EXE_TYPE =	exe
VPATH =		
D_CXXFLAGS =	-std=c++14 -g -Wall -fmessage-length=0 -D_DEBUG -Wno-unused-variable -Wno-unused-but-set-variable
R_CXXFLAGS =	-std=c++14 -O3 -Wall -fmessage-length=0 -Wno-unused-variable -Wno-unused-but-set-variable
D_LIBS =	#-lpthread
R_LIBS =	#-lpthread
D_TARGET_DIR =	debug
R_TARGET_DIR =	release
D_TARGET_EXE =	median
R_TARGET_EXE =	median
D_TRUNK_DIR =	debug
R_TRUNK_DIR =	release
RES_DIR = Res

# Add sourcess without any path (Use VPATH for additional paths with sources)
SRCS =		main.cpp

# Do not touch below
######################################################
D_CXXFLAGS +=	-MMD -MP
R_CXXFLAGS +=	-MMD -MP

D_TARGET = 	${D_TARGET_DIR}/$(D_TARGET_EXE)
R_TARGET = 	${R_TARGET_DIR}/$(R_TARGET_EXE)

D_OBJS =	$(addprefix $(D_TRUNK_DIR)/, $(SRCS:.cpp=.o))
R_OBJS =	$(addprefix $(R_TRUNK_DIR)/, $(SRCS:.cpp=.o))

define resource_compile_rule
$2/$1.o : $1.bin
	ld -r -b binary $(RES_DIR)/$1.bin -o $2/$1.o 
endef

# Main rules : first rule is master one
all:		r_prepdirs $(R_TARGET) d_prepdirs $(D_TARGET)
release:	r_prepdirs $(R_TARGET)
debug:		d_prepdirs $(D_TARGET)

clean:
	rm -f $(D_TRUNK_DIR)/*.o $(D_TRUNK_DIR)/*.d;
	rmdir $(D_TRUNK_DIR)/ 2>/dev/null || true;
	rm -f $(R_TRUNK_DIR)/*.o $(R_TRUNK_DIR)/*.d;
	rmdir $(R_TRUNK_DIR)/ 2>/dev/null || true;
	rm -f ${D_TARGET_DIR}/$(D_TARGET_EXE);
	rm -f ${R_TARGET_DIR}/$(R_TARGET_EXE);
	@echo 'Clean done';

# other rules
.PHONY : clean r_prepdirs d_prepdirs

# preparation rules
r_prepdirs:
	@mkdir -p $(R_TRUNK_DIR) $(R_TARGET_DIR)

d_prepdirs:
	@mkdir -p $(D_TRUNK_DIR) $(D_TARGET_DIR)

ifeq ($(EXE_TYPE), lib)
D_LIBS += -shared
R_LIBS += -shared
endif

# Make target rule
$(R_TARGET):	$(R_OBJS) $(R_RES_OBJS)
ifeq ($(EXE_TYPE), static)
	ar rcs $(R_TARGET) $(R_OBJS) $(R_RES_OBJS)
else
	$(CXX) -o $(R_TARGET) $(R_OBJS) $(R_RES_OBJS) $(R_LIBS)
endif
	@echo 'Build done for $(R_TARGET) [release]';

$(D_TARGET):	$(D_OBJS) $(D_RES_OBJS)
ifeq ($(EXE_TYPE), static)
	ar rcs $(D_TARGET) $(D_OBJS) $(D_RES_OBJS)
else
	$(CXX) -rdynamic -o $(D_TARGET) $(D_OBJS) $(D_LIBS) $(D_RES_OBJS)
endif
	@echo 'Build done for $(D_TARGET) [debug]';

$(R_TRUNK_DIR)/%.o:	%.cpp
	$(CXX) $(R_CXXFLAGS) -o $@ -c $<

$(D_TRUNK_DIR)/%.o: %.cpp
	$(CXX) $(D_CXXFLAGS) -o $@ -c $<

# Include all generated .d files (IF ANY, no force to build them)
-include $(R_OBJS:.o=.d)
-include $(D_OBJS:.o=.d)

