-- Quartus II VHDL Template
-- Binary Counter

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

entity test_reg4 is

	port
	(
		clk		  	: in std_logic;
		reset			: in std_logic;
	
		I				: out std_logic_vector(3 downto 0);
		ld				: out std_logic;
		dec			: out std_logic;
		
		
		A				: in std_logic_vector(3 downto 0);
		
		state			: out std_logic_vector(3 downto 0);
	
		ok				: out std_logic
	);

end entity;

architecture rtl of test_reg4 is
	signal   cnt: integer range 0 to 63;
	signal	I_out:std_logic_vector(3 downto 0);
	signal	ld_out:std_logic:='0';
	signal	dec_out:std_logic:='0';
	signal	ok_next: std_logic:='1';
	signal	ok_out: std_logic:='1';
	
	signal  bad_test_input:std_logic;
	
	signal my_state:std_logic_vector(3 downto 0):=(others=>'0');
	signal my_state_next:std_logic_vector(3 downto 0):=(others=>'0');
	
begin

	process (clk)
	variable cnt_next:integer range 0 to 100000;
	begin
	
	
	if (rising_edge(clk)) then
		if reset='1' then
			ok_out<='1';
			cnt<=0;
			cnt_next:=0;
			my_state<=(others=>'0');
		else
			cnt<=cnt_next;
			my_state<=my_state_next;
			ok_out<=ok_out and ok_next;
			--cnt_next:= cnt_next+1;
			cnt_next:=to_integer(unsigned(std_logic_vector(to_unsigned(cnt * 1103515245 + 12345, 17) and "11111111111111111")));
		end if;
	end if;
	end process;
	
	process (A,I_out,ld_out,dec_out,bad_test_input) 
		variable res:std_logic_vector(3 downto 0);
		
	begin
		if ld_out='1' then
			my_state_next<=I_out;
		elsif dec_out='1' then
			my_state_next<=  std_logic_vector(to_unsigned(to_integer(unsigned( my_state)-1 ),4));
		else
			my_state_next<=my_state;
		end if;
		
	if bad_test_input='1' then 
		ok_next<='1';
	else
		if unsigned(A)=unsigned(my_state) then
			ok_next<='1';
		else
			ok_next<='0';
		end if;
	end if;
	end process;
	
	I<=std_logic_vector(to_unsigned(cnt, 6))(3 downto 0);
	process (cnt)
	begin
	if std_logic_vector(to_unsigned(cnt, 6))(4)='1' and std_logic_vector(to_unsigned(cnt, 6))(5)='1' then
		ld<='0';
		dec<='1';
		ld_out<='0';
		dec_out<='1';
	else
		ld<=std_logic_vector(to_unsigned(cnt, 6))(4);
		ld_out<=std_logic_vector(to_unsigned(cnt, 6))(4);
		dec<=std_logic_vector(to_unsigned(cnt, 6))(5);
		dec_out<=std_logic_vector(to_unsigned(cnt, 6))(5);
	end if;
	
	
	
	end process;
	

	
	I_out<=std_logic_vector(to_unsigned(cnt, 6))(3 downto 0);
	
	bad_test_input<=ld_out and dec_out;
	ok<=ok_out;
	state<=my_state;

end rtl;
