library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

library osvvm; -- Utility Library
context osvvm.OsvvmContext;

use work.rtps_package.all;
use work.user_config.all;
use work.rtps_config_package.all;
use work.rtps_test_package.all;

-- This testbench tests the metatraffic operation behaviour of the RTPS Reader. (Remote Endpoint matching and memory behaviour)
-- This testbench is using external names to access the memory of the rtps_reader directly and check the contents at the supposed locations.
-- This testbench covers following:
--  * Mathing Endpoint
--  * Memory Full Behaviour
--  * Unmatching Endpoint
--  * Unmatching Participant
--  * Updating previously matched Endpoint
--  * Unknown Metatraffic Operation

entity L0_rtps_reader_test1 is
end entity;

architecture testbench of L0_rtps_reader_test1 is
    
    -- *CONSTANT DECLARATION*
    constant MAX_REMOTE_ENDPOINTS   : natural := 3;
    constant NUM_READERS            : natural := 2;
    
    impure function gen_test_config return CONFIG_ARRAY_TYPE is
        variable ret : CONFIG_ARRAY_TYPE(0 to NUM_READERS-1) := (others => DEFAULT_READER_CONFIG);
    begin
        -- vrk
        ret(0).RELIABILITY_QOS              := RELIABLE_RELIABILITY_QOS;
        ret(0).LIVELINESS_QOS               := AUTOMATIC_LIVELINESS_QOS;
        ret(0).DURABILITY_QOS               := VOLATILE_DURABILITY_QOS;
        ret(0).HEARTBEAT_RESPONSE_DELAY     := DURATION_ZERO;
        ret(0).HEARTBEAT_SUPPRESSION_DELAY  := DURATION_ZERO;
        ret(0).LEASE_DURATION               := DURATION_INFINITE;
        ret(0).WITH_KEY                     := TRUE;
        ret(0).MAX_PAYLOAD_SIZE             := 1;
        -- vbk
        ret(1).RELIABILITY_QOS              := BEST_EFFORT_RELIABILITY_QOS;
        ret(1).LIVELINESS_QOS               := AUTOMATIC_LIVELINESS_QOS;
        ret(1).DURABILITY_QOS               := VOLATILE_DURABILITY_QOS;
        ret(1).HEARTBEAT_RESPONSE_DELAY     := DURATION_ZERO;
        ret(1).HEARTBEAT_SUPPRESSION_DELAY  := DURATION_ZERO;
        ret(1).LEASE_DURATION               := DURATION_INFINITE;
        ret(1).WITH_KEY                     := TRUE;
        ret(1).MAX_PAYLOAD_SIZE             := 1;
        return ret;
    end function;
    constant TEST_CONFIG : CONFIG_ARRAY_TYPE := gen_test_config;
    
    -- *TYPE DECLARATION*
    type SEND_STAGE_TYPE is (IDLE, BUSY);
    type HC_STAGE_TYPE is (IDLE, DONE);
    type TEST_RAM_TYPE is array (0 to (MAX_REMOTE_ENDPOINTS*WRITER_ENDPOINT_FRAME_SIZE)-1) of std_logic_vector(WORD_WIDTH-1 downto 0);
    type EMPTY_HEAD_SIG_ARRAY_TYPE is array (0 to NUM_READERS-1) of natural;
    
    -- *SIGNAL DECLARATION*
    signal clk, rd_meta, last_word_in_meta : std_logic := '0';
    signal empty_user, empty_meta, w_map : std_logic_vector(0 to NUM_READERS-1) := (others => '0');
    signal reset : std_logic := '1';
    signal data_in_meta : std_logic_vector(WORD_WIDTH-1 downto 0) := (others => '0');
    signal data_out_hc : WORD_ARRAY_TYPE(0 to NUM_READERS-1) := (others => (others => '0'));
    signal start_hc, ack_hc, done_hc : std_logic_vector(0 to NUM_READERS-1) := (others => '0');
    signal opcode_hc : HISTORY_CACHE_OPCODE_ARRAY_TYPE(0 to NUM_READERS-1) := (others => NOP);
    signal ret_hc : HISTORY_CACHE_RESPONSE_ARRAY_TYPE(0 to NUM_READERS-1) := (others => OK);
    signal stim_stage : SEND_STAGE_TYPE := IDLE;
    signal stage_hc : HC_STAGE_TYPE := IDLE;
    shared variable stimulus, reference : TEST_PACKET_TYPE := EMPTY_TEST_PACKET;
    signal packet_sent : std_logic := '0';
    signal cnt_stim : natural := 0;
    signal start : std_logic := '0';
    shared variable SB_hc : osvvm.ScoreBoardPkg_slv.ScoreBoardPType;
    shared variable SB0_mem, SB1_mem : work.ScoreBoardPkg_MemoryTest.ScoreBoardPType;
    signal stim_done, mem_check_done, out_check_done, test_done : std_logic := '0';
    
    -- *FUNCTION DECLARATION*
    procedure wait_on_sig(signal sig : std_logic) is
    begin
        if (sig /= '1') then
            wait on sig until sig = '1';
        end if;
    end procedure;
    
