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

entity scrolling_buffer is
    port(
        clk : in std_logic;
        rst : in std_logic;
        buffer_clear : in std_logic;
        buffer_write : in std_logic;
        buffer_data : in std_logic_vector(4 downto 0);
        next_char : in std_logic;
        hex_char : out std_logic_vector(4 downto 0);
        elements : out std_logic_vector(4 downto 0)
    );
end entity scrolling_buffer;

architecture Behavioral of scrolling_buffer is

    constant BUFFER_SIZE : integer := 16; 

    type ring_buffer_type is array (0 to BUFFER_SIZE - 1) of std_logic_vector(4 downto 0);
    signal ptr_write : integer range 0 to BUFFER_SIZE - 1;
    signal ptr_read : integer range 0 to BUFFER_SIZE - 1;
    signal ptr_last : integer range -1 to BUFFER_SIZE - 1;
    
    signal ring_buffer : ring_buffer_type;

begin

	process(clk)
	begin
		if clk'event and clk='1' then
			if rst = '1' then
                ptr_last <= -1;
                ptr_write <= 0;
                ring_buffer <= (others => (others => '0'));
                elements <= (others => '0');
            else
                if buffer_write = '1' then
                    ring_buffer(ptr_write) <= buffer_data;
                    
                    if ptr_last /= BUFFER_SIZE - 1 then
                        ptr_last <= ptr_write;
                        elements <= std_logic_vector(to_unsigned(ptr_write + 1, 5));
                    end if;

                    if ptr_write = BUFFER_SIZE - 1 then
                        ptr_write <= 0;
                    else
                        ptr_write <= ptr_write + 1;
                    end if;
                elsif buffer_clear = '1' then
                    ptr_last <= -1;
                    ptr_write <= 0;
                    elements <= (others => '0');
                    ring_buffer <= (others => (others => '0'));
                end if;
            end if;
		end if;
	end process;

    process(clk)
	begin
		if clk'event and clk='1' then
			if rst = '1' then
                ptr_read <= 0;
                hex_char <= (others => '1');
            else
                if ptr_last = -1 then -- Special case
                    hex_char <= (others => '1');
                else
                    hex_char <= ring_buffer(ptr_read);
                end if;
                
                if buffer_clear = '1' then
                    ptr_read <= 0;
                elsif next_char = '1' then    
                    if ptr_read = ptr_last then
                        ptr_read <= 0;
                    else
                        ptr_read <= ptr_read + 1;
                    end if;
                end if;
            end if;
		end if;
	end process;

end Behavioral;
