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

-- Aligned IO only.
-- Unaligned addra bits are ignored.
-- E.g. on a 16-bit bus, last addra bit is ignored.
entity ram is
  generic
  (
    addressWidth : in positive := 16;
    busWidth : in positive := 16;
    size : in positive := 1024
  );
  port
  (
    clk : in std_logic;

  -- port A
    addra : in std_logic_vector(addressWidth - 1 downto 0);
    wea : in std_logic;
    dina : in std_logic_vector(busWidth - 1 downto 0);
    douta : out std_logic_vector(busWidth - 1 downto 0);

  -- port B (read only)
    addrb : in std_logic_vector(addressWidth - 1 downto 0);
    doutb : out std_logic_vector(busWidth - 1 downto 0)
  );
end ram;

architecture Behavioral of ram is
  constant alignment : positive := busWidth / 8;
  constant ramSize : positive := size / alignment;

  type ramType is array(natural range <>) of std_logic_vector(busWidth - 1 downto 0);
  subtype ramRange is natural range 0 to ramSize;

  signal mem : ramType(ramRange);
begin
  process(clk)
    variable indexa, indexb : ramRange;
  begin
    if (rising_edge(clk))
    then
      indexa := to_integer(unsigned(addra)) / alignment;
      indexb := to_integer(unsigned(addrb)) / alignment;

      if (wea = '1')
      then
        mem(indexa) <= dina;
      end if;

      douta <= mem(indexa);
      doutb <= mem(indexb);
    end if;
  end process;
end Behavioral;
