PROJECT_XML := ../src/Project/Project.uvproj
BUILD_DIR := build
TARGET := $(BUILD_DIR)/MCU2_V2.1_260728_4CH

CC := arm-none-eabi-gcc
OBJCOPY := arm-none-eabi-objcopy
SIZE := arm-none-eabi-size

C_SOURCES := $(filter-out ../src/CMSIS/core_cm3.c,$(shell perl extract_sources.pl $(PROJECT_XML)))
S_SOURCES := startup_stm32f10x_hd_gcc.S
OBJECTS := $(patsubst ../src/%.c,$(BUILD_DIR)/%.o,$(C_SOURCES))
OBJECTS += $(BUILD_DIR)/gcc_syscalls.o
OBJECTS += $(BUILD_DIR)/startup_stm32f10x_hd_gcc.o

INCLUDES := \
	-I../src/USER -I../src/CORE -I../src/CMSIS \
	-I../src/SYSTEM/delay -I../src/SYSTEM/debug -I../src/SYSTEM/usart \
	-I../src/STM32F10x_FWLib/inc \
	-I../src/HARDWARE/LED -I../src/HARDWARE/KEY -I../src/HARDWARE/LCD \
	-I../src/HARDWARE/24CXX -I../src/HARDWARE/FLASH -I../src/HARDWARE/IIC \
	-I../src/HARDWARE/SPI -I../src/HARDWARE/BUZZER -I../src/HARDWARE/RFID \
	-I../src/HARDWARE/EXTI -I../src/HARDWARE/TIMER \
	-I../src/HARDWARE/UltrasonicWave -I../src/HARDWARE/USART \
	-I../src/HARDWARE/GPS -I../src/HARDWARE/GSM -I../src/HARDWARE/QR_Code \
	-I../src/HARDWARE/DEVICE -I../src/HARDWARE/NTC_ADC -I../src/HARDWARE/WDG \
	-I../src/HARDWARE/SCALE -I../src/HARDWARE/ElectronicLock \
	-I../src/HARDWARE/MOTOR -I../src/HARDWARE/AUDIO -I../src/HARDWARE/OPTO_SWITCH \
	-I../src/HARDWARE/IR_Distancer -I../src/HARDWARE/RS485 \
	-I../src/HARDWARE/STMFLASH -I../src/HARDWARE/Disinfection

ARCH_FLAGS := -mcpu=cortex-m3 -mthumb
DEFINES := -DSTM32F10X_HD -DUSE_STDPERIPH_DRIVER -Dsignal=gsm_signal_strength
WARNINGS := -Wall -Wextra -Wno-unused-parameter -Wno-unused-variable \
	-Wno-unused-but-set-variable -Wno-sign-compare -Wno-implicit-int \
	-Wno-unknown-pragmas -Wno-format
CFLAGS := $(ARCH_FLAGS) -std=gnu99 -Os -g3 -ffunction-sections -fdata-sections \
	-fcommon -fno-strict-aliasing -fno-builtin -include gcc_compat.h $(DEFINES) $(INCLUDES) $(WARNINGS)
ASFLAGS := $(ARCH_FLAGS) -x assembler-with-cpp -g3
LDFLAGS := $(ARCH_FLAGS) -T stm32f103ve.ld -Wl,--gc-sections \
	-Wl,-Map=$(TARGET).map,--cref -Wl,--print-memory-usage \
	--specs=nano.specs --specs=nosys.specs -u _printf_float
LDLIBS := -Wl,--start-group -lc -lm -Wl,--end-group

.PHONY: all clean verify

all: $(TARGET).hex $(TARGET).bin
	$(SIZE) $(TARGET).elf

$(TARGET).elf: $(OBJECTS) stm32f103ve.ld | $(BUILD_DIR)
	$(CC) $(OBJECTS) $(LDFLAGS) $(LDLIBS) -o $@

$(TARGET).hex: $(TARGET).elf
	$(OBJCOPY) -O ihex $< $@

$(TARGET).bin: $(TARGET).elf
	$(OBJCOPY) -O binary $< $@

$(BUILD_DIR)/%.o: ../src/%.c gcc_compat.h
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -MMD -MP -c $< -o $@

$(BUILD_DIR)/startup_stm32f10x_hd_gcc.o: startup_stm32f10x_hd_gcc.S
	@mkdir -p $(dir $@)
	$(CC) $(ASFLAGS) -c $< -o $@

$(BUILD_DIR)/gcc_syscalls.o: gcc_syscalls.c gcc_compat.h
	@mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -MMD -MP -c $< -o $@

$(BUILD_DIR):
	mkdir -p $@

clean:
	rm -rf $(BUILD_DIR)

-include $(OBJECTS:.o=.d)
