ifndef	PLATFORM_DIR
$(error please define PLATFORM_DIR 'make PLATFORM_DIR=foo')
else
TOOLS    := tools

ELF2MIF  := $(TOOLS)/elf_read/elf_utils.x
LD	       := mipsel-unknown-elf-ld
CC	       := mipsel-unknown-elf-gcc
AS	       := mipsel-unknown-elf-as
DU	       := mipsel-unknown-elf-objdump
RM	       := rm -rf
ECHO	       := echo
MKDIR	       := mkdir
DTC	       := dtc
HEXDUMP	       := hexdump

OBJS_DIR       := objs
MIF_DIR        := mifs

# =============================================================================
# Include files paths
# =============================================================================

INCLUDE	   += -I. -Iio_drivers -I$(PLATFORM_DIR)

# =============================================================================
# Paths of sources in another directories
# =============================================================================

VPATH      += io_drivers
VPATH      += $(PLATFORM_DIR)

# =============================================================================
# Object files
# =============================================================================

S_SRCS     += reset.s

C_SRCS	   += spi.c
C_SRCS	   += sdcard.c
C_SRCS	   += ioc.c
C_SRCS	   += boot_tty.c
C_SRCS	   += boot_loader_entry.c

OBJS       := $(subst .s,.o,$(S_SRCS))
OBJS       += $(subst .c,.o,$(C_SRCS))
OBJS       := $(addprefix $(OBJS_DIR)/, $(OBJS))

TARGET     := bin.soft

ifdef	SOCLIB
DEFS+= -DSOCLIB_IOC
DTS=platform_soclib.dts
$(info Making for $(PLATFORM_DIR), SocLib variant)
else
DTS=platform_fpga.dts
$(info Making for $(PLATFORM_DIR), FPGA variant)
endif

CFLAGS   := -Wall -mno-gpopt -ffreestanding -fomit-frame-pointer -mips32 \
		    -ggdb -mlong-calls
# =============================================================================
# ALL target. If the MIF variable is defined, the $(MIF) file is generated
# using the $(basename $(MIF))_tab.txt file


all: $(TARGET)
	if [ ! -z $(MIF) ]; then\
		if [ ! -e $(MIF_DIR) ]; then\
			$(MKDIR) $(MIF_DIR);\
		fi;\
		$(ECHO) "[   MIF  ]     $(MIF)";\
		$(ELF2MIF) \
			-ELF_FILE $(TARGET) \
			-SEG_FILE $(basename $(MIF))_tab.txt \
			-MIF_FILE $(MIF_DIR)/$(MIF);\
	fi;

$(TARGET): $(OBJS_DIR) $(OBJS) ldscript $(OBJS_DIR)/platform.ld
	@\
	$(ECHO) "[   LD   ]     $@"
	$(LD) -o $@ -T ldscript $(OBJS)
	$(DU) -D $@ > $@.txt

$(OBJS_DIR)/platform.ld: $(OBJS_DIR)/platform.dtb
	$(HEXDUMP) -v -e '"BYTE(0x" 1/1 "%02X" ")\n"' $< > $@

$(OBJS_DIR)/platform.dtb: $(DTS)
	${DTC} -O dtb -o $@ $<

$(OBJS_DIR):
	$(MKDIR) $@

clean:
	$(RM) $(TARGET).txt $(TARGET) *~ $(OBJS_DIR)

distclean: clean
	$(RM) $(MIF_DIR)
# =============================================================================
# Implicit makefile rules

$(OBJS_DIR)/%.o: %.c
	@\
	$(ECHO) "[   CC   ]     $(notdir $<)"
	$(CC) $(DEFS) $(CFLAGS) $(INCLUDE) -c -o $@ $<
	$(DU) -D $@ > $@.txt

$(OBJS_DIR)/%.o: %.S
	@\
	$(ECHO) "[   AS   ]     $(notdir $<)"
	$(CC) $(DEFS) ${INCLUDE} -g -mips32 -c -o $@ $<
	$(DU) -D $@ > $@.txt


.SILENT:
endif
