-- project_7/project_5.srcs/sources_1/new/counter.vhd

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

entity counter is
    Generic ( MAX_LIMIT : STD_LOGIC_VECTOR(3 downto 0) := "1001" ); -- Default to 9
    Port ( CLK : in STD_LOGIC;
           RST : in STD_LOGIC;
           CE : in STD_LOGIC;
           PE : in  STD_LOGIC;
           DIN : in  STD_LOGIC_VECTOR(3 downto 0); 
           TC : out STD_LOGIC;
           COUNT_OUT : out STD_LOGIC_VECTOR (3 downto 0));
end counter;

architecture Behavioral of counter is
    -- Internal signal to keep track of the current number
    signal s_cnt : STD_LOGIC_VECTOR(3 downto 0) := (others => '0');
    -- (others => '0') je to iste ako "0000" pre 4 bity. Ale narozdiel od hardcode
    -- robi nuly cez vsetky bity, takze zalezi na pocte bitov rodica
begin

    -- Main counting logic
    process(CLK)
    begin
        if rising_edge(CLK) then
            if RST = '1' then
                s_cnt <= "0000";
            elsif PE = '1' then
                s_cnt <= DIN;
            elsif CE = '1' then
                if s_cnt = MAX_LIMIT then
                    s_cnt <= (others => '0');   -- Reset to 0 when limit is hit
                else
                    s_cnt <= s_cnt + 1; -- Otherwise increment
                end if;
            end if;
        end if;
    end process;
    TC <= '1' when (s_cnt = MAX_LIMIT and CE = '1') else '0';

    COUNT_OUT <= s_cnt;

end Behavioral;
