library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use ieee.numeric_std.all;

entity regfile is
    Port ( outregna: in std_logic_vector(3 downto 0);
           outregda: out std_logic_vector(15 downto 0);
           
           outregnb: in std_logic_vector(3 downto 0);
           outregdb: out std_logic_vector(15 downto 0);
           
           inregn: in std_logic_vector(3 downto 0);
           inregd: in std_logic_vector(15 downto 0);
           inwe: in std_logic;
           
           rst : in STD_LOGIC;
           clk : in STD_LOGIC
           );
end regfile;

architecture Behavioral of regfile is
  component reg is
    Port ( d : in STD_LOGIC_VECTOR (15 downto 0);
           q : out STD_LOGIC_VECTOR (15 downto 0);
           rst : in STD_LOGIC;
           clk : in STD_LOGIC);
  end component;
  
  type regbank is array(0 to 15) of std_logic_vector(15 downto 0);
  signal regd: regbank;
  signal regq: regbank;
begin

  regs:
  for i in 0 to 15 generate
    regx: reg port map(d => regd(i), q => regq(i), rst => rst, clk => clk);
  end generate;
  
  outregda <= regq(to_integer(unsigned(outregna)));
  outregdb <= regq(to_integer(unsigned(outregnb)));
  
  process(inregn, inregd, regq, inwe)
  begin
    for i in 0 to 15 loop
      regd(i) <= regq(i);
      if inwe = '1' then
        regd(to_integer(unsigned(inregn))) <= inregd;
      end if;
    end loop;
  end process;  

end Behavioral;
