--  The!Cart SPI port for EEPROM
--
--  Copyright (C) 2011-2014 Matthias Reichl <hias@horus.com>
--
--  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 2 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, write to the Free Software
--  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.NUMERIC_STD.ALL;

library work;
use work.all;
use CartDef.all;

entity CartSPI is
    Port (	clk_register: in std_logic;
		a: in vec12;
		cctl_access: in CartControlState;
		d_in: in std_logic_vector;
		rw: in std_logic;
		reset_n: in std_logic;
		cs: out std_logic := '1';
		sck: out std_logic := '0';
		si: out std_logic;
		so: in std_logic;
		output: out data_output
	);
end CartSPI;

architecture Behavioral of CartSPI is

begin

	spi_write: process(clk_register)
	begin
		if falling_edge(clk_register) then
			if (reset_n = '0') then
				cs <= '1';
				si <= '1';
				sck <= '0';
			else
				if (rw = '0') and (cctl_access = access_cctl_thecart) and (a(3 downto 0) = spi_adr) then
					si <= d_in(7);
					cs <= d_in(1);
					sck <= d_in(0);
				end if;
			end if;
		end if;
	end process spi_write;

	spi_read: process(a, rw, cctl_access, so)
	begin
		output.dout_enable <= false;
		output.dout <= (others => '0');
		if (rw = '1') and (cctl_access = access_cctl_thecart) and (a(3 downto 0) = spi_adr) then
			output.dout_enable <= true;
			output.dout <= so & "0000000";
		end if;
	end process spi_read;

end Behavioral;

