library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;


-- Entity declaration
-- The inputs and outputs of the entity are exactly the inputs and output of the
-- top-level node of the model, and they have the same names.
entity RTflowCode is
   port(
      enable : in std_logic;
      count : out integer;
      clk : in std_logic
   );
end RTflowCode;

architecture RTflowCode of RTflowCode is
   -- All the signals arrays
   signal b : std_logic_vector(1-1 downto 0);
   type int_array is array(6-1 downto 0) of integer;
   signal i : int_array;

   -- Reset array - see comments for the reset array process below
   signal reset_array : std_logic_vector(3 downto 0) := (others => '0');
begin

   -- Reset array process
   -- The purpose of this process is to avoid race conditions during initalization of
   -- the chip. This is accomplished by keeping all signals in their intial state for
   -- the first four clock cycles. This process produces a four-bit array whose
   -- contents will be "0000", "1000", "1100", "1110" for the first four clock cycles,
   -- and from the fifth cycle and on, it will be "1111". In the state update process
   -- below, all signals are reset whenever this array is not "1111".
   process (clk)
   begin
      if clk'event and clk = '1' then
         reset_array <= '1' & reset_array(3 downto 1);
      end if;
   end process;

   -- Input synchronization and mapping process
   -- This process copies the inputs declared in the entity to the corresponding
   -- elements of the arrays, where they will be manipulated by the state update
   -- process. At the same time, the inputs are synchronized in order to minimize
   -- the risk for race conditions.
   process (clk)
   begin
      if clk'event and clk = '1' then
         b(0) <= enable;
      end if;
   end process;

   -- State update process
   -- This process generates a set of clocked registers, corresponding to all Pre
   -- blocks in the model. The first four cycles, the registers are forced to
   -- their initial values.
   process (clk)
   begin
      if clk'event and clk = '1' then
         if reset_array = "1111" then
            -- Update state
            i(5) <= i(0);            -- Pre1 <= count;
         else
            -- Reset state
            i(5) <= 0;               -- Pre1 <= 0;
         end if;
      end if;
   end process;

   -- Combinatorial part
   -- These statements constitute the complete combinatorial network, corresponding
   -- to all blocks except for Pre blocks in the model.
   i(2) <= i(5);            -- pre_count <= Pre1;
   i(3) <= 1;               -- v1 <= 1;
   i(4) <= 0;               -- v0 <= 0;
   i(1) <= i(2) + i(3);     -- sum <= pre_count + v1;
   i(0) <= i(1) when b(0) = '1' else i(4);-- count <= sum when enable = '1' else v0;

   -- Output map
   -- These statements copy the produced output values residing in the arrays to
   -- the outputs declared in the entity.
   count <= i(0);

end RTflowCode;