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

entity test_paced is end;
architecture bench of test_paced is
    signal clk : std_logic := '0';
    signal key : std_logic_vector(3 downto 0) := "1110";
    signal switches, lamps : std_logic_vector(9 downto 0) := (others=>'0');
begin
    clk <= not clk after 1 ns;
    dut : entity work.paced_cpu generic map(ISSUE_BITS=>3)
        port map(clk,key,switches,lamps,open,open,open,open,open,open);
    process
        variable fast, slow, first : time;
        variable expected_cycles, measured_cycles : natural;
        variable saved : std_logic_vector(9 downto 0);
        procedure advance(n : positive) is
        begin for j in 1 to n loop wait until falling_edge(clk); end loop; end procedure;
        procedure wait_count(value : natural) is
        begin
            wait until unsigned(lamps)=value for 1000 us;
            assert unsigned(lamps)=value report "FAIL counter timeout " & integer'image(value) severity failure;
        end procedure;
    begin
        advance(5); key<="1111"; switches<=std_logic_vector(to_unsigned(512,10));
        wait_count(1); first:=now; wait_count(2); fast:=now-first;
        switches<=(others=>'0'); advance(64); saved:=lamps; wait for 2 * fast;
        assert lamps=saved report "FAIL held count" severity failure;
        switches<=std_logic_vector(to_unsigned(519,10));
        wait_count(3); first:=now; wait_count(4); slow:=now-first;
        report "Measured fast " & integer'image(fast / (2 ns)) & " and slow "
            & integer'image(slow / (2 ns)) & " clock cycles";
        assert slow>=fast*7 and slow<=fast*8 report "FAIL switch-dependent periods" severity failure;
        assert fast = 8264 * (2 ns) and slow = 65776 * (2 ns)
            report "FAIL absolute periods: check the inner-loop count and the instruction divider" severity failure;
        for setting in 1 to 6 loop
            key <= "1110"; switches <= std_logic_vector(to_unsigned(setting, 10)); advance(10);
            key <= "1111"; switches <= std_logic_vector(to_unsigned(512 + setting, 10));
            wait_count(1); first := now;
            wait_count(2); measured_cycles := (now - first) / (2 ns);
            -- Six fixed instructions and 1,027 per outer pass, eight clocks each.
            expected_cycles := 8 * (6 + 1027 * (setting + 1));
            assert measured_cycles = expected_cycles
                report "FAIL intermediate setting " & integer'image(setting) & ": expected "
                    & integer'image(expected_cycles) & " cycles, measured " & integer'image(measured_cycles)
                severity failure;
        end loop;
        key<="1110"; advance(10);
        assert unsigned(lamps)=0 report "FAIL reset" severity failure;
        report "PASS fast " & integer'image(fast / (2 ns)) & " slow " & integer'image(slow / (2 ns))
            & " cycles; all eight settings, halt and reset"; finish;
    end process;
end architecture;
