--******************************************************************************
--* @short      Sort Rank Merge Unit. merges the sort ranks for one DTCSC/merged moun
--******************************************************************************
--* @author  SAKULIN Hannes  <hsakulin@dsy-srv3.cern.ch>
--* @date    $Date: 2005/01/31 15:17:30 $
--* @version $Revision: 1.3 $
--******************************************************************************
--/
library IEEE;
use IEEE.Std_logic_1164.all;
use IEEE.Numeric_Std.all;
use WORK.GMTTypes.all;

entity LFSortRankMergeUnit is
  
  port (
    -- INPUTS
    iSortRankDTCSC        : in TSortRank;  

    iSortRankMatchedDTCSC : in TSortRank;
    iSortRanksMatchedRPC  : in TSortRank_vector(0 to 3);

    iWhichRPC             : in std_logic_vector(0 to 3);
    iSelectBits           : in std_logic_vector(0 to 3);
    
    -- OUTPUTS
    oSortRank             : out TSortRank;
        
    -- Clock and control
    clk            : in    std_logic;
    sinit          : in    std_logic
  );  
  
end entity LFSortRankMergeUnit;

architecture behavioral of LFSortRankMergeUnit is

  signal sSortRankRPC : TSortRank;
  signal sSelBit      : std_logic; -- 1 for DT/CSC
  signal sIsMerged    : std_logic;
  
begin  -- architecture behavioral

  -----------------------------------------------------------------------------
  -- Mux the RPC muon
  -----------------------------------------------------------------------------

  -- process does not create latches
  -- but case must be complete (i.e. no null in when others)
  mux_srk: process (iSortRanksMatchedRPC, iWhichRPC) is
  begin  -- process mux
    case iWhichRPC is
      when "1000" => sSortRankRPC <= iSortRanksMatchedRPC(0);
      when "0100" => sSortRankRPC <= iSortRanksMatchedRPC(1);
      when "0010" => sSortRankRPC <= iSortRanksMatchedRPC(2);
      when "0001" => sSortRankRPC <= iSortRanksMatchedRPC(3);
      when others => sSortRankRPC <= (others => '0');
    end case;
  end process mux_srk;
  
  mux_sel: process (iSelectBits, iWhichRPC) is
  begin  -- process mux
    case iWhichRPC is
      when "1000" => sSelBit <= iSelectBits(0);
      when "0100" => sSelBit <= iSelectBits(1);
      when "0010" => sSelBit <= iSelectBits(2);
      when "0001" => sSelBit <= iSelectBits(3);
      when others => sSelBit <= '0';
    end case;
  end process mux_sel;

  -----------------------------------------------------------------------------
  -- Mux DTCSC or Merged
  -----------------------------------------------------------------------------
  
  sIsMerged <= iWhichRPC(0) or iWhichRPC(1) or iWhichRPC(2) or iWhichRPC(3) ;

  oSortRank <= iSortRankDTCSC when sIsMerged = '0' else
               iSortRankMatchedDTCSC when sSelBit = '1' else
               sSortRankRPC;

end architecture behavioral;