`timescale 1ns / 1ns
// Larry Doolittle, LBNL, November 2015

// 188.57 MHz clock, multiplexed I and Q from two ADCs,
// full-rate out of 94.29 MS/s ADC chips and reconstructing digital downconverter.

// 8-bit telem word latched during qsync cycles includes at least:
//   padding every fourth qsync, when the result will get overwritten by an 8b10b comma
//   Simple data valid bits, i.e., ADCs working and no overflow
//   bucket will be filled flag, and emergency stop
//   timing to find one clk cycle in 2640 that is the 71.43 kHz sync cycle
//     (2640 = 16 * 5 * 33; qsync synchronous to factor of four)
//   Static info like station number and gateware revision code
//   Dynamic info like optical IIC readout and config registers
//     (latter two can be addressed by cycle number)
//   CRC

// Receiver for above sender
module quadr(
	input clk,
	input [15:0] d_in,
	input comma,
	output [13:0] d_out,  // to descrunch1
	output [23:0] telem,
	output qsync
);

reg [3:0] mode=0;
reg [15:0] d_old=0;
reg [13:0] mux=0;
reg [15:0] telem_s=0;  // shift
reg [23:0] telem_r=0;
wire [1:0] cycle = mode[1:0];
reg qsync_r=0;
always @(posedge clk) begin
	mode <= mode+1;
	if (comma) mode <= 12;
	d_old <= d_in;
	case (cycle)
		2'd0: mux <= {d_old[15:8],d_in[5:0]};
		2'd1: mux <= {d_old[15:6],d_in[3:0]};
		2'd2: mux <= {d_old[15:4],d_in[1:0]};
		2'd3: mux <= {d_old[15:2]};
	endcase
	if (cycle == 3) telem_s <= {telem_s[7:0],d_in[7:0]};
	if (mode == 7) telem_r <= {telem_s,d_in[7:0]};
	qsync_r <= mode==14;
end
assign d_out = mux;
assign telem = telem_r;
assign qsync = qsync_r;
endmodule
