TARGET := out
BUILD_DIR := build

AS := sdasz80
CC := sdcc
MAKEBIN := makebin

ASFLAGS := -plosgff
CCFLAGS := -mz80 --no-std-crt0
LDFLAGS := -mz80 --no-std-crt0 --code-loc 0x0080 --data-loc 0x8000
MAKEBINFLAGS := -p

ASM_SRCS := boot.asm
ASM_BUILDS := $(addprefix $(BUILD_DIR)/,$(notdir $(ASM_SRCS)))
C_SRCS := main.c
C_BUILDS := $(addprefix $(BUILD_DIR)/,$(notdir $(C_SRCS)))

ASM_RELS := $(ASM_BUILDS:.asm=.rel)
C_RELS := $(C_BUILDS:.c=.rel)

IHX := $(BUILD_DIR)/$(TARGET).ihx
MAP := $(BUILD_DIR)/$(TARGET).map
BIN := $(BUILD_DIR)/$(TARGET).bin
LST := $(ASM_BUILDS:.asm=.lst)
SYM := $(ASM_BUILDS:.asm=.sym)

GENERATED := $(ASM_BUILDS) $(C_BUILDS) $(ASM_RELS) $(C_RELS) $(LST) $(SYM) $(IHX) $(MAP) $(BIN)

.PHONY: all clean

all: $(BIN)

$(BIN): $(IHX)
	$(MAKEBIN) $(MAKEBINFLAGS) $< $@

$(IHX): $(ASM_RELS) $(C_RELS) | $(BUILD_DIR)
	$(CC) $(LDFLAGS) -o $@ $(ASM_RELS) $(C_RELS)

$(BUILD_DIR)/%.rel: %.asm | $(BUILD_DIR)
	$(AS) $(ASFLAGS) -o $@ $<

$(BUILD_DIR)/%.rel: %.c | $(BUILD_DIR)
	$(CC) $(CCFLAGS) -c -o $@ $<

$(BUILD_DIR):
	mkdir -p $@

clean:
	rm -rf $(BUILD_DIR)
