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

entity tree_product 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);
        HEX3, HEX2, HEX1, HEX0 : out std_logic_vector(6 downto 0)
    );
end entity;

architecture rtl of tree_product is
    signal operand_a, operand_b : unsigned(7 downto 0);
    signal product, result : unsigned(15 downto 0);
    type words is array (natural range <>) of unsigned(15 downto 0);
    signal partial : words(0 to 7);
    signal pairs : words(0 to 3);
    signal lower, upper : unsigned(15 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
    partials : for row in 0 to 7 generate
        partial(row) <= shift_left(resize(operand_a, 16), row)
                        when operand_b(row) = '1' else (others => '0');
    end generate;
    combine : for row in 0 to 3 generate
        pairs(row) <= partial(2 * row) + partial(2 * row + 1);
    end generate;
    lower <= pairs(0) + pairs(1);
    upper <= pairs(2) + pairs(3);
    result <= lower + lower; -- TODO: include the four high partial products.

    process (KEY(1))
    begin
        if rising_edge(KEY(1)) then
            if KEY(0) = '0' then
                operand_a <= (others => '0');
                operand_b <= (others => '0');
                product <= (others => '0');
            else
                if SW(9) = '1' then operand_a <= unsigned(SW(7 downto 0)); end if;
                if SW(8) = '1' then operand_b <= unsigned(SW(7 downto 0)); end if;
                product <= result;
            end if;
        end if;
    end process;
    LEDR <= "00" & std_logic_vector(operand_a) when SW(9) = '1' else
            "00" & std_logic_vector(operand_b) when SW(8) = '1' else (others => '0');
    HEX3 <= segments(product(15 downto 12));
    HEX2 <= segments(product(11 downto 8));
    HEX1 <= segments(product(7 downto 4));
    HEX0 <= segments(product(3 downto 0));
end architecture;
