library ieee;
use ieee.std_logic_1164.all;

entity byte_reg is
	port (
		clk, rst : in std_logic;
		clr_flag, set_flag : in std_logic;
		data_in : in std_logic_vector (7 downto 0);
		data_out : out std_logic_vector (7 downto 0);
		flag : out std_logic
	);
end byte_reg;

architecture arch of byte_reg is
	signal curr_buff, next_buff : std_logic_vector (7 downto 0); -- signals for current and next byte
	signal curr_flag, next_flag : std_logic; -- signals for current and next flag
	
	begin
	process (clk)
		begin
		if rising_edge(clk) then
			if(rst = '1') then -- reset all signals
				curr_buff <= (others => '0');
				curr_flag <= '0';
			else -- set current signals to their next values
				curr_buff <= next_buff;
				curr_flag <= next_flag;
			end if;
		end if;
	end process;

	process (curr_buff, curr_flag, set_flag, clr_flag, data_in) -- for updating values
		begin
		-- defensively define the values for next_buff and next_flag
		next_buff <= curr_buff;
		next_flag <= curr_flag;
		if (set_flag = '1') then -- a new data value is available
			next_buff <= data_in; -- store the byte
			next_flag <= '1'; -- set the flag
		elsif (clr_flag = '1') then -- the processor wants to clear the flag
			next_flag <= '0'; -- clear the flag
		end if;
	end process;

	-- output logic
	data_out <= curr_buff;
	flag <= curr_flag;
end arch;