library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;

entity VGADriver is
    Port ( Clk : in  STD_LOGIC;
           RGBIn : in  STD_LOGIC_VECTOR (2 downto 0);
			  RGBOut: out STD_LOGIC_VECTOR (2 downto 0);
           VideoActive : out  STD_LOGIC;
           HAddr, VAddr : out  STD_LOGIC_VECTOR (9 downto 0);
           HSOut, VSOut : out  STD_LOGIC := '1');
end VGADriver;


architecture Behavioral of VGADriver is
	SIGNAL HActive, VActive, Active : STD_LOGIC;
	SIGNAL HSync, VSync : STD_LOGIC;
begin
	process(Clk) 
      VARIABLE HCount : integer range 0 to 799 := 0;
		VARIABLE VCount : integer range 0 to 520 := 0;
	begin
		if Clk'event AND Clk = '1' then
			-- horizontální čítač
			if HCount >= 799 then HCount := 0; 
			else HCount := HCount + 1;
			end if;
			
			-- generování adresy pixelu v řádku pro pamě
			if HCount >= 640 then HAddr <= "0000000000";
			else HAddr <= conv_std_logic_vector(HCount,10);
			end if;
			
			-- příznak aktivního běhu v řádku
			if HCount >= 640 AND HCount <= 798 then HActive <= '0';
			else HActive <= '1';
			end if;
		
			-- horizontální synchronizace
			if HCount >= 655 AND HCount <= 751 then HSync <= '0';
			else HSync <= '1';
			end if;
		
			-- vertikalní čítač
			if HCount >= 799 AND VCount >= 520 then VCount := 0;
			elsif HCount >= 799 then VCount := VCount + 1;
			end if;
		
			-- generování adresy řádku pro pamě
	   	if VCount >= 480 then VAddr <= "0000000000";
			else VAddr <= conv_std_logic_vector(VCount, 10);
			end if;
			
			-- příznak aktivního běhu ve snímku
			if VCount >= 480 AND VCount <= 519 then VActive <= '0';
			else VActive <= '1';
			end if;
			
			-- vertikální synchronizace
			if VCount >= 489 AND VCount <= 491 then VSync <= '0';
			else VSync <= '1';
			end if;
      end if;
	end process;
	
	-- výstup hodnot pro řízení monitoru

	Active <= HActive AND VActive;
	VideoActive <= Active;
	RGBOut <= RGBIn when Active = '1' else "000";
	HSOut <= HSync;
	VSOut <= VSync;

end Behavioral;
