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

entity hundredth_clock is
    generic (TICKS : positive := 500000);
    port (CLOCK_50 : in std_logic;
          SW : in std_logic_vector(9 downto 0);
          KEY : in std_logic_vector(3 downto 0);
          HEX5, HEX4, HEX3, HEX2, HEX1, HEX0 : out std_logic_vector(6 downto 0));
end entity;

architecture rtl of hundredth_clock is
    type digits_type is array(0 to 5) of natural range 0 to 9;
    constant terminal : digits_type := (9, 9, 9, 9, 9, 5);
    signal digits : digits_type := (others => 0);
    signal divider : natural range 0 to TICKS-1 := 0;
    signal meta, keys, previous : std_logic_vector(1 downto 0) := "11";
    type segment_table is array(0 to 9) of std_logic_vector(6 downto 0);
    constant segments : segment_table := ("1000000", "1111001", "0100100", "0110000", "0011001", "0010010", "0000010", "1111000", "0000000", "0010000");
begin
    process(CLOCK_50)
        variable carry : boolean;
    begin
        if rising_edge(CLOCK_50) then
            meta <= KEY(1 downto 0);
            keys <= meta;
            previous <= keys;
            if previous(1) = '1' and keys(1) = '0' and
                    unsigned(SW(7 downto 4)) < 6 and unsigned(SW(3 downto 0)) < 10 then
                digits(5) <= to_integer(unsigned(SW(7 downto 4)));
                digits(4) <= to_integer(unsigned(SW(3 downto 0)));
                if SW(9) = '1' then
                    digits(0 to 3) <= (8, 9, 9, 5);
                    divider <= 0;
                end if;
            elsif keys(0) = '1' and SW(8) = '0' then
                if divider = TICKS-1 then
                    divider <= 0;
                    carry := true;
                    for n in digits'range loop
                        if carry then
                            carry := digits(n) = terminal(n);
                            if carry then digits(n) <= 0;
                            else digits(n) <= digits(n) + 1; end if;
                        end if;
                    end loop;
                else divider <= divider + 1; end if;
            end if;
        end if;
    end process;
    HEX0 <= segments(digits(0));
    HEX1 <= segments(digits(1));
    HEX2 <= segments(digits(2));
    HEX3 <= segments(digits(3));
    HEX4 <= segments(digits(4));
    HEX5 <= segments(digits(5));
end architecture;
