include toc.make

S11N_NS ?= s11n

NAMESPACE_PREFIX = src/


NS_SOURCES = $(wildcard $(NAMESPACE_PREFIX)*.at)
NS_HEADERS =
# Be careful with SOURCES/HEADERS, lest they be cleaned up when you don't
# want them to be. Simplest is to put everything into NS_{HEADERS/SOURCES} and expect
# them to be filtered by sed.

SOURCES = \
	$(patsubst $(NAMESPACE_PREFIX)%,%,$(NS_SOURCES)) 
HEADERS = \
	$(patsubst $(NAMESPACE_PREFIX)%,%,$(NS_HEADERS)) 
CLEAN_FILES += $(SOURCES) $(HEADERS)


INSTALL_PACKAGE_HEADERS_DEST = $(prefix)/include/$(S11N_NS)
INSTALL_PACKAGE_HEADERS = $(HEADERS)

FLEXES_TAR = flexes.tar

# use_preflexed_lexers = 1

ifeq (,$(use_preflexed_lexers))
ifeq (,$(FLEX_BIN))
  use_preflexed_lexers = 1
else
  use_preflexed_lexers = 0
endif
endif


ifeq (1,$(use_preflexed_lexers))
# This tree is using pre-flexed lexer files.
# Any changes made to the original flex files will be ignored.
SOURCES_FLEX = $(shell tar tf $(FLEXES_TAR))
DISTCLEAN_FILES += $(SOURCES_FLEX)
$(SOURCES_FLEX): $(FLEXES_TAR)
	@echo Unpacking pre-flexed $@; tar xf $(FLEXES_TAR) $@
	@touch $@
flexes: $(SOURCES_FLEX)
else
# we will flex the lexers ourselves...
include flex.make
$(FLEXES_TAR): flexes $(SOURCES_FLEX)
	tar cf $@ $(SOURCES_FLEX)
dist: $(FLEXES_TAR)
DISTCLEAN_FILES += $(FLEXES_TAR)
endif
# ^^^^^ !use_preflexed_lexers

ifneq (,$(wildcard $(FLEXES_TAR)))
DIST_FILES += $(FLEXES_TAR)
endif


DIST_FILES += flex.make



NAMESPACE = $(S11N_NS)
FILE_FILTERS = namespace
namespace_FILTER_RULES = -e 's|S11N_NS|$(S11N_NS)|g'
namespace_FILTER_NAMESED = s,$(NAMESPACE_PREFIX),,
namespace_FILTER_SOURCES = $(NS_SOURCES) $(NS_HEADERS)
include $(TOC_MAKESDIR)/FILE_FILTERS.make


COMMON_FLEX_DEFS = common_flex_definitions.at

$(COMMON_FLEX_DEFS):
	@true

%.flex.at: $(COMMON_FLEX_DEFS)


OBJECTS = $(patsubst %.cpp,%.o,$(SOURCES) $(SOURCES_FLEX))

INSTALL_PACKAGE_HEADERS_DEST = $(prefix)/include/$(S11N_NS)
INSTALL_PACKAGE_HEADERS = $(HEADERS)

DIST_FILES += $(wildcard $(NAMESPACE_PREFIX)/*.* $(COMMON_FLEX_DEFS))


SYMLINK_HEADERS = $(INSTALL_PACKAGE_HEADERS)
SYMLINK_HEADERS_DEST = $(top_srcdir)/include/$(S11N_NS)
include $(TOC_MAKESDIR)/symlink_headers.make

FlexLexer_h = $(S11N_NS)/FlexLexer.h
patch-FlexLexer:
	@grep '<FlexLexer.h>' *.flex.cpp &>/dev/null || exit 0; \
	echo "Patching generated flex files to use <$(FlexLexer_h)>..."; \
	$(PERL) -i -pe 's|<FlexLexer\.h>|<$(FlexLexer_h)>|g' *.flex.cpp

all: FILE_FILTERS flexes patch-FlexLexer symlink-headers $(OBJECTS)
