--******************************************************************************
--* @short      Data Output Block
--*
--*             receives two muons and puts them out at 80 MHz (as inverted GTLp signals)
--******************************************************************************
--* @author  Taurok Anton  <taurokc@dsy-srv3.cern.ch>
--* @date    $Date: 2006/06/02 09:29:39 $
--* @version $Revision: 1.1 $
--******************************************************************************
--/
library IEEE;
use IEEE.Std_logic_1164.all;
use IEEE.Numeric_std.all;
use WORK.GMTTypes.all;
-- pragma translate_off
library UNISIM;
use UNISIM.VCOMPONENTS.all;
--pragma translate_on

entity SFDOutput is
  port (iMuon1 : in  TGMTMu;
        iMuon2 : in  TGMTMu;
        oMuon  : out TGMTMu_flat;

        -- Clock and control
        clk   : in std_logic;
	clk80 : in std_logic);
end;


architecture behavioral of SFDOutput is
  attribute syn_useioff               : boolean;
  attribute syn_useioff of behavioral : architecture is true;

  signal sMuon1_reg, sMuon2_reg            : TGMTMu;
  signal sMuon1_reg_flat, sMuon2_reg_flat  : TGMTMu_flat;

  signal sel_mu1 : std_logic;


begin  -- architecture behavioral
  --  Remark: The module SFDOutput sends the muons 0.5bx later 
  --          than the original SFDDROutput.vhd.
  --  Reason: REC chip: 2x FD(80MHz) + COND chip 1x FD(80MHz) 
  --          before demultiplexing back to 40 MHz
  ------------------
  -- register muon 1 and muon 2 after ~22ns sorting logic
  reg_12 : process (clk, iMuon1, iMuon2) is
  begin
    if clk'event and clk = '1' then
      sMuon1_reg <= iMuon1;
      sMuon2_reg <= iMuon2;
    end if;
  end process reg_12;
  
  -- convert to flat format
  sMuon1_reg_flat     <= not GMTMu_to_flat(sMuon1_reg);  --send inverted GTLp signals
  sMuon2_reg_flat     <= not GMTMu_to_flat(sMuon2_reg);  --send inverted GTLp signals

  -- Make Select signal for 40to80MUX
  sel_proc: process( clk, clk80)
  begin
      if clk80'event and clk80 = '1' then
         sel_mu1 <= not clk;         -- take inverted clock to send muon1 to muon1 in COND chip
      end if;    
  end process sel_proc;

  -- 40to80MUX and output
  mux40to80: process (clk80, sel_mu1, sMuon1_reg_flat, sMuon2_reg_flat) 
  begin
      if clk80'event and clk80 = '1' then
         if ( sel_mu1 = '1') then
	   oMuon <= sMuon1_reg_flat;
	 else
	   oMuon <= sMuon2_reg_flat;
	 end if;
      end if;
   end process mux40to80;
      
end architecture behavioral;