# Sprinter C Compiler — top-level Makefile
#
#   make             build host tools, libc archive, all tests, all apps
#   make tools       build only host tools (mkexe)
#   make lib         build lib/sprinter.lib (libc archive used by sprinter-cc)
#   make tests       build all libc feature tests under tests/
#   make examples    build all real applications under examples/
#   make floppy      package every .exe + test fixtures into mame/v306/IMG/mc.img
#   make check       run mkexe unit tests
#   make clean       remove all build artefacts
#   make sdcc        download/extract vendored SDCC
#
# Most heavy lifting is delegated to sub-Makefiles.

# Small libc-feature tests (one program per .c-language feature or libc API).
TESTS := hello banked bankedbg strtest cat seek malloc mem_test argv errno \
         rt_test openenv ls conio attrprob timedir mouse banklocl stdlib \
         assrtest ptime stattest filetest gfx_demo gfx_d16 gfx_text gfx_mous

# Larger end-user applications under examples/.
APPS  := mdview

MAME_DIR    := mame/v306
FLOPPY_IMG  := $(MAME_DIR)/IMG/mc.img
MAKE_DISK   := $(MAME_DIR)/make_disk.py

TEST_EXES := $(foreach t,$(TESTS),tests/$(t)/$(t).exe)
APP_EXES  := $(foreach a,$(APPS),examples/$(a)/$(a).exe)
ALL_EXES  := $(TEST_EXES) $(APP_EXES)

DATA_FILES := \
    tests/cat/test.txt          \
    tests/seek/big.txt          \
    examples/mdview/SAMPLE.MD

.PHONY: all tools lib tests examples check clean sdcc floppy $(TESTS) $(APPS)

all: tools lib tests examples

tools:
	$(MAKE) -C toolchain/mkexe

lib:
	$(MAKE) -C lib

check: tools
	$(MAKE) -C toolchain/mkexe check

tests:    $(TESTS)
examples: $(APPS)

$(TESTS): tools lib
	$(MAKE) -C tests/$@

$(APPS):  tools lib
	$(MAKE) -C examples/$@

# Generate big.txt if missing (gen_bigfile.py creates 100 KB marker file).
tests/seek/big.txt:
	cd tests/seek && python3 gen_bigfile.py big.txt 102400

# Re-pack the MAME floppy image with every built exe + needed data files.
floppy: tests examples tests/seek/big.txt
	python3 $(MAKE_DISK) $(FLOPPY_IMG) $(ALL_EXES) $(DATA_FILES)
	@echo
	@echo "Floppy ready: $(FLOPPY_IMG)"
	@echo "Run:  cd $(MAME_DIR) && ./run_mame.sh"

clean:
	$(MAKE) -C toolchain/mkexe clean
	$(MAKE) -C lib clean
	@for t in $(TESTS); do $(MAKE) -C tests/$$t clean; done
	@for a in $(APPS);  do $(MAKE) -C examples/$$a clean; done

sdcc:
	bash third_party/setup-sdcc.sh
