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

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

architecture rtl of array_product is
    type sums_t is array (0 to 4) of unsigned(7 downto 0);
    signal subtotal : sums_t;
    signal a, b : 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
    a <= unsigned(SW(7 downto 4));
    b <= unsigned(SW(3 downto 0));
    subtotal(0) <= (others => '0');

    rows : for row in 0 to 3 generate
        signal masked : unsigned(3 downto 0);
        signal partial : unsigned(7 downto 0);
        signal carry : std_logic_vector(8 downto 0);
    begin
        masked <= a when b(row) = '1' else (others => '0');
        partial <= resize(masked, 8); -- TODO: align this partial product with its binary column.
        carry(0) <= '0';
        cells : for col in 0 to 7 generate
            signal propagate : std_logic;
        begin
            propagate <= subtotal(row)(col) xor partial(col);
            subtotal(row+1)(col) <= propagate xor carry(col);
            carry(col+1) <= (subtotal(row)(col) and partial(col)) or (propagate and carry(col));
        end generate;
    end generate;

    HEX5 <= segments(subtotal(4)(7 downto 4));
    HEX4 <= segments(subtotal(4)(3 downto 0));
    HEX3 <= (others => '1');
    HEX2 <= segments(a);
    HEX1 <= (others => '1');
    HEX0 <= segments(b);
end architecture;
