module ssa_stim(
	input clk,  // Probably 188.6 MHz
	input iqsync,
	output signed [15:0] driveiq,
	output reg signed [15:0] drive_i,
	output reg signed [15:0] drive_q,
	input run,
	input [9:0] g_period,  // external
	input signed [15:0] ampstep,  // external
	input signed [15:0] pertstep  // external
);
// half-period of excitation is (g_period+1)*2 clk cycles
// six half-periods dwell at each amplitude step:
//   nominal
//   nominal
//   +pert amplitude
//   nominal
//   +pert phase
//   nominal

//reg iqs=0;
//always @(posedge clk) iqs <= ~iqs;
//assign iqsync = iqs;
wire iqs = iqsync;

reg [9:0] g=0;
reg [2:0] h=0;
wire g_roll = g==0;
reg run1=0, ts=0, t1=0, t2=0;
always @(posedge clk) begin
	if (iqs) run1 <= run;
	if (run1 & iqs) begin
		g <= g_roll ? g_period : g-1;
		if (g_roll) h <= (h==5) ? 0 : h+1;
	end else if (~run1) begin
		g <= 0;
		h <= 0;
	end
	ts <= g_roll & (h==0) & ~iqs & run1;
	t1 <= g_roll & ( ((h==2) & ~iqs) | ((h==4) & iqs) );
	t2 <= g_roll & ( ((h==3) & ~iqs) | ((h==5) & iqs) );
end

`define SAT(x,old,new) ((~|x[old:new] | &x[old:new]) ? x[new:0] : {x[old],{new{~x[old]}}})
reg signed [15:0] step=0, d2=0;
reg signed [16:0] d1=0;
always @(posedge clk) begin
	step <= ts ? ampstep : t1 ? pertstep : t2 ? (-pertstep) : 0;
	if (run1) begin
		d1 <= d2 + step;
		d2 <= `SAT(d1,16,15);
	end else begin
		d1 <= 0;
		d2 <= 0;
	end
end
assign driveiq = d1;

//reg signed [15:0] drive_i=0, drive_q=0;
// Don't use d1 directly, it has overflow artifacts
always @(posedge clk) begin
	if ( iqs) drive_i <= d2;
	if (~iqs) drive_q <= d2;
end

endmodule
