--
-- bunch_mean_acc.vhd
--
-- Version 1.0 15/10/07 A.McCormick (Alpha Data)
--
-- Bunch mean accumulator
-- Sums sigma, deltax and deltay values over a ms
-- and ouputs the sum


library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_signed.all;
use ieee.std_logic_arith.all;
use ieee.std_logic_misc.all;

library work;
use work.common_interface.all;


entity bunch_mean_acc is
  
  
  port (
    clk : in std_logic;
    acc : in std_logic;
    clr : in std_logic;
    sigma  : in std_logic_vector(15 downto 0);
    deltax : in std_logic_vector(15 downto 0);
    deltay : in std_logic_vector(15 downto 0);
    sum_sigma : out std_logic_vector(31 downto 0);
    sum_deltax : out std_logic_vector(31 downto 0);
    sum_deltay : out std_logic_vector(31 downto 0);
    count  : out std_logic_vector(31 downto 0));

end bunch_mean_acc;

architecture rtl of bunch_mean_acc is

  signal ss,sdx,sdy : std_logic_vector(31 downto 0);
  signal icount : std_logic_vector(15 downto 0);

  signal acc_reg : std_logic;
  signal sigma_reg,deltax_reg,deltay_reg : std_logic_vector(31 downto 0);
  
begin  -- rtl

  accumulate: process (clk)
  begin  -- process accumulate
    if clk'event and clk = '1' then  -- rising clock edge
      acc_reg <= acc;
      sigma_reg <= SXT(sigma,32);
      deltax_reg <= SXT(deltax,32);
      deltay_reg <= SXT(deltay,32);          
      if clr = '1' then
        sum_sigma <= ss;
        sum_deltax <= sdx;
        sum_deltay <= sdy;
        count <= X"0000" & icount;
        if acc_reg = '0' then
          ss <= (others => '0');
          sdx <= (others => '0');
          sdy <= (others => '0');
          icount <= (others => '0');
        else
          icount <= CONV_STD_LOGIC_VECTOR(1,16); 
          ss <= sigma_reg;
          sdx <= deltax_reg;
          sdy <= deltay_reg;
        end if;
      else
        if acc_reg = '1' then
          icount <= icount+1; 
          ss <= ss + sigma_reg;
          sdx <= sdx + deltax_reg;
          sdy <= sdy + deltay_reg;
        end if;
      end if;
    end if;
  end process accumulate;
  
end rtl;
