`timescale 1ns / 1ps

// VGA Pong v1.0     Chris Fallin <cfallin@nd.edu>

module vga_sync(clk_50MHz, reset, hsync, vsync, hpos, vpos, active);
	input clk_50MHz;
	input reset;
	output hsync;
	output vsync;
	output [9:0] hpos;
	output [9:0] vpos;
	output active;

	wire hsync;
	wire vsync;
	reg [9:0] hpos;
	reg [9:0] vpos;
	wire active;
	
	wire active_h, active_v;
	
	/*
	  The sync patterns for 640x480 @ 60Hz (from the Basys board manual) are:
	  
	  H: (50Mhz pixel clock)
		0 - 639: active
		640 - 687: front porch
		688 - 783: H sync pulse (low)
		784 - 799: back porch
		
	  V: (clocked from H sync pulse)
	   0 - 479: active
		480 - 489: front porch
		490 - 491: V sync pulse (low)
		492 - 520: back porch
	*/
	
	reg clk; // 25 MHz pixel clock
	
	always @(posedge clk_50MHz)
		clk <= ~clk;
	
	// H counter
	always @(posedge clk or posedge reset) begin
		
		if(reset == 1) begin
			hpos <= 0;
			vpos <= 0;
		end
		else
		// counter modulo 800
		if(hpos == 799) begin
			hpos <= 0;
			
			// V counter, driven by H counter rollover
			if(vpos == 520)
				vpos <= 0;
			else
				vpos <= vpos + 1;
		end
		else
			hpos <= hpos + 1;
	end
	
	// H sync
	assign hsync = ~ (hpos >= 656 && hpos < 752);
	//assign hsync = ~ (hpos >= 688 && hpos <= 783);
	
	// V sync
	assign vsync = ~ (vpos == 490 || vpos == 491);
	
	// H blank
	assign active_h = (hpos < 640);
	
	// V blank
	assign active_v = (vpos < 480);

	// blanking
	assign active = active_h & active_v;

	// setup
	initial begin
		vpos <= 0;
		hpos <= 0;
	end

endmodule
