module prc_dsp(
	// 8 channels high-speed 16-bit parallel ADC data
	input clk,
	input [1:0] qmode,
	input [127:0] adc_data,
	// result ready to ship to RFS
	output signed [16:0] iq_result1,  // to RFS1
	output signed [16:0] iq_result2,  // to RFS2
	// Local Oscillator
	input signed [17:0] cosd,
	input signed [17:0] sind,
	// pass back to CORDIC for LO
	output [18:0] phase_zero,
	// Software control
	input [1:0] cav_sel,  // external
	input signed [15:0] prl_gain,  // external
	input [8:0] prl_cfg  // external
);

parameter cut = 4;  // high-pass frequency for washout

wire [1:0] prl_sel = prl_cfg[1:0];
wire pz_rst = ~prl_cfg[8];
wire mod2 = qmode[0];

`define SAT(x,old,new) ((~|x[old:new] | &x[old:new]) ? x[new:0] : {x[old],{new{~x[old]}}})

wire signed [16:0] iq_out[0:7];
genvar ix;
generate for (ix=0; ix<8; ix=ix+1) begin
	wire signed [15:0] a = adc_data[16*(ix+1)-1:16*ix];
	wire signed [16:0] b;
	washout #(.dw(16), .cut(cut)) wo(.clk(clk), .rst(1'b0), .track(1'b1),
		.i_data(a), .o_data(b));
	reg signed [15:0] c=0;
	always @(posedge clk) c <= `SAT(b,16,15);
	wire signed [15:0] d;
	fdownconvert dc(.clk(clk), .mod2(mod2), .cosd(cosd), .sind(sind),
		.a_data(c), .a_gate(1'b1), .a_trig(1'b0),
		.o_data(d));
	reg signed [15:0] d1=0, d2=0;
	// Two-tap [1 1] FIR filter on each of I and Q
	// Note that d is 16-bits, iq_out is 17-bits
	always @(posedge clk) begin d1 <= d; d2 <= d1; end
	assign iq_out[ix] = d + d2;
end endgenerate

reg signed [15:0] prl_mean = 0;
reg signed [31:0] prl_d = 0, prl_d2 = 0;  // 16-bit x 16-bit to 32-bit
reg signed [24:0] prl_s = 0;
wire signed [19:0] prl_x = prl_d2[30:11];
wire signed [24:0] prl_ss = prl_s + prl_x;
always @(posedge clk) begin
	// Hard-code channels for PRL for now
	// No averaging yet, therefore no need to address
	// the pi ambiguity from phase averaging
	prl_mean <= prl_sel[0] ? iq_out[6] : iq_out[7];
	// Note that bandwidth of tracking loop depends on both prl_gain and PRL amplitude
	prl_d <= prl_mean * prl_gain;
	prl_d2 <= prl_d;
	if (mod2 | pz_rst) prl_s <= pz_rst ? 1'b0 : prl_ss;
end
assign phase_zero = prl_s[24:6];

wire select0 = cav_sel[0] ^ qmode[1];

assign iq_result1 = cav_sel[1] ?
	(select0 ? iq_out[5] : iq_out[4]) :
	(select0 ? iq_out[3] : iq_out[2]);

assign iq_result2 = cav_sel[1] ?
	(select0 ? iq_out[3] : iq_out[2]) :
	(select0 ? iq_out[5] : iq_out[4]);

endmodule
