--******************************************************************************
--* @short   8->4 Sorter based on sort ranks
--******************************************************************************
--* @author  SAKULIN Hannes  <hsakulin@dsy-srv3.cern.ch>
--* @date    $Date: 2004/12/17 09:30:38 $
--* @version $Revision: 1.3 $
--******************************************************************************
--/
library IEEE;
use IEEE.Std_logic_1164.all;
use IEEE.Numeric_std.all;
use WORK.GMTTypes.all;

package SorterUnit is

  -- Greater-Equal Matrix 
  type TGEMatrix is array (integer range 0 to 7, integer range 0 to 7) of std_logic;
  
  procedure count_wins (
    iGEMatrix         : in  TGEMatrix;
    iEmpty            : in  std_logic_vector(0 to 7);
    signal oSelBits   : out TSelBits_1_of_8_vec);

end SorterUnit;

package body SorterUnit is
  
  procedure count_wins (
    iGEMatrix         : in  TGEMatrix;
    iEmpty            : in  std_logic_vector(0 to 7);
    signal oSelBits : out TSelBits_1_of_8_vec) is

    variable nwin : integer range 0 to 7;
  begin  -- procedure count_wins
    for i in 0 to 7 loop
      nwin := 0;
      for j in 0 to 7 loop
        if i /= j then
          if iGEMatrix(i,j)='1' or  iEmpty(j)='1' then
            nwin := nwin + 1;
          end if;
        end if;
      end loop;  -- j
      if iEmpty(i) = '0' then
        for iplace in oSelBits'RANGE loop
          if nwin = 7-iplace then
            oSelBits(iplace)(i) <= '1';
          else
            oSelBits(iplace)(i) <= '0';            
          end if;            
        end loop;  -- iplace
      else
        for iplace in oSelBits'RANGE loop
          oSelBits(iplace)(i) <= '0';            
        end loop;  -- iplace
      end if;
    end loop;  -- i
  end;
    
end package body SorterUnit;