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

entity decimal_stage is
    port (clk, reset, load : in std_logic;
          preset : in unsigned(3 downto 0);
          enable : in std_logic;
          at_nine : out std_logic;
          segments : out std_logic_vector(6 downto 0));
end entity;
architecture rtl of decimal_stage is
    signal digit : unsigned(3 downto 0);
begin
    at_nine <= '1' when digit = 9 else '0';
    process(clk)
    begin
        if rising_edge(clk) then
            if reset = '1' then digit <= (others => '0');
            elsif load = '1' then digit <= preset;
            elsif enable = '1' then
                if digit = 9 then digit <= (others => '0');
                else digit <= digit + 1;
                end if;
            end if;
        end if;
    end process;
    with to_integer(digit) select segments <=
        "1000000" when 0,
        "1111001" when 1,
        "0100100" when 2,
        "0110000" when 3,
        "0011001" when 4,
        "0010010" when 5,
        "0000010" when 6,
        "1111000" when 7,
        "0000000" when 8,
        "0010000" when 9,
        "1111111" when others;
end architecture;

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

entity cascade_bcd is
    generic (CYCLES_PER_SECOND : positive := 50000000);
    port (CLOCK_50 : in std_logic;
          SW : in std_logic_vector(9 downto 0);
          KEY : in std_logic_vector(3 downto 0);
          HEX2, HEX1, HEX0 : out std_logic_vector(6 downto 0));
end entity;
architecture rtl of cascade_bcd is
    signal meta, controls : std_logic_vector(2 downto 0);
    signal divider : unsigned(25 downto 0);
    signal reset, load, tick, units_nine, tens_nine, tens_enable, hundreds_enable : std_logic;
    signal hundreds_preset : unsigned(3 downto 0);
begin
    reset <= controls(0);
    load <= controls(1) or controls(2);
    hundreds_preset <= "1001" when controls(2) = '1' else "0000";
    tick <= '1' when divider = CYCLES_PER_SECOND - 1 else '0';
    process(CLOCK_50)
    begin
        if rising_edge(CLOCK_50) then
            meta <= SW(9 downto 8) & not KEY(0);
            controls <= meta;
            if reset = '1' or load = '1' or tick = '1' then
                divider <= (others => '0');
            else
                divider <= divider + 1;
            end if;
        end if;
    end process;
    -- TODO: use the lower digits and tick to control each enable.
    tens_enable <= '0';
    hundreds_enable <= '0';
    ones_stage : entity work.decimal_stage port map(CLOCK_50, reset, load, "1000", tick, units_nine, HEX0);
    tens : entity work.decimal_stage port map(CLOCK_50, reset, load, "1001", tens_enable, tens_nine, HEX1);
    hundreds : entity work.decimal_stage port map(CLOCK_50, reset, load, hundreds_preset, hundreds_enable, open, HEX2);
end architecture;
