library ieee;
  use ieee.std_logic_1164.all;
  use ieee.numeric_std.all;



entity detect_periodic is
  -- used in pts to acquire dividers outputs for PD test
  generic(
    data_len_g          : natural := 16 
    );
  port(

    -- Clocks & resets
    clk_i               : in std_logic;
    rst_n_i             : in std_logic;

    -- PD Lock Detect line
    signal_i            : in std_logic;

    -- measured period (Dividers should give periodic pulses)
    period_en_o         : out std_logic;
    period_o            : out std_logic_vector( data_len_g - 1 downto 0 )


  );
end detect_periodic;

architecture arch of detect_periodic is 
  
  constant shr_len_c      : natural := 8;

  signal  signal_shr      : std_logic_vector( shr_len_c - 1 downto 0 );
  signal  cnt_r           : unsigned( data_len_g - 1 downto 0 );
  signal  buffer_r        : unsigned( data_len_g - 1 downto 0 );
  signal  buffer_en_r     : std_logic;

begin

  period_o      <= std_logic_vector( buffer_r );
  period_en_o   <= buffer_en_r;

  shift_reg_sh: process( clk_i, rst_n_i )
  begin
    if rising_edge( clk_i ) then
      if rst_n_i = '0' then
        signal_shr        <= ( others => '0' );
      else
        for i in shr_len_c - 1 downto 1 loop
          signal_shr(i)   <= signal_shr( i - 1 );
        end loop;

        signal_shr( 0 )   <= signal_i;
        
      end if;
    end if;
  end process;


  cnt_sp : process( clk_i, rst_n_i )
  begin
    if rising_edge( clk_i ) then
      if rst_n_i = '0' then
        cnt_r           <= ( others => '0' );
        buffer_r        <= ( others => '0' );
        buffer_en_r     <= '0';
      else
        
        if ( signal_shr( shr_len_c - 1 ) = '0' ) and ( signal_shr( shr_len_c - 2 ) = '1' ) then
          cnt_r         <= ( others => '0' );
          buffer_r      <= cnt_r;
          buffer_en_r   <= '1';
        else
          cnt_r         <= cnt_r + 1;
          buffer_r      <= buffer_r;
          buffer_en_r   <= '0';
        end if;

      end if;
    end if;
  end process;

end arch;