-------------------------------------------------------------------------
-- Project: JCPU, a portable 8-bit RISC CPU written in VHDL
-- This file: The ROM file for use in your VHDL design
--
-- Copyright (C) 2007 J. Ahrensfeld
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program.  If not, see <http://www.gnu.org/licenses/>.
--
-- For questions and ideas, please contact the author at jens@jayfield.org
--
--------------------------------------------------------------------------

LIBRARY ieee;
use IEEE.STD_LOGIC_1164.ALL;
USE ieee.numeric_std.ALL;


ENTITY ram IS
	Generic 
	(
		word_addr_width 	: integer := 6
	);
	Port 
	(
		clk			: in  STD_LOGIC;
		ce			: in  STD_LOGIC;
		we			: in  unsigned(3 downto 0);
		addr		: in  unsigned(31 downto 0);
		din			: in  unsigned(31 downto 0);
		dout		: out unsigned(31 downto 0)
	);
END ram;

ARCHITECTURE behavior OF ram IS 

	constant depth : natural := 2**word_addr_width;
	
	type sram_t is array (0 to depth-1) of unsigned(31 downto 0);

	function sram_clear return sram_t is

	variable result : sram_t;
	begin
		for i in 0 to sram_t'length-1 loop
			result(i) := (others => '0');
		end loop;
		return result;
	end sram_clear;

	signal sram : sram_t := sram_clear;
	
BEGIN


SRAM_RW:
	process(clk)
	variable index : natural range 0 to depth-1;
	begin
		if rising_edge(clk) and ce = '1' then
			index := to_integer(addr(word_addr_width+1 downto 2));
			if we(0) = '1' then
				sram(index)(7 downto 0)		<= din(7 downto 0);
			end if;	
			if we(1) = '1' then
				sram(index)(15 downto 8)	<= din(15 downto 8);
			end if;	
			if we(2) = '1' then
				sram(index)(23 downto 16)	<= din(23 downto 16);
			end if;	
			if we(3) = '1' then
				sram(index)(31 downto 24)	<= din(31 downto 24);
			end if;	
			dout <= sram(index);
		end if;	
	end process;
	
end behavior;
