include toprules.make

#include default config
include Makefile.conf-default
#if exists, include local config which overrides defaults
ifneq ($(shell ls Makefile.conf 2>/dev/null),)
include Makefile.conf
endif

versrcs = ./Version.cpp
verhdrs = ./Mercury.h
verobjs = $(shell echo $(versrcs) | \
		perl -pe 's|(.*)/([^/]*)\.cpp|$$1/.$$2.o|')

define ENABLE_TARGET_template
ifeq ($$(make_$(1)),YES)
subdirs += $$($(1)_dirs)
$(1)_targ = lib$$($(1)_name)$$(LIBEXT)

$(1)_srcs = $$(wildcard $$(patsubst %,%/*.cpp,$$($(1)_dirs)))
$(1)_hdrs = $$(wildcard $$(patsubst %,%/*.h,$$($(1)_dirs)))
$(1)_objs = $$(shell ls $$($(1)_srcs) | \
		perl -pne 's|(.*)/([^/]*)\.cpp|$$$$1/.$$$$2.o|')
$(1)_gcc_deps = $$(shell ls $$($(1)_srcs) | \
		perl -pne 's|(.*)/([^/]*)\.cpp|$$$$1/.$$$$2.d|')

$$($(1)_targ): version $$($(1)_objs) $$($(1)_deps)
TARGETS += $$($(1)_targ)

ifneq ($$($(1)_gcc_deps),)
ifneq ($$(MAKECMDGOALS),clean)
-include $$($(1)_gcc_deps)
endif
endif  # gcc deps

endif  # make_$(1) enabled
endef

all: config.h after_other_targets
	
$(foreach lib,$(LIBS_TOMAKE),$(eval $(call ENABLE_TARGET_template,$(lib))))

SUBDIRS = $(shell echo $(subdirs) | tr '\\ ' '\n' | sort | uniq | tr '\n' ' ')
APPDIRS = $(appdirs)

after_other_targets: $(TARGETS) $(APPDIRS)
config.h:
	@./configure

###############################################################################

precompile:
ifeq ($(RELEASE),release)
	@-rm -f $(verobjs)
endif

version: precompile $(verobjs)

ifneq ($(MAKECMDGOALS),clean)
$(APPDIRS): $(TARGETS)
endif

###############################################################################

clean: $(SUBDIRS) $(APPDIRS) 

doc: doxygen/doxygen.conf doxygen/doxygen.css $(coresrcs)
	doxygen doxygen/doxygen.conf

include botrules.make
