module maint_ctrl #(parameter TCQ = 100, tCK = 2500, nCK_PER_CLK = 2, MAINT_PRESCALER_PERIOD = 200000) (
	input clk,
	input rst,
	
	input dfi_init_complete,
	
	output maint_prescaler_tick
);

	function integer clogb2 (input integer size); // ceiling logb2
    begin
      size = size - 1;
      for (clogb2=1; size>1; clogb2=clogb2+1)
            size = size >> 1;
    end
	endfunction // clogb2
	
   localparam MAINT_PRESCALER_DIV = MAINT_PRESCALER_PERIOD/(tCK * nCK_PER_CLK);  // Round down.
	localparam MAINT_PRESCALER_WIDTH = clogb2(MAINT_PRESCALER_DIV + 1);
	localparam ONE = 1;
	
	// Maintenance and periodic read prescaler.  Nominally 200 nS.
	reg maint_prescaler_tick_r_lcl;
	reg [MAINT_PRESCALER_WIDTH-1:0] maint_prescaler_r;
	reg [MAINT_PRESCALER_WIDTH-1:0] maint_prescaler_ns;
	
	wire maint_prescaler_tick_ns = (maint_prescaler_r == ONE[MAINT_PRESCALER_WIDTH-1:0]);
	always @(/*AS*/dfi_init_complete or maint_prescaler_r
				or maint_prescaler_tick_ns) begin
		maint_prescaler_ns = maint_prescaler_r;
		if (~dfi_init_complete || maint_prescaler_tick_ns)
			maint_prescaler_ns = MAINT_PRESCALER_DIV[MAINT_PRESCALER_WIDTH-1:0];
		else if (|maint_prescaler_r)
			maint_prescaler_ns = maint_prescaler_r - ONE[MAINT_PRESCALER_WIDTH-1:0];
	end
	
	always @(posedge clk) maint_prescaler_r <= #TCQ maint_prescaler_ns;

	always @(posedge clk) maint_prescaler_tick_r_lcl <= #TCQ maint_prescaler_tick_ns;
								  
	assign maint_prescaler_tick = maint_prescaler_tick_r_lcl;

endmodule