include $(TOPDIR)/Makefile.config

USERLIB = $(TOPDIR)/userlib

AS = $(RISCV_AS) -c
GCC = $(RISCV_GCC)
LD = $(RISCV_LD)

INCPATH += -I$(TOPDIR) -I$(USERLIB)
LDFLAGS = $(RISCV_LDFLAGS) -T $(USERLIB)/ldscript.lds
ASFLAGS = $(RISCV_ASFLAGS) $(INCPATH)
CFLAGS  = $(RISCV_CFLAGS) $(INCPATH)

# Rules
%.o: %.s
	$(AS) $(ASFLAGS) -c $<

%.o: %.c
	$(GCC) $(CFLAGS) -c $<

%.a: %.o
	$(AR) $(ARFLAGS) $@ $<

%.dump: %.o
	$(RISCV_OBJCOPY) -j .text -O $(DUMP_FORMAT) $< $@

%.guac: %.o
	$(LD) $(LDFLAGS) $+ -o $@

# Dependencies
.%.d: %.s
	@echo Generating dependencies for $<
	@$(SHELL) -ec '$(GCC) -x assembler-with-cpp -M $(ASFLAGS) $< \
		| sed '\''s/\($*\)\.o[ :]*/\1.o $@ : /g'\'' > $@; \
		[ -s $@ ] || rm -f $@'

.%.d: %.c
	@echo Generating dependencies for $<
	@$(SHELL) -ec '$(GCC) -M $(CFLAGS) $< \
		| sed '\''s/\($*\)\.o[ :]*/\1.o $@ : /g'\'' > $@; \
		[ -s $@ ] || rm -f $@'

$(PROGRAMS):
	$(LD) $(LDFLAGS) $+ -o $@

# Targets
#clean:
#	rm -rf *.o 2> /dev/null
#	rm -rf *.dump 2> /dev/null
#	rm -rf *.guac 2> /dev/null