----------------------------------------------------------------------------------
-- Company: 
-- Engineer: 
-- 
-- Create Date: 09.03.2026 15:14:35
-- Design Name: 
-- Module Name: counter - Behavioral
-- Project Name: 
-- Target Devices: 
-- Tool Versions: 
-- Description: 
-- 
-- Dependencies: 
-- 
-- Revision:
-- Revision 0.01 - File Created
-- Additional Comments:
-- 
----------------------------------------------------------------------------------


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

-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;

-- Uncomment the following library declaration if instantiating
-- any Xilinx leaf cells in this code.
--library UNISIM;
--use UNISIM.VComponents.all;

entity counter is
    Port ( CLK : in STD_LOGIC;
           RST : in STD_LOGIC;
           CE : in STD_LOGIC;
           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) := "0000";
begin

    -- Main counting logic
    process(CLK)
    begin
        if rising_edge(CLK) then
            if RST = '1' then
                s_cnt <= "0000";
            elsif CE = '1' then
                if s_cnt = "1001" then -- If we are at 9
                    s_cnt <= "0000";   -- Reset to 0
                else
                    s_cnt <= s_cnt + 1; -- Increment
                end if;
            end if;
        end if;
    end process;

    -- Terminal Count logic (The red line connection)
    -- TC is '1' ONLY when we are at 9 AND the enable pulse is active.
    -- This ensures the next counter only moves once per rollover.
    TC <= '1' when (s_cnt = "1001" and CE = '1') else '0';

    -- Drive the output ports
    COUNT_OUT <= s_cnt;

end Behavioral;