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

entity vga_timing is
	port(
		clk: in std_logic;
		rst: in std_logic;
		HS: out std_logic;
		VS: out std_logic;
		pixel_x: out std_logic_vector(9 downto 0);
		pixel_y: out std_logic_vector(9 downto 0);
		last_column: out std_logic;
		last_row: out std_logic;
		blank: out std_logic
	);
end vga_timing;

architecture behavior of vga_timing is
	signal pixel_en: std_logic := '0';
	signal column: unsigned(9 downto 0);
	signal column_next: unsigned(9 downto 0);
	signal row: unsigned(9 downto 0);
	signal row_next: unsigned(9 downto 0);
begin
	-- pixel clock
	process(clk, rst)
	begin
		if(rst = '1') then
			pixel_en <= '0';
		elsif(clk'event and clk='1') then
			pixel_en <= not pixel_en;
		end if;
	end process;				
	
	-- register for HS counter
	process(rst,clk)
	begin
		if(rst = '1') then
			column <= (others=>'0');
		elsif(clk'event and clk = '1') then
			if(pixel_en = '1') then
				column <= column_next;
			end if;
		end if;
	end process;
	-- next state HS counter
	column_next <= (others=>'0') when column = 799 else
								column + 1;
	-- output logic for HS counter
	last_column <= '1' when column = 639 else
						'0';
	HS <= '0' when ((column > 655) and (column < 752)) else 
			'1';	
	pixel_x <= std_logic_vector(column);
	
	
	-- register for VS counter
	process(rst,clk, pixel_en, column)
	begin
		if(rst = '1') then
			row <= (others=>'0');
		elsif(clk'event and clk = '1') then
			if(pixel_en = '1' and column = 799) then			--   only increment if HS is 799 and the pixel enable is high
				row <= row_next;
			end if;
		end if;
	end process;
	-- next state VS counter
	row_next <= (others=>'0') when row = 520 else
								row + 1;
	-- output logic for VS counter
	last_row <= '1' when row = 479 else 
					'0';
	VS <= '0' when ((row > 489) and (row < 492)) else						
					'1';
	pixel_y <= std_logic_vector(row);
	
	-- blank signal
	blank <= '1' when (row > 479) or (column > 639) else
				'0';
				
end behavior;