LIBRARY ieee;
USE ieee.std_logic_1164.all;
USE ieee.std_logic_unsigned.all;
use ieee.numeric_std.all;
<?
    if (elem.Bits<2)
      panic("err_counterNeedsMoreBits");
?>
entity DIG_CounterPreset is
  generic ( Bits: integer;<?       vhdl.registerGeneric("Bits");?>
            maxValue: integer );<? vhdl.registerGeneric("maxValue");?>
  port (
    p_out : out std_logic_vector((Bits-1) downto 0);
    ovf : out std_logic;
    C   : in std_logic;
    en  : in std_logic;
    clr : in std_logic;
    dir : in std_logic;
    p_in  : in std_logic_vector((Bits-1) downto 0);
    ld  : in std_logic );
end DIG_CounterPreset;

architecture Behavioral of DIG_CounterPreset is
   signal count : std_logic_vector((Bits-1) downto 0) := (others => '0');

   function maxVal ( maxv : integer )
       return integer is variable m : integer;
   begin
      if (maxv = 0) then
        m := (2**Bits)-1;
      else
        m := maxv;
      end if;
      return m;
   end function maxVal;

begin
    process (C, en)
    begin
      if rising_edge(C) then
        if clr='1' then
          count <= (others => '0');
        elsif ld='1' then
          count <= p_in;
        elsif en='1' then
          if dir='0' then
            if count=maxVal(maxValue) then
              count <= (others => '0');
            else
              count <= count + 1;
            end if;
          else
            if count=<?=0?> then
              count <= std_logic_vector(to_unsigned(maxVal(maxValue), Bits));
            else
              count <= count - 1;
            end if;
          end if;
        end if;
      end if;
    end process;

    p_out <= count;
    ovf <= en when (count = maxVal(maxValue) and dir='0') OR
                   (count = 0 and dir='1') else '0';
end Behavioral;