`timescale 1ns / 1ns

// Histogram for ADC testing
// Concept is 100 to 1000 counts in a bin, 64K bins
// Uses 32 of 325 RAMB36 on 7K160 for 64K x 16
// 1-cycle 94 MHz read-add-write operation, need to stop the acquisition
// for readout to host.
// XXX Some people might ask for a mechanism to clear the memory.
// I recommend they instead use the host to compute deltas.  Then the
// instantiation only needs a switch to disable new counts, so
// the host's read of the array can grab a self-consistent state.

module histogram1 #(
	parameter aw=14,  // sets number of bins
	parameter dw=16   // sets max counts per bin
) (
	input clk,
	input en,
	input [aw-1:0] data_in,
	output [dw-1:0] dout    // results come out here whether or not en is asserted, with two clock cycles delay
	//output time_err
);

reg [aw-1:0] d1 = 0, d2 = 0;
reg e1 = 0, e2 = 0, overlap = 0, o2 = 0;
// time_err_r=0;
always @(posedge clk) begin
	d1 <= data_in;
	d2 <= d1;
	e1 <= en;
	e2 <= e1;
	overlap <= (d1 == data_in) & en & e1 & ~overlap;
	o2 <= overlap;
end

wire [1:0] delta = overlap ? 2 : (e2&~o2) ? 1 : 0;
wire [dw-1:0] old_count;
wire [dw-1:0] new_count = old_count + delta;
dpram #(.aw(aw), .dw(dw)) bin_store(
	.clka(clk), .clkb(clk),
	.addra(d2), .dina(new_count), .wena(1'b1),
	.addrb(d1), .doutb(old_count));

`ifdef SIMULATE
// Non-synthesizable but "obviously correct" histogramming;
// readout must be accomplished using Verilog hierarchical path names.
parameter nw = 1 << aw;
reg [dw-1:0] cross_check[0:nw-1];
integer ix;
initial for (ix=0; ix<nw; ix=ix+1) cross_check[ix]=0;
always @(posedge clk) if (en) cross_check[data_in] = cross_check[data_in] + 1;
`endif

assign dout = old_count;

endmodule

module histogram #(
	parameter aw=14,  // sets number of bins
	parameter dw=16   // sets max counts per bin
) (
	input clk,  // timespec 9.6 ns
	input [aw-1:0] data_in,
	input [aw-1:0] raddr,
	output [dw-1:0] dout,  // three clock cycles delay from raddr
	input start,  // single cycle
	input [31:0] counts,  // sets number of cycles measured
	output ready
);
// It's OK to use a local data bus to drive the "counts" port.
// Its value is only sampled when the "start" port is high.
// So maybe set up an address decoder, and the run operation starts
// when you write the desired number of samples to that port?

reg [aw-1:0] d_pipe=0;
reg [31:0] count=0;
reg run = 0, half = 0, wen = 0;
always @(posedge clk) begin
	if (start | (|count)) count <= start ? counts : count-1;
	run <= |count;
	d_pipe <= run ? data_in : raddr;
	wen <= run;
end

histogram1 #(.aw(aw), .dw(dw)) h(.clk(clk),
	.en(wen), .data_in(d_pipe), .dout(dout));

assign ready = ~run;

endmodule
