module rgb_op0(

(* X_INTERFACE_INFO = "xilinx.com:interface:vid_io:1.0 iV ACTIVE_VIDEO" *) input wire       iRGB_ACTIVE,
(* X_INTERFACE_INFO = "xilinx.com:interface:vid_io:1.0 iV DATA" *)         input wire [23:0]iRGB_DATA  ,
(* X_INTERFACE_INFO = "xilinx.com:interface:vid_io:1.0 iV HSYNC" *)        input wire       iRGB_HSYNC ,
(* X_INTERFACE_INFO = "xilinx.com:interface:vid_io:1.0 iV VSYNC" *)        input wire       iRGB_VSYNC ,


(* X_INTERFACE_INFO = "xilinx.com:interface:vid_io:1.0 oV ACTIVE_VIDEO" *) output wire       oRGB_ACTIVE,
(* X_INTERFACE_INFO = "xilinx.com:interface:vid_io:1.0 oV DATA" *)         output wire [23:0]oRGB_DATA  ,
(* X_INTERFACE_INFO = "xilinx.com:interface:vid_io:1.0 oV HSYNC" *)        output wire       oRGB_HSYNC ,
(* X_INTERFACE_INFO = "xilinx.com:interface:vid_io:1.0 oV VSYNC" *)        output wire       oRGB_VSYNC ,

output wire  [15:0] cnt_iac,
output wire  [15:0] cnt_ihs,
output wire  [15:0] cnt_ivs,

input  wire  [1:0] isel ,
input  wire  hdmi_in_aPixelClkLckd  ,
input  wire  hdmi_out_aPixelClkLckd ,
output wire  hdmi_in_arst           ,
output wire  hdmi_out_arst          ,
input  wire  clk                    ,
input  wire  PixelClk               ,
input  wire  tx_hpd                 ,
output wire  rx_hpd


);


reg [ 7:0] r_hpd_fsm0=0;

reg [15:0] r_cnt_iac;
reg [15:0] r_cnt_ihs;
reg [15:0] r_cnt_ivs;

reg r_iRGB_ACTIVE;
reg r_iRGB_HSYNC ;
reg r_iRGB_VSYNC ;

assign cnt_iac = r_cnt_iac;
assign cnt_ihs = r_cnt_ihs;
assign cnt_ivs = r_cnt_ivs;

always@(posedge PixelClk ) begin

r_iRGB_ACTIVE <= iRGB_ACTIVE;
r_iRGB_HSYNC  <= iRGB_HSYNC ;
r_iRGB_VSYNC  <= iRGB_VSYNC ;

r_cnt_iac <= (~iRGB_ACTIVE)? 0: (&r_cnt_iac)? r_cnt_iac: r_cnt_iac+1;
r_cnt_ihs <= (~iRGB_HSYNC )? 0: (&r_cnt_ihs)? r_cnt_ihs: r_cnt_ihs+1;
r_cnt_ivs <= (~iRGB_VSYNC )? 0: (&r_cnt_ivs)? r_cnt_ivs: ( {r_iRGB_HSYNC,iRGB_HSYNC}==2'b01 )? r_cnt_ivs+1: r_cnt_ivs;

end

always@(posedge clk) begin
r_hpd_fsm0 <=

//delay done. check if hdmi_in is still locked
(&r_hpd_fsm0 && hdmi_in_aPixelClkLckd )? r_hpd_fsm0:
//if not locked goto 0 (retry)
(&r_hpd_fsm0 )? 0:

//start
(r_hpd_fsm0==0 )? 1:

//waits for hdmi_in 
(r_hpd_fsm0==1 && hdmi_in_aPixelClkLckd )? 2: 

//waits for hdmi_out 
(r_hpd_fsm0==2 && hdmi_out_aPixelClkLckd && tx_hpd)? 3: 

//delay, so that retry is not so quick                                          
(r_hpd_fsm0>=3 )? r_hpd_fsm0+1:

r_hpd_fsm0;

end

assign hdmi_in_arst  = (r_hpd_fsm0>=1)? 0: 1;
assign rx_hpd        = (r_hpd_fsm0>=1)? 1: 0;
assign hdmi_out_arst = (r_hpd_fsm0>=2)? 0: 1; 

assign oRGB_ACTIVE = iRGB_ACTIVE;
assign oRGB_DATA[8*0+:8] =(isel[0])? ~iRGB_DATA[8*0+:8] : iRGB_DATA[8*0+:8];
assign oRGB_DATA[8*1+:8] =(isel[0])? ~iRGB_DATA[8*1+:8] : iRGB_DATA[8*1+:8];
assign oRGB_DATA[8*2+:8] =(isel[0])? ~iRGB_DATA[8*2+:8] : iRGB_DATA[8*2+:8];
assign oRGB_HSYNC  = iRGB_HSYNC ;
assign oRGB_VSYNC  = iRGB_VSYNC ;
 
endmodule
