module ring_osc_adjust (
	input			reset_i,				// async reset
	input			clk_ringosc_i,		// the ring oscillator output divided by 2 (this is not clk_main)
	input			clk_32khz_i,			// 32.768KHz reference clock
	input			enable_i,				// enable, can be tied off externally or driven occasionally to force re-calibration
	output	[15:0]	cal_val_o				// divider selection control for the ring oscillator divider circuit (in ASSP)
);

reg			enable_r1, enable_r2, enable_r3;
reg	[2:0]	downCnt;
reg			downCnt1_r1, downCnt1_r2;
reg	[15:0]	ringosc_2_cnt;
wire		ringosccnt_reset;

//// New Logic to produce CNT to system
//// Detect transition of Calibration aneble from Low to Hi
always @(posedge clk_32khz_i or posedge reset_i)
begin
	if (reset_i) begin
		enable_r1 <= 1'b0;
		enable_r2 <= 1'b0;
		enable_r3 <= 1'b0;
	end
	else begin
		enable_r1 <= enable_i;
		enable_r2 <= enable_r1;
		enable_r3 <= enable_r2;
	end
end

// Generating enable for Clock Cnt circuit
// Default is is 2 32KHz CLK period
always @(posedge clk_32khz_i or posedge reset_i)
begin
	if (reset_i)
		downCnt <= 3'b0;
	else
		if (enable_r2 && !enable_r3)
			downCnt <= 3'b111;
		else if (downCnt != 3'b000)
			downCnt <= downCnt - 1'b1;
		else
			downCnt <= downCnt;
end

// Sync to ring osc clk
always @(posedge clk_ringosc_i or posedge reset_i)
	if (reset_i)
	begin
		downCnt1_r1 <= 1'b0;
		downCnt1_r2 <= 1'b0;
	end
	else
	begin
		downCnt1_r1 <= downCnt[2];
		downCnt1_r2 <= downCnt1_r1;
	end

assign ringosccnt_reset = reset_i || !enable_i;
// Counting # of ringosc cyces in two 32KHz clock
always @(posedge clk_ringosc_i or posedge ringosccnt_reset)
begin
	if (ringosccnt_reset)
		ringosc_2_cnt <= 16'b0;
	else if (downCnt1_r2)
		ringosc_2_cnt <= ringosc_2_cnt + 1'b1;
	else
		ringosc_2_cnt <= ringosc_2_cnt;
end

assign	cal_val_o = ringosc_2_cnt;

endmodule