module hotplug_decode(
    input  clk,
    input  hpd,
    output reg irq,
    output reg present
);

   reg hpd_meta1;   // TODO Should also set ASYNC_REG
   reg hpd_meta2;   // TODO Should also set ASYNC_REG
   reg hpd_synced;
   reg hpd_last;

   reg [17:0] pulse_count;


initial begin
    hpd_meta1    = 1'b0;
    hpd_meta2    = 1'b0;
    hpd_synced   = 1'b0;
    hpd_last     = 1'b1;
    pulse_count  = 18'b0;
    present      = 1'b0;
    irq          = 1'b0;
end 

always @(posedge clk) begin
    irq <= 1'b0;
    if(hpd_last == 1'b0) begin
        if(hpd_synced == 1'b0) begin
            if(pulse_count == 200000) begin  // TODO - should not be a constant!
                //--------------------------------
                // Sink has gone away for over 2ms
                // No longer present
                //--------------------------------
                present <= 1'b0;
            end else begin
                pulse_count <= pulse_count + 1;
            end
        end else begin
            //----------------------------------------
            // Timing the pulse to see if it is an IRQ
            //----------------------------------------
            if(pulse_count > 100000) begin  // TODO - should not be a constant!
                //-----------------------------------
                // Signal is back, but less than 2ms
                // so signal an IRQ...
                //-----------------------------------
                if(present == 1'b1) begin
                  irq <= present;
                end
            end
            pulse_count = 18'b0;
        end
    end else begin
        if(hpd_synced == 1'b0) begin
            pulse_count = 18'b0;            // Flip to other state
        end else begin
            if(pulse_count == 220000) begin
                present <= 1'b1;                // Pulse seen long enough to be valid
            end else begin
                pulse_count <= pulse_count + 1; // Time till the signal is valid for > 2ms
            end
        end
    end
    hpd_last   <= hpd_synced;
    hpd_synced <= hpd_meta1;
    hpd_meta1  <= hpd_meta2;
    hpd_meta2  <= hpd;
end
endmodule