module PipPositionAdj(
	input  iVS,
	input  iCLOCK,
	input  iDEMO,

	input  [9:0]iVGA_R,
	input  [9:0]iVGA_G,
	input  [9:0]iVGA_B,

	output [9:0]oVGA_R,
	output [9:0]oVGA_G,
	output [9:0]oVGA_B,
	
	output reg oMemON,
	input  [7:0]iXoffest,
	input  [7:0]iYoffset,
	output oDispPiP,
	input [10:0]iX,
	input [10:0]iY,
	input [10:0]iPosition_X,
	input [10:0]iPosition_Y

);


  reg [10:0]delay;
  reg [10:0]Xofset_x;
  reg [10:0]Yofset_y;

  always @(posedge iVS)
  begin 
		delay=delay+1;
  end


  wire [10:0]Xofset_X =312; //0~320
  wire [10:0]Yofset_Y =220; //0~120


  wire [10:0]Xofset=(!iDEMO)?Xofset_X:iXoffest;
  wire [10:0]Yofset=(!iDEMO)?Yofset_Y:iYoffset;
	
reg tr,tr_np;

always @( posedge iCLOCK)
tr=(
		(iX[10:0]>= (Xofset[10:0]             +5 ))&&
		(iX[10:0]<  (Xofset[10:0]+ iPosition_X + 5 ))&& 
		(iY[10:0]>= Yofset[10:0])&&
		(iY[10:0]<  (Yofset[10:0]+iPosition_Y)-1) 
		)?1:0;

always @( posedge iCLOCK)
tr_np=(
		(iX[10:0]>= (Xofset[10:0]+ 9 ))&&
		(iX[10:0]<  (Xofset[10:0]+ iPosition_X + 1 ))&& 
		(iY[10:0]>= (Yofset[10:0]+ 5))&&
		(iY[10:0]<  (Yofset[10:0]- 5    + iPosition_Y)-1)
		)?1:0;


 assign oVGA_R =((tr) && (tr_np))?iVGA_R :10'h3ff;
 assign oVGA_B=((tr) && (tr_np))?iVGA_B:10'h3ff;
 assign oVGA_G=((tr) && (tr_np))?iVGA_G:10'h3ff;


reg    tr_all;		
assign oDispPiP = tr;
always @(posedge iVS or posedge iCLOCK) begin
if     	( iVS )  
	tr_all=1;
else if (tr) 
	tr_all=0;
end


//=======================================================
//			 PIP trigger process
//=======================================================
reg [7:0]PIPdelay;
always @( posedge  tr_all or posedge  iCLOCK)begin
if (  tr_all )
begin
	oMemON=0;
	PIPdelay=0;
end
	else begin 
		if (!PIPdelay[7]) 
			PIPdelay <= PIPdelay+1;
		if (PIPdelay==1 ) 
			oMemON=1;  
			else 
				oMemON=0;
	end 
end


endmodule 