--
-- VHDL Architecture FACT_FAD_lib.trigger_manager.beha
--
-- Created:
--          by - daqct3.UNKNOWN (IHP110)
--          at - 11:26:52 14.01.2011
--
-- using Mentor Graphics HDL Designer(TM) 2009.1 (Build 12)
--
LIBRARY ieee;
USE ieee.std_logic_1164.all;
USE ieee.std_logic_arith.all;

ENTITY trigger_manager IS
  port (
    clk : in std_logic;
    
    trigger_in : in std_logic;
    trigger_out : out std_logic := '0';
    
    drs_write : out std_logic := '1';
    
    drs_readout_ready : in std_logic;
    drs_readout_ready_ack : out std_logic := '0'

  );
END ENTITY trigger_manager;

--
ARCHITECTURE beha OF trigger_manager IS
  
  type trigger_in_state_type is (T_IN_MAIN, T_IN_END);
  type trigger_out_state_type is (T_OUT_MAIN, T_OUT_TSTART, T_OUT_TEND);
  
  signal trigger_in_state : trigger_in_state_type := T_IN_MAIN;
  signal trigger_out_state : trigger_out_state_type := T_OUT_MAIN;

  signal drs_write_flag, drs_write_flag_int : std_logic := '0';
  
BEGIN
  
  trigger_in_proc : process (trigger_in, trigger_in_state) begin
    case trigger_in_state is
      when T_IN_MAIN =>
        if rising_edge (trigger_in) then
          -- stop drs
          drs_write <= '0';
          -- set flag
          drs_write_flag <= '1';
        end if;
      when T_IN_END =>
        drs_write <= '1';
        drs_write_flag <= '0';
    end case; -- trigger_in_state
  end process trigger_in_proc;
  
  trigger_out_proc : process (clk) begin
    if rising_edge (clk) then
      
      drs_write_flag_int <= drs_write_flag;
      
      case trigger_out_state is
        when T_OUT_MAIN =>
          if (drs_write_flag_int = '1') then
            trigger_out <= '1';
            drs_readout_ready_ack <= '0';
            trigger_out_state <= T_OUT_TSTART;
          end if;
        when T_OUT_TSTART =>
          if (drs_readout_ready = '1') then
            trigger_out <= '0';
            trigger_in_state <= T_IN_END;
            trigger_out_state <= T_OUT_TEND;
          end if;
        when T_OUT_TEND =>
          drs_readout_ready_ack <= '1';
          trigger_in_state <= T_IN_MAIN;
          trigger_out_state <= T_OUT_MAIN;
      end case; -- trigger_out_state
    end if;
  end process trigger_out_proc;
  
END ARCHITECTURE beha;

