LIBRARY ieee;
USE ieee.std_logic_1164.all;
USE ieee.std_logic_arith.all;
use ieee.std_logic_unsigned.all;

USE work.sercon_types.all;

--
entity sercon_stat is
  generic(
    bit_width:natural:=32
    );
  port(
    ctrl: in sercon_ctrl;
    --
    sbus_in: in sercon_bus;
    sbus_out: out sercon_bus;
    
    -- parallel data input.
    pdin: in std_logic_vector(bit_width-1 downto 0)
    );
end entity sercon_stat;
--
architecture v0 of sercon_stat is

--   rst: in std_logic;
--   clk: in std_logic;
--   --
--   wload: in std_logic;
--   rload: in std_logic;
--     sclk_en: in std_logic;
--     -- serial data input
--     sdin: in std_logic;
--     -- serial data output
--     sdout: out std_logic;
--     -- serial mask input 
--     smin: in std_logic;
--     -- serial mask output: 
--     smout: out std_logic;

  signal rst: std_logic;
  signal clk: std_logic;
--
  signal wload: std_logic;
  signal rload: std_logic;
  signal sclk_en: std_logic;


-- serial data input
  signal sdin: std_logic;
-- serial data output
  signal sdout: std_logic;
-- serial mask input 
  signal smin: std_logic;
-- serial mask output: 
  signal smout: std_logic;
  
  signal int_dsreg: std_logic_vector(bit_width-1 downto 0);
  signal int_msreg: std_logic_vector(bit_width-1 downto 0);
begin
  
  rst<=ctrl.rst;
  clk<=ctrl.clk;
  sclk_en<=ctrl.cen;
  wload<=ctrl.wload;
  rload<=ctrl.rload;

  sdin<=sbus_in.sdata;
  smin<=sbus_in.smask;
  
  sbus_out.sdata<=sdout;
  sbus_out.smask<=smout;

  smout<=int_msreg(bit_width-1);
  sdout<=int_dsreg(bit_width-1);
  
  sercon_slave:process(rst, clk)
  begin
    if(rst='1')then 
      int_msreg<=(others=>'0');
      int_dsreg<=(others=>'0');
    elsif(clk='1' and clk'event)then
      if(sclk_en='1')then
        int_msreg<=int_msreg(bit_width-2 downto 0)&smin;
        int_dsreg<=int_dsreg(bit_width-2 downto 0)&sdin;
      elsif(rload='1')then
        int_dsreg<=pdin;
      elsif(wload='1')then
        -- deal with the case
        -- where a write is attempted:
        int_dsreg<=(others=>'0');
        int_msreg<=(others=>'0');        
      end if;
    end if;
  end process sercon_slave;     

end architecture v0;
