library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

--  Uncomment the following lines to use the declarations that are
--  provided for instantiating Xilinx primitive components.
--library UNISIM;
--use UNISIM.VComponents.all;

entity main_top is
    Port ( clk  : in std_logic;
	        resn : in std_logic; 
	        a : in std_logic_vector(31 downto 0);
           d : inout std_logic_vector(31 downto 0);
           wen : in std_logic;
           csn : in std_logic);
end main_top;

architecture Behavioral of main_top is

type t_reg is array (31 downto 0) of std_logic ;
signal reg_a, reg_b, reg_c : t_reg;
signal cs_a, cs_b, cs_c, CI, CO : std_logic;
signal dmuxo : std_logic_vector(31 downto 0);
signal mux_ctrl : std_logic_vector (3 downto 0);
signal AA,BB,S31: std_logic_vector(32-1 downto 0);
signal sum : std_logic_vector(32 downto 0);
signal zeros: std_logic_vector(32-1 downto 0) := (others => '0');

begin

mux_ctrl <= a(7 downto 4);

dmuxo <= std_logic_vector(reg_a) when (mux_ctrl = X"0") else
         std_logic_vector(reg_b) when (mux_ctrl = X"1") else
			std_logic_vector(reg_c) when (mux_ctrl = X"2") else
			X"12345678";

cs_a <= '1' when (mux_ctrl = X"0" and csn = '0') else '0';
cs_b <= '1' when (mux_ctrl = X"1" and csn = '0') else '0';
cs_c <= '1' when (mux_ctrl = X"2" and csn = '0') else '0';

CI <= wen;
AA <= dmuxo when (wen = '1' and csn = '0') else (31 downto 0 => 'Z');
BB <=a;
d <= S31;

write_reg_a: process (clk, wen, cs_a, d)
begin
  
  if clk'event and clk = '0' then
    if (wen = '0' and cs_a = '1') then
      reg_a <= t_reg(d);
    end if;
  end if;
end process;

write_reg_b: process (clk, wen, cs_b, d)
begin
  
  if clk'event and clk = '0' then
    if (wen = '0' and cs_b = '1') then
      reg_b <= t_reg(d);
    end if;
  end if;
end process;

write_reg_c: process (clk, wen, cs_c, d)
begin
  
  if clk'event and clk = '0' then
    if (wen = '0' and cs_c = '1') then
      reg_c <= t_reg(d);
    end if;
  end if;
end process;

process (CI, AA, BB, sum)
begin
	sum <= ('0' & AA) + ('0' & BB) + (zeros & CI);
	S31 <= sum(32-1 downto 0);
	CO <= sum(32);

end process;
end Behavioral;
