//
// deglitch.v
//


module deglitch_bit (
		 input rst_n,
		 input clk,

		 input d,
		 output reg q
		 );

   parameter cbits = 2;		// need 2^cbits same signals in a row

   reg d_reg;
   reg [cbits-1:0] ctr;

   always @(posedge clk or negedge rst_n)
     if (~rst_n)
       begin
	  d_reg <= d;
	  q <= d_reg;
	  ctr <= {(cbits){1'b0}};
       end
     else
       begin
	  d_reg <= d;

	  if (d_reg ^ q)
	    begin
	       if (&ctr)
		 q <= d_reg;

	       ctr <= ctr + 1'b1;
	    end
	  else
	    begin
	       if (|ctr)
		 ctr <= ctr - 1'b1;
	    end // else: !if(d_reg ^ q)
       end // else: !if(~rst_n)
endmodule // deglitch_one

module deglitch #(parameter width = 1, parameter cbits = 2) (
		 input rst_n,
		 input clk,

		 input [width-1:0] d,
		 output [width-1:0] q
		 );

   generate
      genvar i;

      for (i = 0; i < width; i = i+1)
	begin : genbit
	   deglitch_bit #(.cbits(cbits)) dg
	       (
		.rst_n ( rst_n ),
		.clk   ( clk ),
		.d     ( d[i] ),
		.q     ( q[i] )
		);
	end
   endgenerate
endmodule
