--******************************************************************************
--* @short      Delta Phi Subtractor (signed, modulo 144) 
--******************************************************************************
--* @author  SAKULIN Hannes  <hsakulin@dsy-srv3.cern.ch>
--* @date    $Date: 2005/01/31 15:17:29 $
--* @version $Revision: 1.6 $
--******************************************************************************
--/
library IEEE;
use IEEE.Std_logic_1164.all;
use IEEE.Numeric_std.all;

entity LFDeltaPhiSub is
--  generic (
--    edge : std_logic := '1');
  port (
    phi1, phi2 : in std_logic_vector (7 downto 0);
    dphi       : out std_logic_vector (2 downto 0)
    
--    clk : std_logic
    );  
  
end entity LFDeltaPhiSub;

-------------------------------------------------------------------------------
-- Synplify synthesis of the below architecture looks fine
-- about 10 ns delays w/o nets
-- Synplify even detects that only the upper 4 bits are needed
-- in the +/- 144 adders
-------------------------------------------------------------------------------


architecture behavioral of LFDeltaPhiSub is
  
  signal delta  : signed(8 downto 0);
  signal delta1 : signed(8 downto 0);
  signal delta2 : signed(8 downto 0);

  signal delta_out : signed(8 downto 0);

begin  -- architecture behavioral

  delta  <= SIGNED(resize( UNSIGNED(phi1), 9)) -SIGNED(resize( UNSIGNED(phi2), 9));
  delta1 <= SIGNED(resize( UNSIGNED(phi1), 9)) -SIGNED(resize( UNSIGNED(phi2), 9)) - TO_SIGNED(144,9);
  delta2 <= SIGNED(resize( UNSIGNED(phi1), 9)) -SIGNED(resize( UNSIGNED(phi2), 9)) + TO_SIGNED(144,9);

  delta_out <= delta1 when (delta>TO_SIGNED(72,9)) else
               delta2 when (delta<TO_SIGNED(-72,9)) else
               delta;

  -- reduce to 3 bit representing -3 to 3
  -- overflow is coded as -4 ("100" bin)

  -- register output
--   outp: process (clk) is

--   begin  -- process outp
--     if (clk'event and clk=edge) then
--       if (delta_out >= TO_SIGNED (3,9) or delta_out <= TO_SIGNED (-3,9) ) then
--         dphi <= std_logic_vector(TO_SIGNED(-4,3));
--       else
--         dphi <= ( std_logic_vector(delta_out(8 downto 8)) &
--                 std_logic_vector(delta_out(1 downto 0)) );
--       end if;
--     end if;    
--   end process outp;

  dphi <= std_logic_vector(TO_SIGNED(-4,3)) when (delta_out >= TO_SIGNED (3,9) or delta_out <= TO_SIGNED (-3,9) )
                          else ( std_logic_vector(delta_out(8 downto 8)) & std_logic_vector(delta_out(1 downto 0)) );

end architecture behavioral;