library ieee;
use ieee.std_logic_1164.all;

entity bcd_gates_segment is
    port (x : in std_logic_vector(3 downto 0);
          pins : out std_logic_vector(6 downto 0));
end entity;

architecture rtl of bcd_gates_segment is
begin
    pins(0) <= (not x(0) and not x(1) and x(2)) or (x(0) and not x(1) and not x(2) and not x(3));
    pins(1) <= (not x(0) and x(1) and x(2)) or (x(0) and not x(1) and x(2));
    pins(2) <= (not x(0) and x(1) and not x(2));
    pins(3) <= (not x(0) and not x(1) and x(2)) or (x(0) and not x(1) and not x(2) and not x(3)) or (x(0) and x(1) and x(2));
    pins(4) <= (not x(1) and x(2)) or x(0);
    pins(5) <= (x(1) and not x(2)) or (x(0) and not x(2) and not x(3)) or (x(0) and x(1));
    pins(6) <= (not x(1) and not x(2) and not x(3)) or (x(0) and x(1) and x(2));
end architecture;

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

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

architecture rtl of bcd_gates is
    signal x, y, ones_digit, tens_digit : std_logic_vector(3 downto 0);
    signal invalid, correction : std_logic;
    signal raw : std_logic_vector(3 downto 0);
    signal carry : std_logic_vector(4 downto 0);
    signal carry2, carry3 : std_logic;
begin
    x <= SW(7 downto 4);
    y <= SW(3 downto 0);
    invalid <= (x(3) and (x(2) or x(1))) or (y(3) and (y(2) or y(1)));
    tens_digit <= "000" & correction;
    carry(0) <= SW(8);
    binary_columns : for i in 0 to 3 generate
        raw(i) <= x(i) xor y(i) xor carry(i);
        carry(i+1) <= (x(i) and y(i)) or ((x(i) xor y(i)) and carry(i));
    end generate;
    LEDR <= invalid & "0000" & carry(4) & raw;
    -- Implement decimal carry and correction using Boolean gates.
    correction <= '0';
    ones_digit <= raw;
    show_hex5 : entity work.bcd_gates_segment port map (x, HEX5);
    show_hex3 : entity work.bcd_gates_segment port map (y, HEX3);
    show_hex1 : entity work.bcd_gates_segment port map (tens_digit, HEX1);
    show_hex0 : entity work.bcd_gates_segment port map (ones_digit, HEX0);
end architecture;
