# Default target first
all:

# options
CFLAGS += -ansi -pedantic -W -Wall -Wold-style-cast -Woverloaded-virtual -Wcast-qual -Wsynth 
# additional flags for debugging...
CFLAGS += -g
LFLAGS += -g
# or for optimization
#CFLAGS += -march=native -O3 -fomit-frame-pointer 

# executables
CC      = g++
LD      = $(CC)
CPP	= $(CC) -E
SHELL   = /bin/bash
MAKE    = /usr/bin/make



sinclude makefile.target


.PHONY: all clean

# Compile everything
all: makefile.target $(TARGETS)

# Clean temporary files
clean:	
	@rm -f $(TARGETS) $(ALLOBJECTS) *~ */*~ makefile.depend makefile.target gmon.out */*.exe
	@rm -rf doc/

# Create dependency table, clean manually if necessary
depend:
	@rm -f makefile.depend 
	@$(MAKE) -s makefile.depend
	@rm -f makefile.target
	@$(MAKE) -s makefile.target

doc: $(ALLFILES)
	@doxygen Doxyfile

makefile.depend:
	@find -noleaf -name '*.cpp' -exec $(CPP) -MM $(CFLAGS) "{}" \; > makefile.depend

makefile.target: makefile.depend
	@echo -n "TARGETS = " > makefile.target
	@find -noleaf -name '*.cpp' -exec egrep -l "^[[:space:]]*(int|void)[[:space:]]+main[[:space:]]*\(" "{}" \; | sed 's/\.cpp$$//' | xargs >> makefile.target
	@echo -n "OBJECTS = " >> makefile.target
	@find -noleaf -name '*.cpp' -exec egrep -L "^[[:space:]]*(int|void)[[:space:]]+main[[:space:]]*\(" "{}" \; | sed 's/\.cpp$$/\.o/' | xargs >> makefile.target
	@echo -n "ALLOBJECTS = " >> makefile.target
	@find -noleaf -name '*.cpp' | sed 's/\.cpp$$/\.o/' | xargs >> makefile.target
	@echo -n "ALLFILES = " >> makefile.target
	@find -noleaf -name '*.cpp' -or -name '*.h' | xargs >> makefile.target

# Compile and link
$(ALLOBJECTS): %.o: %.cpp
	@echo "Compiling $<"
	@$(CC) -c $< -o $@ $(CFLAGS)

$(TARGETS): %: %.o $(OBJECTS)
	@echo "Linking $@"
	@$(LD) $< -o $@ $(OBJECTS) $(LFLAGS) 

sinclude makefile.depend
