----------------------------------------------------------------------------------
-- Company: 
-- Engineer: CC
-- 
-- Create Date:    10:12:25 04/10/2016
-- Design Name: 
-- Module Name:    rst_cnt_fsm - Behavioral 
-- Project Name: 
-- Target Devices: 
-- Tool versions: 
-- Description: state machine to manage reset procedure for counters
--
-- Dependencies: 
--
-- Revision 0.01 - File Created
--Revision 0.03 - add trigger I/O
--Revision 0.0 - add tdc enable output 
-- Additional Comments: 
----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
--use ieee.numeric_std.all;


entity rst_cnt_fsm is

    Port (
		clk_i				: in std_logic;
		rst_i				: in std_logic;	
		cnt_en_i			: in std_logic;	
		pps_detect_i	: in std_logic;
		cnt_en_o 		: out std_logic;
		cnt_en_ack_o 	: out std_logic;
		tdc_rst_o		: out std_logic;
		ext_trig_o		: out std_logic
	 );
end rst_cnt_fsm;

architecture Behavioral of rst_cnt_fsm is
	
	type STATE_TYPE is (RST,INIT, RUN);		
	signal current_state : STATE_TYPE;
	 
begin

  
  process (clk_i)
	begin
	if rising_edge(clk_i)then
		if (rst_i = '1') then
			cnt_en_ack_o  <= '0';
			cnt_en_o 		<= '0';
			ext_trig_o		<= '0';
			tdc_rst_o     	<= '1';
			current_state	<= RST;	

		else
			case current_state is
					
			when RST =>
				tdc_rst_o     	<= '1';
				cnt_en_ack_o  	<= '0';
				cnt_en_o 		<= '0';
				ext_trig_o		<= '0';							
				if cnt_en_i = '1' then		-- command received to start counters & TDC 
					--cnt_en_ack_o  	<= '1';
					current_state	<= INIT;		
				else
					--cnt_en_ack_o  	<= '0';
					current_state	<=	RST;
				end if;
				
				when INIT =>
					--cnt_en_ack_o  <= '1';
					if pps_detect_i = '1' then -- enable TDC, start counters & send an external trigger on next PPS
						ext_trig_o		<= '1';	-- width one clock cycle, enough ?
						cnt_en_ack_o  	<= '1';
						cnt_en_o 		<= '1';
						tdc_rst_o     	<= '0';
						current_state 	<= RUN;
					else
						tdc_rst_o     	<= '1';
						ext_trig_o		<= '0';
						cnt_en_o 		<= '0';
						current_state	<=	INIT;
					end if;
				
				when RUN =>
					tdc_rst_o   <= '0';
					--cnt_en_o 	<= '1';
					ext_trig_o	<= '0';
					if cnt_en_i = '0' then
						cnt_en_o 		<= '0';
						cnt_en_ack_o  	<= '0';		-- send reset ack through UDP and disable & reset counters
						tdc_rst_o     	<= '1';		-- disable tdc
						current_state	<= RST;		-- STOP_TRIG;
					else
						cnt_en_o 	  <= '1';
						cnt_en_ack_o  <= '1';
						tdc_rst_o     <= '0';
						current_state	<=	RUN;
					end if;					
						
				when others => 
					current_state	<=	RUN;			
			end case;
		 end if; 
	end if;
	end process;
	
	
end Behavioral;
