# Makefile for cc09 - Wintek 6809 cross tools recreation (a9, xld, xc9 etc.)
# Builds native tools for macOS and Linux/UNIX from src/
# Does not touch anything under WINTEK/

CC      ?= cc
CFLAGS  ?= -O2 -Wall -Wextra -std=c99 -D_POSIX_C_SOURCE=200809L
# For debug: CFLAGS += -g

PREFIX  ?= /usr/local
BINDIR  ?= $(PREFIX)/bin

TOOLS   = a9 xld xc9 hex   # hex is the PROM filter from HEX.EXE

.PHONY: all clean install uninstall test dirs

all: dirs $(addprefix bin/,$(TOOLS))

dirs:
	mkdir -p bin

COMMON_HDR = src/common/srec.h src/common/util.h src/common/opcode6809.h src/common/sections.h
COMMON_SRC = src/common/srec.c src/common/util.c src/common/opcode6809.c src/common/sections.c
COMMON_OBJ = $(COMMON_SRC:.c=.o)

bin/a9: src/a9/a9.c $(COMMON_OBJ)
	$(CC) $(CFLAGS) -Isrc/common -o $@ $^

bin/xld: src/xld/xld.c $(COMMON_OBJ)
	$(CC) $(CFLAGS) -Isrc/common -o $@ $^

bin/xc9: src/xc9/xc9.c $(COMMON_OBJ)
	$(CC) $(CFLAGS) -Isrc/common -o $@ $^

bin/hex: src/common/hex.c
	$(CC) $(CFLAGS) -o $@ $^

src/common/%.o: src/common/%.c $(COMMON_HDR)
	$(CC) $(CFLAGS) -Isrc/common -c -o $@ $<

# Ensure minimal sections implementation exists (committed small file)
src/common/sections.c: src/common/sections.h

src/common/sections.h:
	@true

clean:
	rm -f bin/* src/common/*.o
	rm -rf bin

install: all
	mkdir -p $(BINDIR)
	cp bin/a9 bin/xld bin/xc9 bin/hex $(BINDIR)/
	@echo "Installed to $(BINDIR)"

uninstall:
	rm -f $(BINDIR)/a9 $(BINDIR)/xld $(BINDIR)/xc9 $(BINDIR)/hex

test: all
	@echo "=== Testing CLI banners (should match original style) ==="
	@bin/a9 2>&1 | cat || true
	@echo "---"
	@bin/xld 2>&1 | cat || true
	@echo "---"
	@bin/xc9 2>&1 | cat || true
	@echo "---"
	@bin/hex 2>&1 | cat || true
	@echo "=== Basic structure and build OK ==="
	@ls -l bin/
	@echo "For real tests once implemented: make asm-test ; etc."

asm-test: bin/a9
	bin/a9 lib/src/cstart.asm -l /tmp/cstart.lst -o /tmp/cstart.rel 2>&1 || true
	@echo "Produced (or attempted) /tmp/cstart.rel / .lst using current a9 impl."

# To compare behavior with original, use dosbox + the untouched WINTEK/*.EXE on
# the staged lib/src/*.asm files (or crafted tests under tests/).

