DEVICE?=STM32F401xE
TARGET?=stm32f4x
CPU?=cortex-m7

APP=mam-arm04.elf

BINDIR=bin
SRCDIR=src
INCDIR=include
OBJDIR=obj
DEPDIR=$(OBJDIR)/.deps

DEVICEDIR=devices/$(DEVICE)
GENERALDIR=devices/general

PROJSRCS=$(wildcard $(SRCDIR)/*.c)
GENERALSRCS=$(wildcard $(GENERALDIR)/*.c)
DEVICESRCS=$(wildcard $(DEVICEDIR)/*.c)

SRCS=$(PROJSRCS) $(GENERALSRCS) $(DEVICESRCS)
OBJS=$(patsubst %.c,$(OBJDIR)/%.o,$(SRCS))
DEPFILES=$(patsubst %.c,$(DEPDIR)/%.d,$(SRCS))

DEPFLAGS = -MT $@ -MMD -MP -MF $(DEPDIR)/$*.d
CFLAGS=-I$(INCDIR) \
				-I$(DEVICEDIR)/$(INCDIR) \
				-Ilibs/CMSIS_6/CMSIS/Core/Include \
				-Ilibs/cmsis_device_f4/Include \
				-mthumb -mcpu=$(CPU) --specs=nano.specs -g \
				-D$(DEVICE)
LDFLAGS=-T$(DEVICEDIR)/linker_script.ld

CC=arm-none-eabi-gcc
LD=arm-none-eabi-ld
OPENOCD=openocd

$(BINDIR)/$(APP): $(OBJS) | $(BINDIR)
	$(CC) $^ -o $@ $(CFLAGS) $(LDFLAGS) $(DEPFLAGS)

%.o : %.c
$(OBJDIR)/%.o: %.c | $(DEPDIR) $(OBJDIR)
	mkdir -p "$(dir $@)"
	mkdir -p $(dir $(DEPDIR)/$*.d)
	$(CC) -c $< -o $@ $(CFLAGS) $(DEPFLAGS)

.PHONY: openocd flash clean
openocd:
	$(OPENOCD) -f interface/stlink.cfg -f target/$(TARGET).cfg

flash: $(BINDIR)/$(APP)
	$(OPENOCD) -f interface/stlink.cfg -f target/$(TARGET).cfg -c "program $(BINDIR)/$(APP) verify reset exit"

clean:
	rm -rf $(OBJDIR) $(BINDIR) $(DEPDIR)

$(BINDIR): ; mkdir -p $@
$(OBJDIR): ; mkdir -p $@
$(DEPDIR): ; mkdir -p $@

$(DEPFILES):
include $(wildcard $(DEPFILES))
