-- Tester for simple ram model
library ieee;
use ieee.std_logic_1164.all;
library bitlib;
use bitlib.bit_pack.all;

entity RAM6116_system is
end RAM6116_system;

architecture RAMtest of RAM6116_system is
	component RAM6116 is
		port(Cs_b, We_b: in bit;
			Address: in bit_vector(7 downto 0);
			IO: inout std_logic_vector(7 downto 0));
	end component RAM6116;
	signal state, next_state: integer range 0 to 3;
	signal inc_adrs, inc_data, ld_data, en_data, Cs_b, clk, done: bit;
	signal We_b: bit := '1';				-- initialize to read mode
	signal Data: bit_vector(7 downto 0);		-- data register
	signal Address: bit_vector(7 downto 0);	-- address register
	signal IO: std_logic_vector(7 downto 0);	-- I/O bus

begin
	RAM1: RAM6116 port map(Cs_b, We_b, Address, IO);
	control: process(state, Address)
	begin
		--initialize all control signals (RAM always selected)
		ld_data<='0'; inc_data<='0'; inc_adrs<='0'; en_data <='0';
		 done <= '0'; We_b <='1'; Cs_b <= '0';
		--start SM chart here
		case (state) is
			when 0 => 	ld_data <= '1';  next_state <= 1;
			when 1 =>	inc_data <= '1'; next_state <= 2;
			when 2 =>	We_b <= '0';  en_data <= '1';  inc_adrs <= '1'; next_state <= 3;
			when 3 =>	if (Address = "00001000") then done <= '1';
								else next_state <= 0;
							end if;
		end case;
	end process control;

	--The following process is executed on the rising edge of a clock.
	register_update: process
	begin
		wait until clk = '1';
		state <= next_state;
		if (inc_data = '1') then data <= int2vec(vec2int(data)+1,8); end if;
		if (ld_data = '1') then data <= To_bitvector(IO); end if;
		if (inc_adrs = '1') then  
			Address <= int2vec(vec2int(Address)+1,8) after 1 ns;
					-- delay added to allow completion of memory write 
		end if;
	end process register_update;

	-- Concurrent statements
	clk <= not clk after 100 ns;
	IO <= To_StdLogicVector(data) when en_data = '1' 
		else "ZZZZZZZZ";
end RAMtest;


