# <top>/configure/RULES_EXPAND

vpath %@ $(USR_VPATH) $(ALL_SRC_DIRS)

#---------------------------------------------------------------
# Variable expansion

# Default settings
EXPAND_TOOL ?= $(PERL) $(TOOLS)/expandVars.pl

EXPANDFLAGS += -t $(INSTALL_LOCATION) -a $(T_A)
EXPANDFLAGS += $(addprefix -D ,$(EXPAND_VARS))

# The names of files to be expanded must end with '@'
EXPANDED = $(EXPAND:%@=%)

$(EXPANDED): %: %@
	$(ECHO) "Expanding $< to $@"
	@$(RM) $@
	@$(EXPAND_TOOL) $(EXPANDFLAGS) $($@_EXPANDFLAGS) $< $@

clean: expand_clean

expand_clean:
	@$(RM) $(EXPANDED)

.PRECIOUS: $(EXPANDED)
.PHONY: expand_clean

#---------------------------------------------------------------
# Assemblies (files assembled from snippets)

ASSEMBLE_TOOL ?= $(PERL) $(TOOLS)/assembleSnippets.pl

define COMMON_ASSEMBLY_template
ifneq '$$($1_PATTERN)' ''
$1_SNIPPETS += $$(foreach dir, .. $$(SRC_DIRS), \
    $$(wildcard $$(dir)/$$($1_PATTERN)))
endif
$(COMMON_DIR)/$1: $$($1_SNIPPETS)
	$(ECHO) "Assembling common file $$@ from snippets"
	@$(RM) $1
	$(ASSEMBLE_TOOL) -o $1 $$^
	@$(MV) $1 $$@
endef
$(foreach asy, $(COMMON_ASSEMBLIES), \
    $(eval $(call COMMON_ASSEMBLY_template,$(strip $(asy)))))

define ASSEMBLY_template
ifneq '$$($1_PATTERN)' ''
$1_SNIPPETS += $$(foreach dir, .. $$(SRC_DIRS), \
    $$(wildcard $$(dir)/$$($1_PATTERN)))
endif
$1: $$($1_SNIPPETS)
	$(ECHO) "Assembling file $$@ from snippets"
	@$(RM) $$@
	$(ASSEMBLE_TOOL) -o $$@ $$^
endef
$(foreach asy, $(ASSEMBLIES), \
    $(eval $(call ASSEMBLY_template,$(strip $(asy)))))

define ASSEMBLY_DEP_template
$1$(DEP):
	@echo $1: > $$@
endef
$(foreach asy, $(sort $(COMMON_ASSEMBLIES) $(ASSEMBLIES)), \
    $(eval $(call ASSEMBLY_DEP_template,$(strip $(asy)))))

