library  IEEE;
use IEEE.STD_LOGIC_1164.all;
use IEEE.STD_LOGIC_unsigned.all;

entity En_clk is
port (
	Resetb:		in  std_logic;
	Clk:		in  std_logic;
	Start:		in	std_logic;
	Stop:		in	std_logic;
	Clk_out:	out	std_logic;
	SPY1:		out	std_logic;
	SPY2:		out	std_logic;
	SPY3:		out	std_logic;
	SPY4:		out	std_logic);
end En_clk;

architecture rtl of En_clk is

signal SynchStart1, SynchStart2, SynchStart3:	std_logic;
signal SynchStop1, SynchStop2, SynchStop3:	std_logic;
signal Strt, Stp :	std_logic;
signal StateMeClk :	std_logic_vector(0 downto 0);
signal Enable :	std_logic;

begin

--------------------------
-- Synchro signal Start --
--------------------------
SynchInSignal1: process (Resetb, Clk)
begin
if  Resetb = '0' then
	SynchStart1		<= '0';
	SynchStart2		<= '0';
	SynchStart3		<= '0';
else
	if Clk'Event and Clk = '1' then
		SynchStart1  	<= Start;
		SynchStart2 	<= SynchStart1;
		SynchStart3 	<= SynchStart2;
	end if;
end if;
end process SynchInSignal1;

Strt <= SynchStart2 AND (NOT(SynchStart3));

---------------------------
-- Synchro signal Stop   --
---------------------------
SynchInSignal2: process (Resetb, Clk)
begin
if  Resetb = '0' then
	SynchStop1		<= '0';
	SynchStop2		<= '0';
	SynchStop3		<= '0';
else
	if Clk'Event and Clk = '1' then
		SynchStop1  <= Stop;
		SynchStop2 	<= SynchStop1;
		SynchStop3 	<= SynchStop2;
	end if;
end if;
end process SynchInSignal2;

Stp <= SynchStop2 AND (NOT(SynchStop3));

------------------------------------------
-- Machine Etat               --
------------------------------------------

MeClk : process (Resetb, Clk)
---------------------------------
begin
  if Resetb = '0' then
	StateMeClk <= "1";
  else
    if (Clk'event and Clk = '0') then

      case StateMeClk is
        when "0" =>        if Strt = '1' then
                                  StateMeClk <= "1";
                                else
                                  StateMeClk <= "0";
                                end if;

        when "1" =>        if Stp = '1' then
                                  StateMeClk <= "0";
                                else
                                  StateMeClk <= "1";
                                end if;

        when others   =>        StateMeClk <= "1";
      end case;
    end if;                             -- falling edge clock
  end if;                               -- reset
end process MeClk;

Enable <= StateMeClk(0);

Clk_out <= Enable AND Clk;
SPY1 <= Enable;
SPY2 <= Clk;
SPY3 <= Strt;
SPY4 <= SynchStart1;

end rtl;
