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

library work;
use work.mbist_pkg.all;

-- ----------------------------------------------------------------------------
-- Entity
-- ----------------------------------------------------------------------------
entity MBIST_NCNT_DEC is
  generic (
    WIDTH      : natural;        -- Width of counter
    STEPS      : unsigned        -- Number of steps to go
  );
  port (
    CLK        : in  std_logic;  -- System clock
    RST_B      : in  std_logic;  -- System wide reset

    CNTE       : in  std_logic;  -- Counter enable
    CLR        : in  std_logic;  -- Counter clear

    CNT_END    : out std_logic   -- This value is last in cycle
  );
end entity MBIST_NCNT_DEC;

architecture rtl of MBIST_NCNT_DEC is

  subtype t_CNT is unsigned(WIDTH - 1 downto 0);
  signal cnt_c : t_CNT;
  signal cnt_s : t_CNT := (others => '0');
  
begin

  p_cnt_c: process (cnt_s, CNTE, CLR) is
    variable cnt_fb_c : std_logic;
  begin
    if CLR = '1' or cnt_s = STEPS then
      cnt_c <= (others => '0');
    elsif CNTE = '1' then
      cnt_c <= cnt_s + to_unsigned(1, WIDTH);
    else
      cnt_c <= cnt_s;
    end if;
  end process p_cnt_c;

  p_ff_s: process (CLK, RST_B) is
  begin
    if RST_B = '0' then
      cnt_s <= (others => '0');
    elsif rising_edge(CLK) then
      cnt_s <= cnt_c;
    end if;
  end process;

  -- Detect end of counting
  CNT_END <= '1' when cnt_s = STEPS else '0';

end architecture rtl;
