`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

module quads(
	input clk,
	input [13:0] d_in,  // from scrunch1
	input [23:0] telem,
// telem sends 24 bits every 16 cycles, see above
	input qsync,  // one every sixteen clock cycles
// qsync establishes pattern of four data words, AI, BI, AQ, BQ
	output [15:0] d_out,  // to GTP, still needs commas added
	output s_out          // to GTP, replace lower byte with comma
);

reg [13:0] d_old=0;
reg [3:0] mode=0;
reg [15:0] mux=0;
reg [23:0] telem_h=0;
reg s=0;
wire [1:0] cycle = mode[1:0];
always @(posedge clk) begin
	mode <= mode+1;
	if (qsync) mode <= 15;
	if (qsync | cycle==2) telem_h <= qsync ? telem : {telem_h[16:0],8'b0};
	d_old <= d_in;
	case (cycle)
		2'd0: mux <= {d_in[13:6], telem_h[23:16]};
		2'd1: mux <= {d_in[13:4], d_old[5:0]};
		2'd2: mux <= {d_in[13:2], d_old[3:0]};
		2'd3: mux <= {d_in      , d_old[1:0]};
	endcase;
	s <= mode==12;
end
assign d_out = mux;
assign s_out = s;

endmodule

