-- Quartus II VHDL Template
-- Binary Counter

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

entity test_mp2_1 is

	port
	(
		clk		  	: in std_logic;
		reset			: in std_logic;
	
		i0				: out std_logic_vector(3 downto 0);
		i1				: out std_logic_vector(3 downto 0);
		s0				: out std_logic;
		
		y				: in std_logic_vector(3 downto 0);
	
		ok				: out std_logic
	);

end entity;

architecture rtl of test_mp2_1 is
	signal   cnt: integer range 0 to 511:=0;
	signal   cnt_next: integer range 0 to 511:=0;
	signal	i0_out:std_logic_vector(3 downto 0):= (others=>'0');
	signal	i1_out:std_logic_vector(3 downto 0):= (others=>'0');
	signal	s0_out:std_logic:='0';
	signal	ok_next: std_logic:='1';
	signal	ok_out: std_logic:='1';
	
begin

	process (clk)
	variable cnt_next:integer range 0 to 511;
	begin
	
	
	if (rising_edge(clk)) then
		if reset='1' then
			ok_out<='1';
			cnt<=0;
			cnt_next:=0;
		else
			cnt<=cnt_next;
			ok_out<=ok_out and ok_next;
			cnt_next:=cnt_next+1;
		end if;
	end if;
	end process;
	
	process (y,i0_out,i1_out,s0_out) 
		variable res:std_logic_vector(3 downto 0);
	begin
		if s0_out='1' then
			res:=i1_out;
		else
			res:=i0_out;
		end if;
	
		if unsigned(y)=unsigned(res) then
			ok_next<='1';
		else
			ok_next<='0';
		end if;
	end process;
	
	i0_out<=std_logic_vector(to_unsigned(cnt, 9))(3 downto 0);
	i1_out<=std_logic_vector(to_unsigned(cnt, 9))(7 downto 4);
	s0_out<=std_logic_vector(to_unsigned(cnt, 9))(8);
	
	i0<=std_logic_vector(to_unsigned(cnt, 9))(3 downto 0);
	i1<=std_logic_vector(to_unsigned(cnt, 9))(7 downto 4);
	s0<=std_logic_vector(to_unsigned(cnt, 9))(8);	
	ok<=ok_out;

end rtl;
