# The MIT License (MIT)
#
# Copyright (C) 2026 Scott Duensing
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.

# Sound Library Makefile for DJGPP cross-compilation
#
# audio.lib (see audio.h) and its sound drivers: every drivers/<name>/
# directory is one driver, built from all its sources into
# drivers/<name>.drv beside the library, where audio.lib finds it.
#
# The mixer and the drivers run code at interrupt time from pinned
# memory (audioLockSpan pins from a module's first listed function to the
# end of its data), so gcc must not split functions into hot and cold
# parts placed elsewhere, nor turn loops into memset/memcpy calls.

include ../../../common.mk

ISR_CFLAGS = -fno-reorder-blocks-and-partition -fno-tree-loop-distribute-patterns
CFLAGS     = $(DOS_CFLAGS) $(ISR_CFLAGS) -I. -I../libdvx -I../libdvx/platform -I../libdvx/thirdparty -I../libtasks -I../dvxshell

OBJDIR    = ../../../../obj/audio
LIBSDIR   = ../../../../bin/libs

SRCS      = $(wildcard *.c)
OBJS      = $(patsubst %.c,$(OBJDIR)/%.o,$(SRCS))
TARGETDIR = $(LIBSDIR)/kpunch/audio
TARGET    = $(TARGETDIR)/audio.lib

DRVDIR      = $(TARGETDIR)/drivers
DRV_OBJS    = $(patsubst %.c,$(OBJDIR)/%.o,$(wildcard drivers/*/*.c))
DRV_TARGETS = $(patsubst %,$(DRVDIR)/%.drv,$(DVX_DRIVERS))

.PHONY: all clean

all: $(TARGET) $(TARGETDIR)/audio.dep $(DRV_TARGETS)

$(TARGETDIR)/audio.dep: audio.dep | $(TARGETDIR)
	sed 's/$$/\r/' $< > $@

$(TARGET): $(OBJS) | $(TARGETDIR)
	$(DXE3GEN) -o $(TARGETDIR)/audio.dxe -U $(OBJS)
	mv $(TARGETDIR)/audio.dxe $@

$(foreach d,$(DVX_DRIVERS),$(eval $(call DVX_DRIVER_RULE,$d)))

$(OBJDIR)/%.o: %.c $(DVX_MAKEFILES) | $(OBJDIR)
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -c -o $@ $<

$(OBJDIR):
	mkdir -p $(OBJDIR)

$(TARGETDIR):
	mkdir -p $(TARGETDIR)

$(DRVDIR):
	mkdir -p $(DRVDIR)

-include $(OBJS:.o=.d) $(DRV_OBJS:.o=.d)

clean:
	rm -rf $(OBJDIR) $(TARGETDIR)
