library ieee;
use ieee.std_logic_1164.all;

entity Midi_interface is
	port (
		clk, rst : in std_logic;
		rx : in std_logic;
		clr_flag : in std_logic;
		data_out : out std_logic_vector (7 downto 0);
		status_out : out std_logic_vector (7 downto 0)
	);
end Midi_interface;

architecture arch of Midi_interface is
	component tick_counter
	port (
		clk, rst: in std_logic;
		tick: out std_logic
	);
	end component;
	
	component uart_rec
	port (
		clk, rst : in std_logic;
		rx : in std_logic;
		tick : in std_logic;
		data_ready : out std_logic;
		data_out : out std_logic_vector (7 downto 0)
	);
	end component;
	
	component byte_reg
	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 component;
	
	signal tick_sig, done_sig : std_logic;
	signal the_byte, dat, curr_out, next_out: std_logic_vector (7 downto 0);
	signal curr_stat, next_stat : std_logic_vector (7 downto 0);
	signal flag_sig : std_logic;
	
	begin

	ctr: tick_counter port map (clk, rst, tick_sig);
	uart: uart_rec port map (clk, rst, rx, tick_sig, done_sig, the_byte);
	reg: byte_reg port map (clk, rst, clr_flag, done_sig, the_byte, dat, flag_sig);

	process (flag_sig, dat, curr_out)
	begin
		next_out <= dat;
		next_stat <= "0000000" & flag_sig;
	end process;
	
	process (clk)
	begin
		if rst = '1' then
			curr_out <= (others => '0');
			curr_stat <= (others => '0');
		elsif rising_edge(clk) then
			curr_out <= next_out;
			curr_stat <= next_stat;
		end if;
	end process;
	
	data_out <= curr_out;
	status_out <= curr_stat;
end arch;