TARGET_SIM ?= verilog/verilator/obj_dir/VTop
TARGET_FLAGS ?= $(RISCV_TARGET_FLAGS)
ifeq ($(shell command -v $(TARGET_SIM) 2> /dev/null),)
    $(error Target simulator executable '$(TARGET_SIM)` not found)
endif

RISCV_PREFIX   ?= riscv64-unknown-elf-
RISCV_GCC      ?= $(RISCV_PREFIX)gcc
RISCV_OBJDUMP  ?= $(RISCV_PREFIX)objdump
RISCV_OBJCOPY  ?= $(RISCV_PREFIX)objcopy
RISCV_GCC_OPTS ?= -g -static -mcmodel=medany -fvisibility=hidden -nostdlib -nostartfiles $(RVTEST_DEFINES)

COMPILE_CMD = $$(RISCV_GCC) $(1) $$(RISCV_GCC_OPTS) \
							-I$(ROOTDIR)/riscv-test-suite/env/ \
							-I$(TARGETDIR)/$(RISCV_TARGET)/ \
							-T$(TARGETDIR)/$(RISCV_TARGET)/link.ld \
							$$(<) -o $$@ 

OBJDUMP_CMD = $$(RISCV_OBJDUMP) $$@ -D > $$@.objdump; \
					$$(RISCV_OBJDUMP) $$@ --source > $$@.debug; \
                    $$(RISCV_OBJDUMP) -t $$@ | grep " begin_signature$$$$" | awk '{ print $$$$1 }' > $$@.begin_signature; \
                    $$(RISCV_OBJDUMP) -t $$@ | grep " end_signature$$$$" | awk '{ print $$$$1 }' > $$@.end_signature; \
                    $$(RISCV_OBJDUMP) -t $$@ | grep " tohost$$$$" | awk '{ print $$$$1 }' > $$@.halt \


OBJCOPY_CMD = $$(RISCV_OBJCOPY) $$@ -O binary  -j .text -j .data -j .tohost $$@.asmbin

COMPILE_TARGET=\
				$(COMPILE_CMD); \
        if [ $$$$? -ne 0 ] ; \
                then \
                echo "\e[31m$$(RISCV_GCC) failed for target $$(@) \e[39m" ; \
                exit 1 ; \
                fi ; \
				$(OBJDUMP_CMD); \
        if [ $$$$? -ne 0 ] ; \
                then \
                echo "\e[31m $$(RISCV_OBJDUMP) failed for target $$(@) \e[39m" ; \
                exit 1 ; \
                fi ; \
                $(OBJCOPY_CMD); \
        if [ $$$$? -ne 0 ] ; \
                then \
                echo "\e[31m $$(RISCV_OBJCOPY) failed for target $$(@) \e[39m" ; \
                exit 1 ; \
                fi ; \
    
RUN_CMD = $(TARGET_SIM) $(TARGET_FLAGS) \
            -signature 0x$(shell cat $(<).begin_signature) 0x$(shell cat $(<).end_signature) $(*).signature.output \
            -halt 0x$(shell cat $(<).halt) \
            -time 1000000 \
            -instruction $(<).asmbin
RUN_TARGET = \
    $(RUN_CMD)
