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

entity inferred_ram is
    port (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 inferred_ram is
    type words is array (0 to 31) of unsigned(3 downto 0);
    signal memory : words;
    signal address : unsigned(4 downto 0);
    signal read_data : unsigned(3 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
    address <= unsigned(SW(8 downto 4));
    process(KEY)
    begin
        if rising_edge(KEY(0)) then
            if SW(9) = '1' then memory(to_integer(address)) <= unsigned(SW(3 downto 0));
            else read_data <= memory(to_integer(address(3 downto 0))); -- TODO: inspect the upper half.
            end if;
        end if;
    end process;
    HEX5 <= segments(resize(address(4 downto 4), 4));
    HEX4 <= segments(address(3 downto 0));
    HEX3 <= "1111111";
    HEX2 <= segments(unsigned(SW(3 downto 0)));
    HEX1 <= "1111111";
    HEX0 <= segments(read_data);
end architecture;
