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

--  Uncomment the following lines to use the declarations that are
--  provided for instantiating Xilinx primitive components.
--library UNISIM;
--use UNISIM.VComponents.all;


entity decim is
    Port ( reset 			: in std_logic;
           clk 			: in std_logic;							  -- clk signal
           decim_ratio	: in std_logic_vector (1 downto 0);	  -- deimation ratio
			  decim_en		: in std_logic;							  -- enable
			  decim_flag	: in std_logic;							  -- equivalent to synch'd trigger
			  decim_sig		: out std_logic);							  -- decimated signal
end decim;

-- ##################################################################### --
-- The decimation is performed by controlling the write and read enable. --
-- The clock signals are NOT gated.													 --
--	decim_ratio:																			 --
--		00 <=>  No decimation															 --
--		01 <=>  1:2          															 --
--		10 <=>  1:4																			 --
--		11 <=>  1:8																			 --
--	Once the decim flag (trigger received) is active then the decimation	 --
-- stops																						 --
-- ##################################################################### --


architecture Behavioral of decim is

-- signals
-------------------------------------------------------
signal cnt 				: integer range 7 downto 0;
signal cnt_vect		: std_logic_vector (2 downto 0);

-------------------------------------------------------
-- architecture description
-------------------------------------------------------
begin
	-- assignments
	cnt_vect <= CONV_STD_LOGIC_VECTOR (cnt, 3);
	----------------------------------------------------

	-- processes
	----------------------------------------------------

	-- counter -- 
	process (reset, clk, decim_en, cnt)
	begin  
		if reset = '0' then
 			cnt <= 0;

		elsif ( clk'event and clk = '1' ) then

			if decim_en = '0' then

				if cnt < 7 then 			
					cnt <= cnt + 1;

				else
					cnt <= 0;

				end if;

			else
				cnt <= cnt;
			end if;

		end if;
	end process;
	----------------------------------------------------

	-- decimation signal
	process (reset, decim_flag, decim_ratio, cnt_vect)
	begin  
		if reset = '0' then
	
			decim_sig <= '1';
	
		elsif decim_flag = '0' then

		   case decim_ratio is
		      when "00" =>
		         decim_sig <= '0';
		      when "01" =>
		         decim_sig <= cnt_vect(0);
		      when "10" =>
		         decim_sig <= cnt_vect(0) or cnt_vect(1);
		      when others =>
		         decim_sig <= cnt_vect(0) or cnt_vect(1) or cnt_vect(2);
		   end case;

		else 	

			decim_sig <= '0';

		end if;
	
	end process;

end Behavioral;
