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

entity stored_sum is
    port (
        SW : in std_logic_vector(9 downto 0);
        KEY : in std_logic_vector(3 downto 0);
        LEDR : out std_logic_vector(9 downto 0);
        HEX5, HEX4, HEX3, HEX2, HEX1, HEX0 : out std_logic_vector(6 downto 0)
    );
end entity;

architecture rtl of stored_sum is
    signal stored : unsigned(7 downto 0);
    signal total : unsigned(8 downto 0);
    function segments(nibble : unsigned(3 downto 0)) return std_logic_vector is
    begin
        case to_integer(nibble) is
            when 0 => return "1000000";
            when 1 => return "1111001";
            when 2 => return "0100100";
            when 3 => return "0110000";
            when 4 => return "0011001";
            when 5 => return "0010010";
            when 6 => return "0000010";
            when 7 => return "1111000";
            when 8 => return "0000000";
            when 9 => return "0010000";
            when 10 => return "0001000";
            when 11 => return "0000011";
            when 12 => return "1000110";
            when 13 => return "0100001";
            when 14 => return "0000110";
            when 15 => return "0001110";
            when others => return "1111111";
        end case;
    end function;
begin
    process (KEY(1), KEY(0))
    begin
        if KEY(0) = '0' then
            stored <= (others => '0');
        elsif rising_edge(KEY(1)) then
            stored <= (others => '0'); -- TODO: capture the first operand
        end if;
    end process;
    total <= resize(stored, 9) + resize(unsigned(SW(7 downto 0)), 9);
    LEDR <= (0 => total(8), others => '0');
    HEX0 <= segments(unsigned(SW(3 downto 0)));
    HEX1 <= segments(unsigned(SW(7 downto 4)));
    HEX2 <= segments(stored(3 downto 0));
    HEX3 <= segments(stored(7 downto 4));
    HEX4 <= segments(total(3 downto 0));
    HEX5 <= segments(total(7 downto 4));
end architecture;
