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

entity test_clock is end entity;
architecture bench of test_clock is
    signal clk : std_logic := '0';
    signal keys : std_logic_vector(3 downto 0) := "1111";
    signal sw : std_logic_vector(9 downto 0) := (others => '0');
    type outputs is array(0 to 5) of std_logic_vector(6 downto 0);
    signal h : outputs;
    type codes is array(0 to 9) of natural;
    constant pattern : codes := (64,121,36,48,25,18,2,120,0,16);
begin
    clk <= not clk after 1 ns;
    dut : entity work.hundredth_clock generic map(4) port map(clk,sw,keys,h(5),h(4),h(3),h(2),h(1),h(0));
    process
        procedure cycles(n : positive) is
        begin
            for i in 1 to n loop wait until falling_edge(clk); end loop;
        end procedure;
        procedure check(m, s, cs : natural) is
            type values is array (0 to 5) of natural;
            constant digits : values := (cs mod 10,cs/10,s mod 10,s/10,m mod 10,m/10);
        begin
            for i in digits'range loop
                assert unsigned(h(i)) = pattern(digits(i)) report "FAIL at digit " & integer'image(i) severity failure;
            end loop;
        end procedure;
        procedure load(word : natural) is
        begin
            sw <= std_logic_vector(to_unsigned(word,10)); cycles(5);
            keys(1)<='0'; cycles(6); keys(1)<='1'; cycles(6);
        end procedure;
    begin
        sw <= std_logic_vector(to_unsigned(16#359#,10)); cycles(8); load(16#359#); check(59,59,98);
        load(16#142#); check(42,59,98);
        load(16#162#); check(42,59,98);
        load(16#14a#); check(42,59,98);
        load(16#359#); check(59,59,98);
        sw(9 downto 8) <= "00"; cycles(4); check(59,59,99); cycles(4); check(0,0,0);
        for step in 1 to 6205 loop cycles(4); check(step/6000,(step/100) mod 60,step mod 100); end loop;
        keys(0)<='0'; cycles(8); check(1,2,5); cycles(50); check(1,2,5);
        keys(0)<='1'; cycles(8); check(1,2,7);
        sw(8) <= '1'; cycles(48); check(1,2,7);
        sw(8) <= '0'; cycles(8); check(1,2,9);
        report "PASS minute preset, invalid input, 59:59.99 wrap, 6205 ticks, pause and resume";
        finish;
    end process;
end architecture;