begin

    -- Unit Under Test
    uut : entity work.rtps_reader(arch)
        generic map (
            NUM_READERS             => NUM_READERS,
            CONFIG_ARRAY            => to_QUARTUS_CONFIG_ARRAY_TYPE(TEST_CONFIG),
            ENTITYID                => (0 => x"61d32d07", 1 => x"3c1f1907"),
            MAX_REMOTE_ENDPOINTS    => MAX_REMOTE_ENDPOINTS
        )
        port map (
            -- SYSTEM
            clk                 => clk,
            reset               => reset,
            time                => TIME_ZERO,
            empty_user          => (others => '1'),
            rd_user             => open,
            data_in_user        => (others => '0'),
            last_word_in_user   => '0',
            empty_meta          => empty_meta or (empty_meta'range => packet_sent),
            rd_meta             => rd_meta,
            data_in_meta        => data_in_meta,
            last_word_in_meta   => last_word_in_meta,
            wr_ro               => open,
            full_ro             => '0',
            last_word_out_ro    => open,
            data_out_ro         => open,
            start_hc            => start_hc,
            opcode_hc           => opcode_hc,
            ack_hc              => ack_hc,
            done_hc             => done_hc,
            ret_hc              => ret_hc,
            data_out_hc         => data_out_hc,
            valid_out_hc        => open,
            ready_out_hc        => (others => '0'),
            last_word_out_hc    => open
        );
    
    stimulus_prc : process
        variable RV                         : RandomPType;
        variable p0, p1, participant        : PARTICIPANT_DATA_TYPE := DEFAULT_PARTICIPANT_DATA;
        variable e0, e1, e2, e3, endpoint   : ENDPOINT_DATA_TYPE := DEFAULT_ENDPOINT_DATA;
        
        alias empty_head is <<signal uut.empty_head_sig : EMPTY_HEAD_SIG_ARRAY_TYPE>>;
        
        -- Wrapper to use procedure as function
        impure function gen_rand_loc_2 return LOCATOR_TYPE is
            variable ret : LOCATOR_TYPE := EMPTY_LOCATOR;
        begin
            gen_rand_loc(RV, ret);
            return ret;
        end function;
        
        impure function gen_rand_guid_prefix return GUIDPREFIX_TYPE is
            variable ret : GUIDPREFIX_TYPE;
        begin
            ret := (0 => RV.RandSlv(WORD_WIDTH), 1 => RV.RandSlv(WORD_WIDTH), 2 => RV.RandSlv(WORD_WIDTH));
            return ret;
        end function;
        
        procedure push_remove(writer_id,i : natural) is
            variable t : std_logic_vector(0 to NUM_READERS-1) := (others => '0');
        begin
            t(i) := '1';
            SB_hc.Push(t);
            SB_hc.Push(std_logic_vector(to_unsigned(writer_id, WORD_WIDTH)));
        end procedure;
        
        procedure start_test is
        begin
            start <= '1';
            wait until rising_edge(clk);
            start <= '0';
            wait until rising_edge(clk);
        end procedure;
    begin
        
        SetAlertLogName("L0_rtps_reader_test1 - Metatraffic Handling");
        SetAlertEnable(FAILURE, TRUE);
        SetAlertEnable(ERROR, TRUE);
        SetAlertEnable(WARNING, TRUE);
        SetLogEnable(DEBUG, FALSE);
        SetLogEnable(PASSED, FALSE);
        SetLogEnable(INFO, TRUE);
        RV.InitSeed(RV'instance_name);
        SB_hc.SetAlertLogID(Name => "HC", ParentID => OSVVM_ALERTLOG_ID);
        SB0_mem.SetAlertLogID(Name => "MEMORY 0", ParentID => OSVVM_ALERTLOG_ID);
        SB1_mem.SetAlertLogID(Name => "MEMORY 1", ParentID => OSVVM_ALERTLOG_ID);
        
        p0.guidPrefix := gen_rand_guid_prefix;
        p1.guidPrefix := gen_rand_guid_prefix;
        
        -- Endpoint 0
        e0                      := DEFAULT_ENDPOINT_DATA;
        e0.reader               := FALSE;
        e0.participant          := p0;
        e0.entityid             := RV.RandSlv(ENTITYID_WIDTH);
        e0.unicastLocatorList   := (numLocators => int(1,CDR_LONG_WIDTH), locator => (0 => gen_rand_loc_2, others => EMPTY_LOCATOR));
        e0.reliability          := RELIABLE_RELIABILITY_QOS;
        -- Endpoint 1
        e1                      := DEFAULT_ENDPOINT_DATA;
        e1.reader               := FALSE;
        e1.participant          := p0;
        e1.entityid             := RV.RandSlv(ENTITYID_WIDTH);
        e1.unicastLocatorList   := (numLocators => int(1,CDR_LONG_WIDTH), locator => (0 => gen_rand_loc_2, others => EMPTY_LOCATOR));
        e1.lifespan             := gen_duration(1 sec);
        e1.reliability          := BEST_EFFORT_RELIABILITY_QOS;
        -- Endpoint 2
        e2                      := DEFAULT_ENDPOINT_DATA;
        e2.reader               := FALSE;
        e2.participant          := p1;
        e2.entityid             := RV.RandSlv(ENTITYID_WIDTH);
        e2.unicastLocatorList   := (numLocators => int(1,CDR_LONG_WIDTH), locator => (0 => gen_rand_loc_2, others => EMPTY_LOCATOR));
        e2.lifespan             := gen_duration(2 sec);
        e2.reliability          := BEST_EFFORT_RELIABILITY_QOS;
        -- Endpoint 3
        e3                      := DEFAULT_ENDPOINT_DATA;
        e3.reader               := FALSE;
        e3.participant          := p1;
        e3.entityid             := RV.RandSlv(ENTITYID_WIDTH);
        e3.unicastLocatorList   := (numLocators => int(1,CDR_LONG_WIDTH), locator => (0 => gen_rand_loc_2, others => EMPTY_LOCATOR));
        e3.lifespan             := gen_duration(3 sec);
        e3.reliability          := RELIABLE_RELIABILITY_QOS;
        
        Log("Initiating Test", INFO);
        stim_done   <= '0';
        start       <= '0';
        reset       <= '1';
        w_map       <= (others => '0');
        wait until rising_edge(clk);
        wait until rising_edge(clk);
        reset   <= '0';
        -- MEMORY 0 STATE -/0,17,34
        -- MEMORY 1 STATE -/0,17,34
        
        
        Log("Insert Endpoint 0 Participant 0 {READER 0}", INFO);
        endpoint        := e0;
        endpoint.nr     := 0;
        endpoint.match  := MATCH;
        gen_endpoint_match_frame(endpoint, stimulus);
        SB0_mem.Push(gen_writer_endpoint_mem_frame(endpoint));
        w_map   <= "10";
        start_test;
        wait_on_sig(packet_sent);
        stimulus            := EMPTY_TEST_PACKET;
        wait_on_sig(mem_check_done);
        AlertIf(empty_head(0) /= 17, "Memory 0 Empty List Head incorrect", FAILURE);
        AlertIf(empty_head(1) /= 0, "Memory 1 Empty List Head incorrect", FAILURE);
        -- MEMORY 0 STATE 0(P0E0)/17,34
        -- MEMORY 1 STATE -/0,17,34
        
        Log("Insert Endpoint 1 Participant 0 {READER 0, READER 1}", INFO);
        endpoint            := e1;
        endpoint.nr         := 1;
        endpoint.match      := MATCH;
        gen_endpoint_match_frame(endpoint, stimulus);
        SB0_mem.Push(gen_writer_endpoint_mem_frame(endpoint));
        endpoint.nr         := 0;
        SB1_mem.Push(gen_writer_endpoint_mem_frame(endpoint));
        w_map   <= "11";
        start_test;
        wait_on_sig(packet_sent);
        stimulus            := EMPTY_TEST_PACKET;
        wait_on_sig(mem_check_done);
        AlertIf(empty_head(0) /= 34, "Memory 0 Empty List Head incorrect", FAILURE);
        AlertIf(empty_head(1) /= 17, "Memory 1 Empty List Head incorrect", FAILURE);
        -- MEMORY 0 STATE 17(P0E1),0(P0E0)/34
        -- MEMORY 1 STATE 0(P0E1)/17,34
        
        Log("Insert Endpoint 2 Participant 1 [READER 0]", INFO);
        endpoint        := e2;
        endpoint.nr     := 2;
        endpoint.match  := MATCH;
        gen_endpoint_match_frame(endpoint, stimulus);
        SB0_mem.Push(gen_writer_endpoint_mem_frame(endpoint));
        w_map   <= "10";
        start_test;
        wait_on_sig(packet_sent);
        stimulus            := EMPTY_TEST_PACKET;
        wait_on_sig(mem_check_done);
        AlertIf(empty_head(0) /= 50, "Memory 0 Empty List Head incorrect", FAILURE);
        AlertIf(empty_head(1) /= 17, "Memory 1 Empty List Head incorrect", FAILURE);
        -- MEMORY 0 STATE 34(P1E2),17(P0E1),0(P0E0)/-
        -- MEMORY 1 STATE 0(P0E1)/17,34
        
        Log("Insert Endpoint 3 Participant 1 {READER 0, READER 1}", INFO);
        Log("READER 0: Ignore", DEBUG);
        endpoint        := e3;
        endpoint.nr     := 1;
        endpoint.match  := MATCH;
        gen_endpoint_match_frame(endpoint, stimulus);
        SB1_mem.Push(gen_writer_endpoint_mem_frame(endpoint));
        -- Re-check Mem-State
        endpoint        := e0;
        endpoint.nr     := 0;
        SB0_mem.Push(gen_writer_endpoint_mem_frame(endpoint));
        endpoint        := e1;
        endpoint.nr     := 1;
        SB0_mem.Push(gen_writer_endpoint_mem_frame(endpoint));
        endpoint.nr     := 0;
        SB1_mem.Push(gen_writer_endpoint_mem_frame(endpoint));
        endpoint        := e2;
        endpoint.nr     := 2;
        SB0_mem.Push(gen_writer_endpoint_mem_frame(endpoint));
        w_map   <= "11";
        start_test;
        wait_on_sig(packet_sent);
        stimulus            := EMPTY_TEST_PACKET;
        wait_on_sig(mem_check_done);
        AlertIf(empty_head(0) /= 50, "Memory 0 Empty List Head incorrect", FAILURE);
        AlertIf(empty_head(1) /= 34, "Memory 1 Empty List Head incorrect", FAILURE);
        -- MEMORY 0 STATE 34(P1E2),17(P0E1),0(P0E0)/-
        -- MEMORY 1 STATE 17(P1E3),0(P0E1)/34
        
        Log("Remove Endpoint 2 Participant 1 {READER 0, READER 1}", INFO);
        Log("READER 1: Ignore", DEBUG);
        endpoint        := e2;
        endpoint.nr     := 2;
        endpoint.match  := UNMATCH;
        gen_endpoint_match_frame(endpoint, stimulus);
        push_remove(2,0);
        w_map   <= "11";
        start_test;
        wait_on_sig(packet_sent);
        stimulus            := EMPTY_TEST_PACKET;
        wait_on_sig(mem_check_done);
        AlertIf(empty_head(0) /= 34, "Memory 0 Empty List Head incorrect", FAILURE);
        AlertIf(empty_head(1) /= 34, "Memory 1 Empty List Head incorrect", FAILURE);
        -- MEMORY 0 STATE 17(P0E1),0(P0E0)/34
        -- MEMORY 1 STATE 17(P1E3),0(P0E1)/34
        
        Log("Insert Endpoint 3 Participant 1 {READER 0 ,READER 1}", INFO);
        Log("READER 1: Ignore", DEBUG);
        endpoint        := e3;
        endpoint.nr     := 2;
        endpoint.match  := MATCH;
        gen_endpoint_match_frame(endpoint, stimulus);
        SB0_mem.Push(gen_writer_endpoint_mem_frame(endpoint));
        w_map   <= "11";
        start_test;
        wait_on_sig(packet_sent);
        stimulus            := EMPTY_TEST_PACKET;
        wait_on_sig(mem_check_done);
        AlertIf(empty_head(0) /= 50, "Memory 0 Empty List Head incorrect", FAILURE);
        AlertIf(empty_head(1) /= 34, "Memory 1 Empty List Head incorrect", FAILURE);
        -- MEMORY 0 STATE 34(P1E3),17(P0E1),0(P0E0)/-
        -- MEMORY 1 STATE 17(P1E3),0(P0E1)/34
        
        Log("Remove Participant 0 {READER 0, READER 1}", INFO);
        participant         := p0;
        participant.match   := UNMATCH;
        gen_participant_match_frame(participant, stimulus);
        push_remove(1,0);
        push_remove(0,0);
        push_remove(0,1);
        w_map   <= "11";
        start_test;
        wait_on_sig(packet_sent);
        stimulus            := EMPTY_TEST_PACKET;
        wait_on_sig(mem_check_done);
        AlertIf(empty_head(0) /= 0, "Memory 0 Empty List Head incorrect", FAILURE);
        AlertIf(empty_head(1) /= 0, "Memory 1 Empty List Head incorrect", FAILURE);
        -- MEMORY 0 STATE 34(P1E3)/0,17
        -- MEMORY 1 STATE 17(P1E3)/0,34
        
        Log("Insert Endpoint 2 Participant 1 {READER 0}", INFO);
        endpoint        := e2;
        endpoint.nr     := 0;
        endpoint.match  := MATCH;
        gen_endpoint_match_frame(endpoint, stimulus);
        SB0_mem.Push(gen_writer_endpoint_mem_frame(endpoint));
        w_map   <= "10";
        start_test;
        wait_on_sig(packet_sent);
        stimulus            := EMPTY_TEST_PACKET;
        wait_on_sig(mem_check_done);
        AlertIf(empty_head(0) /= 17, "Memory 0 Empty List Head incorrect", FAILURE);
        AlertIf(empty_head(1) /= 0, "Memory 1 Empty List Head incorrect", FAILURE);
        -- MEMORY 0 STATE 0(P1E2),34(P1E3)/17
        -- MEMORY 1 STATE 17(P1E3)/0,34
        
        Log("Unknown Metatraffic Operation followed by insertion of Enpoint 1 Participant 0 {READER 0, READER 1}", INFO);
        for i in 0 to 9 loop
            stimulus.data(i)    := RV.RandSlv(WORD_WIDTH);
        end loop;
        stimulus.last(9)    := '1';
        stimulus.length     := 10;
        endpoint        := e1;
        endpoint.nr     := 1;
        endpoint.match  := MATCH;
        gen_endpoint_match_frame(endpoint, stimulus);
        -- Re-check Mem-State
        endpoint        := e2;
        endpoint.nr     := 0;
        SB0_mem.Push(gen_writer_endpoint_mem_frame(endpoint));
        endpoint        := e1;
        endpoint.nr     := 1;
        SB0_mem.Push(gen_writer_endpoint_mem_frame(endpoint));
        endpoint.nr     := 0;
        SB1_mem.Push(gen_writer_endpoint_mem_frame(endpoint));
        endpoint        := e3;
        endpoint.nr     := 2;
        SB0_mem.Push(gen_writer_endpoint_mem_frame(endpoint));
        endpoint.nr     := 1;
        SB1_mem.Push(gen_writer_endpoint_mem_frame(endpoint));
        w_map   <= "11";
        start_test;
        wait_on_sig(packet_sent);
        stimulus            := EMPTY_TEST_PACKET;
        wait_on_sig(mem_check_done);
        AlertIf(empty_head(0) /= 50, "Memory 0 Empty List Head incorrect", FAILURE);
        AlertIf(empty_head(1) /= 34, "Memory 1 Empty List Head incorrect", FAILURE);
        -- MEMORY 0 STATE 17(P0E1),0(P1E2),34(P1E3)/-
        -- MEMORY 1 STATE 0(P0E1)17(P1E3)/34
        
        Log("Update Endpoint 3 Participant 1 {READER 0, READER 1}", INFO);
        endpoint        := e3;
        endpoint.match  := MATCH;
        endpoint.unicastLocatorList := (numLocators => int(1,CDR_LONG_WIDTH), locator => (0 => gen_rand_loc_2, others => EMPTY_LOCATOR));
        gen_endpoint_match_frame(endpoint, stimulus);
        endpoint.nr     := 2;
        SB0_mem.Push(gen_writer_endpoint_mem_frame(endpoint));
        endpoint.nr     := 1;
        SB1_mem.Push(gen_writer_endpoint_mem_frame(endpoint));
        w_map   <= "11";
        start_test;
        wait_on_sig(packet_sent);
        stimulus            := EMPTY_TEST_PACKET;
        wait_on_sig(mem_check_done);
        AlertIf(empty_head(0) /= 50, "Memory 0 Empty List Head incorrect", FAILURE);
        AlertIf(empty_head(1) /= 34, "Memory 1 Empty List Head incorrect", FAILURE);
        -- MEMORY 0 STATE 17(P0E1),0(P1E2),34(P1E3)/-
        -- MEMORY 1 STATE 0(P0E1)17(P1E3)/34
        
        stim_done   <= '1';
        wait_on_sig(test_done);
        TranscriptOpen(RESULTS_FILE, APPEND_MODE);
        SetTranscriptMirror;
        ReportAlerts;
        TranscriptClose;
        std.env.stop;
        wait;
    end process;
    
    clock_prc : process
    begin
        clk <= '0';
        wait for 25 ns;
        clk <= '1';
        wait for 25 ns;
    end process;
    
    in_empty_prc : process
    begin
        empty_meta  <= not w_map;
        wait until rising_edge(clk);
        empty_meta  <= (others => '1');
        wait until rising_edge(clk);
    end process;
    
    alert_prc : process(all)
    begin
        if rising_edge(clk) then
            alertif(empty_meta = (empty_meta'range => '1') and rd_meta = '1', "Input FIFO read signal high while empty signal high", FAILURE);
        end if;
    end process;
    
    input_prc : process(all)
    begin
        data_in_meta        <= stimulus.data(cnt_stim);
        last_word_in_meta   <= stimulus.last(cnt_stim);
        
        if rising_edge(clk) then
            if (reset = '1') then
                cnt_stim    <= 0;
                stim_stage  <= IDLE;
                packet_sent <= '1';
            else
                case (stim_stage) is
                    when IDLE =>
                        if (start = '1' and stimulus.length /= 0) then
                            stim_stage  <= BUSY;
                            packet_sent <= '0';
                        end if;
                    when BUSY =>
                        if (rd_meta = '1') then
                            if (cnt_stim = stimulus.length-1) then
                                stim_stage  <= IDLE;
                                packet_sent <= '1';
                                cnt_stim    <= 0;
                            else
                                cnt_stim    <= cnt_stim + 1;
                            end if;
                        end if;
                end case;
            end if;
        end if;
    end process;
    
    done_proc : process(clk)
    begin
        if rising_edge(clk) then
            if (stim_done = '1' and SB_hc.empty and SB0_mem.empty and SB1_mem.empty) then
                test_done   <= '1';
            else
                test_done   <= '0';
            end if;
        end if;
    end process;
    
    hc_prc : process (all)
        variable ind            : natural := 0;
        
        function one_hot_converter(input : std_logic_vector) return natural is
        begin
            for i in 0 to input'length-1 loop
                if (input(i) = '1') then
                    return i;
                end if;
            end loop;
            return 0; -- DEFAULT
        end function;
    begin
        if rising_edge(clk) then
            case (stage_hc) is
                when IDLE =>
                    if (start_hc /= (start_hc'range => '0')) then
                        alertif((signed(start_hc) and (- signed(start_hc))) = (start_hc'range => '0'), "start_hc not in one-hot encoding", FAILURE);
                        ind         := one_hot_converter(start_hc);
                        case (opcode_hc(ind)) is
                            when REMOVE_WRITER =>
                                SB_hc.check(start_hc);
                                SB_hc.check(data_out_hc(ind));
                                stage_hc    <= DONE;
                            when others =>
                                Alert("Unexpected HC Opcode", FAILURE);
                                stage_hc    <= DONE;
                        end case;
                    end if;
                when DONE =>
                    stage_hc    <= IDLE;
                when others =>
                    null;
            end case;
        end if;
        
        -- DEFAULT
        ack_hc          <= (others => '0');
        done_hc         <= (others => '0');
        ret_hc          <= (others => ERROR);
        
        case (stage_hc) is
            when IDLE =>
                if (start_hc /= (start_hc'range => '0')) then
                    -- HACK: We trigger all acks because we cannot use 'ind' variable in the same clock cycle
                    --       Since the uut only interfaces with 1 HC at a time (one-hot encoded start_hc) this
                    --       is still valid.
                    ack_hc  <= (others => '1');
                end if;
            when DONE =>
                done_hc(ind)    <= '1';
                ret_hc(ind)     <= OK;
            when others =>
                null;
        end case;
    end process;
    
    mem_check_prc : process
        alias mem0 is <<signal uut.mem_ctrl_gen(0).mem_ctrl_inst.ram_inst.mem : TEST_RAM_TYPE>>;
        alias mem1 is <<signal uut.mem_ctrl_gen(1).mem_ctrl_inst.ram_inst.mem : TEST_RAM_TYPE>>;
        alias mem_op_done is <<signal uut.mem_op_done : std_logic>>;
        alias idle_sig is <<signal uut.idle_sig : std_logic>>;
        variable reference : TEST_WRITER_ENDPOINT_MEMORY_FRAME_TYPE;
        
        -- NOTE: This procedure waits until the idle_sig is high for at least
        --       two consecutive clock cycles.
        procedure wait_on_idle is
            variable first : boolean := TRUE;
        begin
            loop
                if (idle_sig /= '1') then
                    wait until idle_sig = '1';
                elsif (not first) then
                    exit;
                end if;
                wait until rising_edge(clk);
                wait until rising_edge(clk);
                first := FALSE;
            end loop;
        end procedure;
    begin
        wait_on_sig(start);
        wait until falling_edge(packet_sent);
        mem_check_done  <= '0';
        -- Wait for Packet to be sent
        wait_on_sig(packet_sent);
        -- Wait for UUT IDLE state
        wait_on_idle;
        wait_on_sig(mem_op_done);
        -- MEM0
        while (not SB0_mem.empty) loop
            SB0_mem.Pop(reference);
            for i in 0 to reference'length-1 loop
                AffirmIf(?? (mem0(reference(i).addr) ?= reference(i).data), "Address: " & integer'image(reference(i).addr) & " Received: " & to_hstring(mem0(reference(i).addr)) & " Expected: " & to_hstring(reference(i).data));
            end loop;
        end loop;
        -- MEM1
        while (not SB1_mem.empty) loop
            SB1_mem.Pop(reference);
            for i in 0 to reference'length-1 loop
                AffirmIf(?? (mem1(reference(i).addr) ?= reference(i).data), "Address: " & integer'image(reference(i).addr) & " Received: " & to_hstring(mem1(reference(i).addr)) & " Expected: " & to_hstring(reference(i).data));
            end loop;
        end loop;
        -- Toggle High for one clock cycle
        mem_check_done  <= '1';
        wait until rising_edge(clk);
    end process;
    
    watchdog : process
    begin
        wait for 1 ms;
        Alert("Test timeout", FAILURE);
        std.env.stop;
    end process;
    
end architecture;