module TV_to_VGA (
			OSC_27,
			RESET,
 			VGA_BLANK,
			VGA_SYNC,
			VGA_HS,
 			VGA_VS,
 			HSx2,
 			TD_VS,
 			TD_HS
);
input		    OSC_27;
input			RESET;
input 			HSx2;
input 			TD_VS;
input 			TD_HS;
output 			VGA_BLANK;
output			VGA_SYNC;
output			VGA_HS;
output 			VGA_VS;


wire mTD_HSx2;
reg 	[10:0]L_COUNTER;//<<
reg 	[10:0]RL_COUNTER;//<<
wire 	sync_reset=(RL_COUNTER==9)?1:0;//<<
reg  	sync_en;//<<
reg  	[7:0]delay;//<<

reg		[9:0]	H_Cont;
reg		[9:0]	V_Cont;
reg				oVGA_H_SYNC;
reg				oVGA_V_SYNC;
reg				Pre_HS;
reg				Pre_VS;
reg				mACT_HS;
reg				mACT_VS;

always@(posedge OSC_27 or negedge sync_en)//<<
begin
	if(!sync_en)//<<
	begin
		Pre_HS		<=	0;
		mACT_HS		<=	0;
		H_Cont		<=	0;
		oVGA_H_SYNC	<=	0;
	end
	else
	begin
		Pre_HS	<=	HSx2;
		if({Pre_HS, HSx2}==2'b10)
		mACT_HS	<=	1;
		if(mACT_HS)
		begin
			//	H_Sync Counter
			if( H_Cont < 852 )
			H_Cont	<=	H_Cont+1;
			else
			begin
				H_Cont	<=	0;
				mACT_HS	<=	0;
			end
			//	H_Sync Generator
			if( H_Cont < 96 )
			oVGA_H_SYNC	<=	0;
			else
			oVGA_H_SYNC	<=	1;
		end
		else
		begin
			oVGA_H_SYNC	<=	0;
			H_Cont		<=	0;
		end
	end
end

always@(posedge OSC_27 or negedge sync_en)//<<
begin
	if(!sync_en)//<<
	begin
		Pre_VS		<=	1;
		mACT_VS		<=	0;
		V_Cont		<=	0;
		oVGA_V_SYNC	<=	0;
	end
	else
	begin
		Pre_VS	<=	TD_VS;
		if({Pre_VS,TD_VS}==2'b01)
		mACT_VS	<=	1;
		if( (H_Cont==1) && mACT_VS)
		begin
			//	V_Sync Counter
			if( V_Cont < 524 )
			V_Cont	<=	V_Cont+1;
			else
			V_Cont	<=	0;
			//	V_Sync Generator
			if(	V_Cont < 2 )
			oVGA_V_SYNC	<=	0;
			else
			oVGA_V_SYNC	<=	1;
		end
	end
end

assign	VGA_HS		=	oVGA_H_SYNC;
assign	VGA_VS		=	oVGA_V_SYNC;
assign	VGA_SYNC	=	1'b0;
assign	VGA_CLOCK	=	OSC_27;


//>>lock detector
always @(posedge TD_HS) begin
if (TD_VS) L_COUNTER=0;		  
			else L_COUNTER=L_COUNTER+1;
end			

always @(posedge TD_VS) begin
		RL_COUNTER=L_COUNTER;//1714
end	
always@(negedge sync_reset or posedge TD_VS) begin
if (!sync_reset)
	delay=0;
    else if (delay < 250)
	 delay=delay+1;
end	

always@(negedge sync_reset or negedge TD_VS) begin
if (!sync_reset)     
		sync_en=0; 
else if (delay < 100)
    sync_en=0; 
    else
	sync_en=1;
end
//<<

endmodule