// First attempt at cal is 0.035 Hz/bit for the on-the-fiber 18-bit
// detune frequency (easily adjusted up or down by a factor of ten).
// 18 bits for 1 kHz on the output -> 0.0038 Hz/bit
// GBW = 1 Hz = 6 rad/s,  R = 90k updates/second
// Want GBW/R Hz/Hz accumulation per update
// is GBW / R * 0.035 / 0.0038 counts/count accumulation per update
// 6.1e-4 counts/count accumulation per update
// So place 11 bits to the right of the binary point,
// to go with 18 bits (DAC) to the left of the binary point.
// The bandwidth goal is so fuzzy, and it's really easy to change
// the scaling from the detune calculator, so this module doesn't
// mess with a multiplier in the integrator.

module integ5(
	input clk,
	input strobe,  // one strobe every 11.2 microseconds
	input signed [17:0] detune,  // provisional 0.035 Hz/bit
	// configuration
	input signed [17:0] setpoint,   // Nominally zero
	input int_enable,  // otherwise frozen
	input signed [17:0] dac_min,
	input signed [17:0] dac_max,
	// output
	output strobe_out,
	output signed [17:0] dac
);

parameter sw = 11;  // Bit width of saturated error that sets slew rate
// 11 means fastest motion of accum (defined below) is +1023 / -1024

parameter lsbs = 11;  // number of lsbs in integrator
// gain of system is 2^(-lsbs) per cycle

// One simple pipeline stage to get things started
reg signed [18:0] error=0;  reg strobe1=0;
always @(posedge clk) begin
	error <= detune - setpoint;
	if (~int_enable) error <= 0;
	strobe1 <= strobe;
end

// Saturate the error, part of the plan to limit slew rate
// of the output.  Also reduces the chance that a single bad
// detune measurements will confuse the system.
`define SAT(x,old,new) ((~|x[old:new] | &x[old:new]) ? x[new:0] : {x[old],{new{~x[old]}}})
reg signed [sw-1:0] sat_error=0;  reg strobe2=0;
always @(posedge clk) begin
	sat_error <= `SAT(error, 18, sw-1);
	strobe2 <= strobe1;
end

// Actual integration with saturation
// Clocked really slowly (50 MHz in a Kintex) so just do it
// all in a single cycle.
// Note that the clip limits are enforced in a way that limits the DAC
// slew rate, even if the host changes min/max settings capriciously.
// When lsbs=11, it will take 2^(29-sw) cycles = 5.9 seconds
// to move across the full range, 170 Hz / second slew.
// dac_max takes priority over dac_min
reg signed [17+lsbs:0] accum=0, next=0;
wire signed [17:0] accum_h = accum[17+lsbs:lsbs];
reg strobe3=0;
reg signed [sw-1:0] delta;
always @(posedge clk) begin
	if      (accum_h > dac_max) delta = {1'b1,{sw-1{1'b0}}};
	else if (accum_h < dac_min) delta = {1'b0,{sw-1{1'b1}}};
	else if (accum_h > dac_min && sat_error < 0) delta = sat_error;
	else if (accum_h < dac_max && sat_error > 0) delta = sat_error;
	else                        delta = 0;
	if (strobe2) accum <= accum + delta;
	strobe3 <= strobe2;
end
assign dac = accum_h;
assign strobe_out = strobe3;

endmodule
