# Directory layout
SRCDIR = src
OBJDIR = obj
INCDIR = include

# Compiler and flags
CC = wcc386
LD = wlink
CFLAGS = -zq -i=$(INCDIR)

# Project name (root) — everything else derives from this
NAME = dspace
TARGET = $(NAME).exe
IMG = $(NAME).img

# Deploy location for testing in DOSBox-X
DOSBOX_DRIVE = ~/DosBox-x/C_Drive

# OpenWatcom DOS extender stub, needed on the disk image alongside TARGET
DOS4GW = ~/openwatcom_c/binw/dos4gw.exe

# Disk image geometry (1.44MB floppy, FAT12)
IMG_BLOCKS = 1440
IMG_FAT = 12

# Source and object files
SRCS = $(wildcard $(SRCDIR)/*.c)
OBJS = $(patsubst $(SRCDIR)/%.c,$(OBJDIR)/%.o,$(SRCS))
DEPS = $(OBJS:.o=.d)

# Default target
all: $(TARGET)

# Link object files into executable
$(TARGET): $(OBJS)
	$(LD) system dos4g name $@ file { $(OBJS) }

# Compile .c files to .o files, with auto-dependency generation
$(OBJDIR)/%.o: $(SRCDIR)/%.c | $(OBJDIR)
	$(CC) -fo=$@ $(CFLAGS) -ad=$(@:.o=.d) -adfs $<

# Ensure obj/ exists before any compile runs
$(OBJDIR):
	mkdir -p $(OBJDIR)

# Pull in auto-generated header dependencies (silently ignored if missing)
-include $(DEPS)

# Clean up build artifacts
clean:
	rm -f $(OBJS) $(DEPS) $(TARGET) $(IMG)

test: $(TARGET)
	cp $(TARGET) $(DOSBOX_DRIVE)/
	echo 'Ready to test'

image: $(TARGET)
	rm -f $(IMG)
	dd if=/dev/zero of=$(IMG) bs=1024 count=$(IMG_BLOCKS)
	mkfs.vfat -F $(IMG_FAT) $(IMG)
	mcopy -i $(IMG) $(TARGET) ::
	mcopy -i $(IMG) $(DOS4GW) ::

.PHONY: all clean test image
