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

entity test_program is generic(mode : integer := -1); end;
architecture bench of test_program is
    type digits_t is array(0 to 5) of std_logic_vector(6 downto 0);
    type integers_t is array(0 to 15) of natural;
    constant glyphs : integers_t := (63,6,91,79,102,109,125,7,127,103,119,124,57,94,121,113);
    signal clk : std_logic := '0';
    signal key : std_logic_vector(3 downto 0) := "1110";
    signal sw, leds : std_logic_vector(9 downto 0) := (others=>'0');
    signal h : digits_t;
begin
    clk <= not clk after 1 ns;
    dut : entity work.stack_cpu port map(clk,key,sw,leds,h(0),h(1),h(2),h(3),h(4),h(5));
    process
        variable word : unsigned(15 downto 0);
        -- Allow the program to write all four digits before recording the word.
        procedure observe_word(wanted : unsigned(15 downto 0); step : natural) is
            variable expected : digits_t := (others=>(others=>'1'));
            variable stable : natural := 0;
        begin
            for i in 0 to 3 loop
                expected(i):=not std_logic_vector(to_unsigned(glyphs(to_integer(wanted(4*i+3 downto 4*i))),7));
            end loop;
            for cycle in 1 to 100000 loop
                wait until falling_edge(clk);
                if h=expected then stable:=stable+1; else stable:=0; end if;
                exit when stable=256;
            end loop;
            assert stable=256 and (step=0 or leds=sw)
                report "FAIL cumulative mode " & integer'image(mode) & " step " & integer'image(step) &
                       " expected " & to_hstring(wanted) & ", LED pins " & to_hstring(leds) severity failure;
            report "step " & integer'image(step) & ": " & to_hstring(wanted);
        end procedure;
    begin
        for i in 1 to 5 loop wait until falling_edge(clk); end loop;
        key<="1111";
        if mode=-1 then
            sw<=std_logic_vector(to_unsigned(512,10));
            for i in 1 to 1800 loop wait until falling_edge(clk); end loop;
            assert unsigned(leds)=85 report "FAIL stack, shifts or carry" severity failure;
        else
            assert mode>=0 and mode<=3 report "Choose mode 0 through 3" severity failure;
            sw<=std_logic_vector(to_unsigned(513+32*mode,10));
            word:=x"9010";
            observe_word(word,0);
            for step in 1 to 5 loop
                case mode is
                    when 0 => word:=shift_left(word,1);
                    when 1 => word:=shift_right(word,1);
                    when 2 => word:=unsigned(shift_right(signed(word),1));
                    when others => word:=rotate_right(word,1);
                end case;
                observe_word(word,step);
            end loop;
        end if;
        report "PASS assembly program"; finish;
    end process;
end architecture;
