----------------------------------------------------------------------------------
-- Company:   University of Connecticut
-- Engineer:  Igor Senderovich
-- 
-- Create Date:    09:40:38 11/12/2007 
-- Design Name: 
-- Module Name:    EdgeCounter4bit - Behavioral 
-- Description:    4-bit edge counter reset at Go
----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
--use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

entity EdgeCounter4bit is
    Port ( Clk : in  STD_LOGIC;
	   Rst : STD_LOGIC;
           Go : in  STD_LOGIC;
	   En : out STD_LOGIC;
           Q : out  STD_LOGIC_VECTOR (3 downto 0)
	 );
end EdgeCounter4bit;

architecture Behavioral of EdgeCounter4bit is

	signal count : STD_LOGIC_VECTOR (3 downto 0);
	signal count1_sh : STD_LOGIC;
	signal En_int : STD_LOGIC;

begin
	
	EdgeCounter4bit : process (Clk, Go, En_int, Rst)
	begin
		if Rst='1' then 
			count(3 downto 1) <= "111";
			count1_sh <= '1';
			En_int <= '0';
		else
			if falling_edge(Clk) then
			
				if count(3 downto 1)="111" then
					if Go='1' then
						count(3 downto 1) <= count(3 downto 1) + "001";
						En_int <= '1';
					else
						count(3 downto 1) <= count(3 downto 1);
						En_int <= not count1_sh;
					end if;
				else
					En_int<='1';
					count(3 downto 1) <= count(3 downto 1) + "001";
				end if;
				
			else
				count(3 downto 1) <= count(3 downto 1);
			end if;
			if rising_edge(Clk) and En_int='1' then 
				count1_sh <= not count1_sh;
			else 
				count1_sh <= count1_sh;
			end if;
		end if;
		count(0) <= not (count1_sh xor count(1));
--		if (Go='1' and Clk='0') then
--			count <= "0000";
--		else
--			if (En_int='1' and Clk'event and (Clk'last_value='0' or Clk'last_value='1')) then 
--				count <= count + "0001";
--			else
--				count <= count;
--			end if;
--		end if;
	end process;
	
	Q <= count;
	En <= En_int;-- or Go;
	
end Behavioral;
