include ../makedefs

###### recursive wildcard function #######
rwildcard=$(wildcard $1$2) $(foreach d, $(wildcard $1*),$(call rwildcard,$d/,$2))

###### returns all directories except one generated by configuro ######
DIRS = $(filter-out $(NAME)/, $(wildcard */))

###### returns all sources in example directory ######
SOURCES    = $(wildcard *.c)
CPPSOURCES = $(wildcard *.cpp)
ASM_FILES  = $(wildcard *.asm)

###### recursively find all sources in every subdirectory ######
SOURCES    += $(foreach d, $(DIRS),$(call rwildcard,$(d),*.c))
CPPSOURCES += $(foreach d, $(DIRS),$(call rwildcard,$(d),*.cpp))
ASM_FILES  += $(foreach d, $(DIRS),$(call rwildcard,$(d),*.asm))

###### get list of source directories to add to compiler include paths ######
INC_DIRS = $(foreach d, $(sort $(dir $(abspath $(SOURCES) $(CPPSOURCES) $(AMS_FILES)))), -I$(d))

###### recursively find all cmd scripts in every returned directory ######
CMDS = $(foreach d, $(DIRS),$(call rwildcard,$(d),*.cmd))

###### return list of .obj's from all .c's ######
OBJECTS  = $(patsubst %.c, %.obj, $(SOURCES))
OBJECTS += $(patsubst %.cpp, %.obj, $(CPPSOURCES))
OBJECTS += $(patsubst %.asm, %.obj, $(ASM_FILES))

###### return config file name #######
NAME = $(strip $(patsubst %.cfg, %, $(wildcard *.cfg)))

###### return example name #######
EXAMPLENAME = $(notdir $(shell $(pwd)))

###### Extend compiler options here ######

CFLAGS += $(INC_DIRS) 

###### Extend linker options here ######
LFLAGS += $(CMDS) 

.PRECIOUS: %/compiler.opt %/linker.cmd

all: $(EXAMPLENAME).out

%/compiler.opt: %/linker.cmd;

%.obj : %.c
%.obj : %.cpp
%.obj : %.asm

%/linker.cmd: %.cfg
	@ echo Running Configuro...
	@ $(XDC_INSTALL_DIR)/xs xdc.tools.configuro -c "$(CODEGEN_INSTALL_DIR)" -t $(XDCTARGET) -p $(PLATFORM) --compileOptions "$(CFLAGS)" $(NAME).cfg

%.obj: %.c $(NAME)/compiler.opt
	@ echo Building $@
	@ $(CC)  $(CFLAGS) $< --cmd_file=$(NAME)/compiler.opt --output_file=$@

%.obj: %.cpp $(NAME)/compiler.opt
	@ echo Building $@
	@ $(CC)  $(CFLAGS) $< --cmd_file=$(NAME)/compiler.opt --output_file=$@

%.obj: %.asm $(NAME)/compiler.opt
	@ echo Building $@
	@ $(CC)  $(CFLAGS) $< --cmd_file=$(NAME)/compiler.opt --output_file=$@

$(EXAMPLENAME).out: $(OBJECTS) $(NAME)/linker.cmd
	@ echo linking...
	@ $(LNK) $(CFLAGS) -z $(OBJECTS) -l$(NAME)/linker.cmd $(LFLAGS) -o $(EXAMPLENAME).out

clean:
	@ echo Cleaning...
	@ $(call remove, $(OBJECTS))
	@ $(call remove, $(EXAMPLENAME).out)
	@ $(call remove, $(NAME).map)
	@ $(RMDIR) $(NAME)
