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

entity signed_accumulator 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 signed_accumulator is
    signal operand, total, rhs : unsigned(7 downto 0);
    signal result : unsigned(8 downto 0);
    signal carry, overflow, next_overflow : std_logic;
    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
    rhs <= operand;
    result <= resize(total, 9) + resize(rhs, 9);
    next_overflow <= (not (total(7) xor rhs(7))) and (result(7) xor total(7));
    process (KEY(1), KEY(0))
    begin
        if KEY(0) = '0' then
            operand <= (others => '0');
            total <= (others => '0');
            carry <= '0';
            overflow <= '0';
        elsif rising_edge(KEY(1)) then
            operand <= unsigned(SW(7 downto 0));
            total <= result(7 downto 0);
            carry <= result(8);
            overflow <= result(8); -- TODO: distinguish signed overflow from unsigned carry.
        end if;
    end process;
    LEDR <= overflow & carry & std_logic_vector(result(7 downto 0));
    HEX3 <= segments(operand(7 downto 4));
    HEX2 <= segments(operand(3 downto 0));
    HEX1 <= segments(total(7 downto 4));
    HEX0 <= segments(total(3 downto 0));
end architecture;
