//******************************************************************************************
    //*  COMPANY    :  TERASIC.  www.terasic.com  (c) 2005 all rights reserved.                *
    //*  NAME       :  dual port RAM control
    //*  Created    :  7/5/2005                                                                *
    //*  Author     :  Joe Yang                                                                *
    //******************************************************************************************

module dul_port_c1024(
	iDATA,
	iHSYNC,
	iHSYNCx2,
	Y_CLOCK,
	Y_CLOCKx2,
	VS,
	oDATA,
	field
	//test
/*
	counter,
	I,
	COUNTER_a,
    COUNTER_b,
    CLOCK_a,
    CLOCK_b,
	I_a,
	I_b
*/
);

input  [7:0]iDATA;
input  iHSYNC;
input  iHSYNCx2;
input  Y_CLOCK;
input  Y_CLOCKx2;
input  field;
input  VS;
output [7:0]oDATA;
/*
output [9:0]counter;
output I;
output [9:0]COUNTER_a;
output [9:0]COUNTER_b;
output CLOCK_a;
output CLOCK_b;
output I_a;
output I_b;
*/
reg I;
always@(negedge iHSYNC)begin
	if (VS) 
		I=field;
	else
		I=~I;
end

reg  [9:0]counter;
always@(posedge iHSYNC or posedge Y_CLOCK)begin
if (iHSYNC)
	 counter=0;
else counter=counter+1;
end
 
reg  [9:0]counterx2;
always@(negedge iHSYNCx2 or posedge Y_CLOCKx2)begin
if (!iHSYNCx2)
	 counterx2=0;
else counterx2=counterx2+1;
end

wire [7:0]DATA_a,DATA_b; 
wire I_a= I;
wire I_b=~I;
wire [9:0]COUNTER_a=(I==1)?counter:counterx2;
wire [9:0]COUNTER_b=(I==0)?counter:counterx2;
wire CLOCK_a=(I==1)?~Y_CLOCK:~Y_CLOCKx2;
wire CLOCK_b=(I==0)?~Y_CLOCK:~Y_CLOCKx2;
wire [7:0]oDATA=(I==0)?DATA_a:DATA_b;


RAM2 u(
	.data_a(iDATA[7:0]),
	.wren_a(I_a),
	.address_a(COUNTER_a[9:0]),
	.clock_a(CLOCK_a),
	.q_a(DATA_a[7:0]),
	
	.data_b(iDATA[7:0]),
	.wren_b(I_b),
	.address_b(COUNTER_b[9:0]),
	.clock_b(CLOCK_b),
	.q_b(DATA_b[7:0])
	);
	
endmodule