-- Sample the processor bus at the falling edge, after rising-edge updates have settled.
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
use std.env.all;
use std.textio.all;

entity trace_io is
end;
architecture bench of trace_io is
    signal clk : std_logic := '0';
    signal key : std_logic_vector(3 downto 0) := "1110";
    signal sw : std_logic_vector(9 downto 0) := (others=>'0');
    signal lamps : std_logic_vector(9 downto 0);
begin
    clk <= not clk after 1 ns;
    dut : entity work.io_cpu port map(clk,key,sw,lamps);
    process
        alias ir is << signal .trace_io.dut.core.ir : std_logic_vector(15 downto 0) >>;
        alias addr is << signal .trace_io.dut.address : std_logic_vector(15 downto 0) >>;
        alias din is << signal .trace_io.dut.read_data : std_logic_vector(15 downto 0) >>;
        alias dout is << signal .trace_io.dut.write_data : std_logic_vector(15 downto 0) >>;
        alias w is << signal .trace_io.dut.write_enable : std_logic >>;
        alias bus_data is << signal .trace_io.dut.core.buswires : std_logic_vector(15 downto 0) >>;
        alias r0 is << signal .trace_io.dut.core.r0 : std_logic_vector(15 downto 0) >>;
        alias r1 is << signal .trace_io.dut.core.r1 : std_logic_vector(15 downto 0) >>;
        variable row : line;
    begin
        for j in 1 to 3 loop wait until falling_edge(clk); end loop;
        key<="1111"; sw<=std_logic_vector(to_unsigned(16#235#,10));
        write(row, string'("edge IR   ADDR DIN  DOUT W BUS  R0   R1")); writeline(output,row);
        for i in 1 to 48 loop
            wait until falling_edge(clk);
            if ir=x"8004" or ir=x"A005" or ir=x"8205" then
                write(row, integer'image(i) & " " & to_hstring(ir) & " " & to_hstring(addr)
                      & " " & to_hstring(din) & " " & to_hstring(dout) & " " & to_string(w)
                      & " " & to_hstring(bus_data) & " " & to_hstring(r0) & " " & to_hstring(r1));
                writeline(output,row);
            end if;
        end loop;
        finish;
    end process;
end architecture;
