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



entity phase_comparator is
  generic(
    data_len_g          : natural := 16 
    );
  port(

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

    clk_lb_i            : in std_logic;

    max_value_i         : in std_logic_vector( data_len_g - 1 downto 0 );

    stable_o            : out std_logic;
    value_o             : out std_logic
  );
end phase_comparator;

architecture arch of phase_comparator is 

  -- stable_r values counter
  signal  cnt_r       : unsigned( data_len_g - 1 downto 0 );

  signal  shr_r       : std_logic_vector( 7 downto 0 );
  
  signal  stable_r      : std_logic;
  signal  value_r       : std_logic;

begin

  stable_o    <= stable_r;
  value_o     <= value_r;


  stable_detector_sp : process( clk_ref_i )
  begin
    if rising_edge( clk_ref_i ) then
      if rst_n_i = '0' then
        cnt_r       <= ( to_unsigned( 0, data_len_g ) );
      else
        value_r     <= shr_r(7);
        
        if shr_r(7) = shr_r(6) then
          
          if cnt_r < unsigned( max_value_i ) then
            cnt_r       <= cnt_r + 1;
            stable_r      <= '0';

          else
            cnt_r       <= cnt_r;
            stable_r      <= '1';
            
          end if;
        else
          cnt_r        <= ( to_unsigned( 0, data_len_g ) );
          stable_r       <= '0';

        end if;
      end if;
    end if;
  end process;


  shr_sp : process( clk_ref_i )
  begin
    if rising_edge( clk_ref_i ) then
      if rst_n_i = '0' then
        shr_r     <= ( others => '0' );

      else
        shr_r     <= shr_r( 6 downto 0 ) & clk_lb_i;

      end if;
    end if;
  end process;


  



end arch;