library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;

entity COUNT_ONES is
  port (INPUT : in std_logic_vector (3 downto 0);
        OUTPUT : out std_logic_vector (2 downto 0));
end COUNT_ONES;

architecture BEHAV of COUNT_ONES is
begin
  process (INPUT)
    variable COUNT : std_logic_vector (2 downto 0);
  begin
    COUNT := "000";
    for I in 3 downto 0 loop
      if (INPUT(I) = '1') then
        COUNT := COUNT + "1";
      end if;
    end loop;
    OUTPUT <= COUNT;
  end process;
end BEHAV;   

library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;
use work.all;

entity HIER_COUNT_ONES is
  port (INPUT : in std_logic_vector (11 downto 0);
        OUTPUT : out std_logic_vector (3 downto 0));
end HIER_COUNT_ONES;

architecture STRUCT of HIER_COUNT_ONES is
  signal COUNT : std_logic_vector (8 downto 0);
begin
  U1 : entity COUNT_ONES(BEHAV)
       port map (INPUT(11 downto 8), COUNT(8 downto 6));
  U2 : entity COUNT_ONES(BEHAV)
       port map (INPUT(7 downto 4), COUNT(5 downto 3));
  U3 : entity COUNT_ONES(BEHAV)
       port map (INPUT(3 downto 0), COUNT(2 downto 0));
  OUTPUT <= "0000" + COUNT(8 downto 6) + COUNT(5 downto 3) + COUNT(2 downto 0);
end STRUCT;