
-- file #1: D_FF.vhd

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

entity D_FF is
     Port( 
      clock : in  STD_LOGIC;
      R     : in  STD_LOGIC;
      D     : in  STD_LOGIC;
		
      Q     : out  STD_LOGIC
     );
end D_FF;

architecture Structural of D_FF is

begin

process(R, clock)
begin
	if (R = '1') then
	     Q <= '0';
	elsif rising_edge(clock) then
	     Q <= D;
	end if;
end process;

end Structural;

-- file #2 : counter.vhd

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

entity Counter is
     Port(
      clock : in  STD_LOGIC;
      R     : in  STD_LOGIC;
		
      count : out  STD_LOGIC_VECTOR (2 downto 0)
     );
end Counter;

architecture Structural of Counter is

component D_FF is
     Port(
      clock : in  STD_LOGIC;
      R     : in  STD_LOGIC;
      D     : in  STD_LOGIC;
		
      Q     : out  STD_LOGIC
      );
end component;

signal feedback	: STD_LOGIC_VECTOR(2 downto 0);
signal Q        : STD_LOGIC_VECTOR(2 downto 0);

begin

registers : for i in 0 to 2 generate
begin
	
     flip_flops : component D_FF
	Port Map(
	 clock	=> clock,
	 R	=> R,
	 D	=> feedback(i),
			
	 Q	=> Q(i)
	);
			
end generate;


feedback(0) <= not Q(0);
feedback(1) <= ((not Q(1)) and Q(0)) or (Q(1) and (not Q(0)));
feedback(2) <= ((not Q(1)) and Q(2)) or ((not Q(0)) and Q(2)) or ((not Q(2)) and Q(1) and Q(0));

count <= Q;

end Structural;
