library ieee;
use ieee.std_logic_1164.all;

entity PORT_A is
port(clk, rst_b, Port_Sel, ADDR0, R_W: in std_logic;
		DBUS:	inout std_logic_vector(7 downto 0);
		PinA: inout std_logic_vector(7 downto 0));
end PORT_A;

architecture port1 of PORT_A is
signal DDRA, PORTA : std_logic_vector(7 downto 0);
signal loadDDRA, loadPORTA, ReadPORTA, ReadDDRA : std_logic;

begin			
loadPORTA <= '1' when (Port_Sel='1' and ADDR0='0' and R_W='1') else '0';
loadDDRA <= '1' when (Port_Sel='1' and ADDR0='1' and R_W='1') else '0';
ReadPORTA <= '1' when (Port_Sel='1' and ADDR0='0' and R_W='0') else '0';
ReadDDRA <= '1' when (Port_Sel='1' and ADDR0='1' and R_W='0') else '0';

-- pin interface logic
Portbits: for i in 7 downto 0 generate
  PinA(i) <= PORTA(i) when DDRA(i) = '1' else 'Z';  -- set external pin state
  DBUS(i) <= DDRA(i) when (ReadDDRA = '1')  -- read data direction register
    else PinA(i) when (ReadPORTA = '1')
    else 'Z';							
end generate;

process (clk, rst_b)	-- this process writes to the port registers
begin
  if (rst_b = '0') then DDRA <= "00000000";   -- set all pins to inputs
	elsif (rising_edge(clk)) then
    if (loadDDRA = '1') then DDRA <= DBUS; end if;
    if (loadPORTA = '1') then PORTA <= DBUS;end if;
	end if;
end process;
end port1;

