library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_arith.all;
use ieee.std_logic_unsigned.all;

entity simple_trigger_input_latch is

  port(
    srst: in std_logic;
    clk: in std_logic;
    --
    enable: in std_logic_vector(15 downto 0);
    invert_mask: in std_logic_vector(15 downto 0);
    
    trig_in_se: in std_logic_vector(7 downto 0);
    trig_in_p: in std_logic_vector(7 downto 0);
    trig_in_n: in std_logic_vector(7 downto 0);
    --
    trig_out: out std_logic_vector(15 downto 0);

    -- unlatched trigger out for real time monitoring: 
    trig_out_rt: out std_logic_vector(15 downto 0)

    );

end entity simple_trigger_input_latch;

architecture v0 of simple_trigger_input_latch is

  signal int_trig_in_converted: std_logic_vector(7 downto 0);

  signal int_trig:std_logic_vector(15 downto 0);
  
  signal int_latched_trigger_reg0: std_logic_vector(15 downto 0);
  signal int_latched_trigger_reg1: std_logic_vector(15 downto 0);

  component ibufds_lvds_25
    port(
      O  : out std_ulogic;
      I   : in std_ulogic;
      IB  : in std_ulogic
      );
  end component ibufds_lvds_25;
  
begin 
  -- lvds conversion:
  
  u_gen_ibufds_lvds_25:for i in 0 to 7
  generate
    u_ibufds_lvds_25:ibufds_lvds_25
      port map(
        O =>int_trig_in_converted(i),
        I  =>trig_in_p(i),
        IB =>trig_in_n(i));
  end generate u_gen_ibufds_lvds_25;
  
  -- permit the inversion of any channel: 
  u_gen_inversion0:for i in 0 to 7
  generate
    int_trig(i)<=trig_in_se(i) when invert_mask(i)='0' else
                  not(trig_in_se(i));
  end generate u_gen_inversion0;

  u_gen_inversion:for i in 8 to 15
  generate
    int_trig(i)<=int_trig_in_converted(i-8) when invert_mask(i)='0' else
                  not(int_trig_in_converted(i-8));
  end generate u_gen_inversion;
  
  
  -- 
  latch_inputs:process(clk)
  begin
    if(rising_edge(clk))then 
      if(srst='1')then
        int_latched_trigger_reg1<=(others=>'0');
      else
        int_latched_trigger_reg0<=int_trig;

        for i in 0 to 15 loop
          if(int_latched_trigger_reg0(i)='1' and enable(i)='1')then
            int_latched_trigger_reg1(i)<='1';
          end if;
        end loop; 
      end if;
    end if;
  end process latch_inputs;

  trig_out<=int_latched_trigger_reg1;
  trig_out_rt<=int_latched_trigger_reg0;
  
end architecture v0;
