--
-- Downlink Serialiser
--
-- A bit micky-mouse but will do the job in sim
--
-- Matt Warren Aug 2016
--
--


library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_arith.all;
use ieee.std_logic_unsigned.all;

library downlink;
use downlink.lcb_pkg_globals.all;


entity lcb_serialiser is
  port(

    frame_sync_i : in std_logic_vector(1 downto 0);
    par4_i       : in std_logic_vector(3 downto 0);
    delay160_i   : in std_logic_vector(1 downto 0);

    ------------------------------
    ser_o : out std_logic;

    -- Infra
    clk160 : in std_logic;
    --clk40    : in std_logic;              --40MHz BCO
    rst    : in std_logic
    );

-- Declarations

end lcb_serialiser;

---------------------------------------------------------------------------
architecture rtl of lcb_serialiser is


  signal fs160_q     : std_logic;
  signal ser_q      : std_logic_vector(3 downto 0);
  signal bitcount160 : integer range 0 to 3;


begin


  -- Serialiser
  -- -----------------------------------------------------------------------
  -- Selector type - may not be ideal, but this will never make it
  -- to the final system anyway

  prc_serialiser : process (clk160)
    variable bitcount160_set : std_logic;
  begin

    if rising_edge(clk160) then
      if (rst = '1') then
        fs160_q         <= '0';
        bitcount160_set := '0';

      else

        -- defaults
        fs160_q         <= '0';
        bitcount160_set := '0';

        if (frame_sync_i = FSYNC_FRAME) then
          fs160_q <= '1';
          if (fs160_q = '0') then
            bitcount160_set := '1';
          end if;
        end if;

        -- bit counter
        -------------------------------------------
        if (bitcount160_set = '1') then
          bitcount160 <= 2;             -- This is tuned for phase of outgoing
                                     -- ser wrt BCO            
        elsif (bitcount160 = 0) then
          bitcount160 <= 3;

        else
          bitcount160 <= bitcount160 - 1;

        end if;



      end if;
    end if;
  end process;



  -- delayed ser to match decoder phasing
  -- (and to clock out too)

  ser_q(0) <= par4_i(bitcount160); -- direct flow thought, if needed
  ser_q(3 downto 1) <= ser_q(2 downto 0) when rising_edge(clk160);

  ser_o  <= ser_q(conv_integer(delay160_i));


end rtl;