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

library ip;
use ip.wishbone_package.all;
use ip.all;

entity sram_wb is
	port(
		clk    : in  std_logic;
		rst    : in  std_logic;

		-- Wishbone
		wb_in  : in  wishbone_v3_slave_in;
		wb_out : out wishbone_v3_slave_out
	);
end entity sram_wb;

architecture RTL of sram_wb is
	signal ram_address : std_logic_vector(10 DOWNTO 0);
	signal ram_byteena : std_logic_vector(3 DOWNTO 0);
	signal ram_dIn     : std_logic_vector(31 DOWNTO 0);
	signal ram_we      : std_logic;
	signal ram_dOut    : std_logic_vector(31 DOWNTO 0);
	signal ackRead     : std_logic;
begin
	ram0_inst : entity ip.ram0
		port map(
			address => ram_address,
			byteena => ram_byteena,
			clock   => clk,
			data    => ram_dIn,
			wren    => ram_we,
			q       => ram_dOut
		);

	sram_p : process(clk, rst) is
	begin
		if rst = '1' then
			ackRead <= '0';
		elsif rising_edge(clk) then
			ackRead <= '0';
			if wb_in.CYC = '1' and wb_in.STB = '1' and wb_in.WE = '0' then
				ackRead <= '1';
			end if;
		end if;
	end process sram_p;

	ram_address <= wb_in.ADR(12 downto 2);
	ram_we      <= wb_in.WE and wb_in.CYC and wb_in.STB;
	wb_out.ACK  <= (wb_in.WE or ackRead) and wb_in.CYC and wb_in.STB;
	wb_out.ERR  <= '0';
	wb_out.RTY  <= '0';
	wb_out.DAT  <= ram_dOut;

	ram_dIn     <= wb_in.DAT;
	ram_byteena <= wb_in.SEL;

end architecture RTL;
