# first author : Vincent Pierlot
# modified by Sebastien Pierard

CC=g++

COMMONFLAGS = -W -Wall -Wextra --pedantic -Werror -O2 -Wunused -Wno-unused-function -Wno-unused-parameter
DEBUG = no
ifeq ($(DEBUG),yes)
	FLAGS = $(COMMONFLAGS) -g -ggdb -pg
else
	FLAGS = $(COMMONFLAGS)
endif

CFLAGS = $(FLAGS) -D _GNU_SOURCE -I/opt/local/include
LDFLAGS = $(FLAGS) -l jpeg -L/opt/local/lib

# the name of this Makefile
MAKEFILE = Makefile

# directory of the source files .c and .h
SRCDIR = ./src
# directory of the binary files .o
BINDIR = ./bin
# directory of the dependency files .d
DEPDIR = ./dep
# directory of the source files .c and .h
SRCDIRM = ./src_mains
# directory of the binary files .o
BINDIRM = ./bin_mains
# directory of the dependency files .d
DEPDIRM = ./dep_mains
# directory used by 'tarball' target to store archives .tar.gz
ARCHIVESDIR = ./archives

SRC = $(wildcard $(SRCDIR)/*.cpp)
INC = $(wildcard $(SRCDIR)/*.h)
OBJ = $(patsubst $(SRCDIR)/%.cpp,$(BINDIR)/%.o,$(SRC))
DEP = $(patsubst $(SRCDIR)/%.cpp,$(DEPDIR)/%.d,$(SRC))

SRCM = $(wildcard $(SRCDIRM)/*.cpp)
OBJM = $(patsubst $(SRCDIRM)/%.cpp,$(BINDIRM)/%.o,$(SRCM))
DEPM = $(patsubst $(SRCDIRM)/%.cpp,$(DEPDIRM)/%.d,$(SRCM))
EXEC = $(patsubst $(SRCDIRM)/%.cpp,%,$(SRCM))

default: all

all: $(OBJM)

# pull in dependency info for existing .o files
-include $(DEP)
-include $(DEPM)

dummy:$(OBJ) $(OBJM) ;

# compile and generate dependency info
$(BINDIRM)/%.o: $(SRCDIRM)/%.cpp $(OBJ) $(MAKEFILE)
	@mkdir -p $(BINDIRM) $(DEPDIRM)
	@printf "Compiling $@ ... \r\n"
	@$(CC) -c $(CFLAGS) -I$(SRCDIR) $< -o $@
	@$(CC) -MM $(CFLAGS) -I$(SRCDIR) -MT $(BINDIRM)/$*.o $< > $(DEPDIRM)/$*.d
	@printf "\033[1m%79s\033[0m\r\n" "OK"
	@printf "Linking $@ ... \r\n"
	@$(CC) $(LDFLAGS) $@ $(BINDIR)/*.o -o $*
	@printf "\033[1m%79s\033[0m\r\n" "OK"

$(BINDIR)/%.o: $(SRCDIR)/%.cpp $(MAKEFILE)
	@mkdir -p $(BINDIR) $(DEPDIR)
	@printf "Compiling $@ ... \r\n"
	@$(CC) -c $(CFLAGS) $< -o $@
	@$(CC) -MM $(CFLAGS) -MT $(BINDIR)/$*.o $< > $(DEPDIR)/$*.d
	@printf "\033[1m%79s\033[0m\r\n" "OK"

.PHONY: stats clean mrproper

# make an archive
tarball: $(MAKEFILE) $(SRC) $(INC) $(SRCM) *.txt
	@mkdir -p $(ARCHIVESDIR)
	tar zcf $(ARCHIVESDIR)/$(shell basename $(shell pwd))-$(shell date +%Y%m%d-%Hh%Mm).tar.gz $^

# Display some statistics on source files
stats:
	@echo lines words bytes file
	@ls $(SRCDIR)/* $(SRCDIRM)/* $(MAKEFILE) | xargs wc

# cleaners
clean:
	rm -f $(OBJ) $(DEP) $(OBJM) $(DEPM) $(SRCDIR)/*~ $(SRCDIRM)/*~ *~ core *.out
	rm -rf $(BINDIR) $(DEPDIR) $(BINDIRM) $(DEPDIRM)

mrproper: clean
	rm -f $(EXEC)

