`timescale 1ns / 1ns module histmode( clk40, rstn, trace_enable, average, stop_count, trace_address, write_enable, avg_clear, cnt_at_pulse_end); input clk40, rstn, trace_enable; input [6:0] average; input [14:0] stop_count; output [8:0] trace_address; output write_enable, avg_clear; output [14:0] cnt_at_pulse_end; reg [14:0] cnt_at_pulse_end; reg [7:0] countl; reg [14:0] counth; wire [8:0] trace_address = {counth[7:0], countl[0:0]}; reg write_squelch; wire avg_clear = countl[7:1] == 7'b0000000; wire carry = countl == {average, 1'b1}; assign write_enable = trace_enable & ~write_squelch; always @(posedge clk40 or negedge rstn) if (~rstn) begin countl <= 0; counth <= 0; cnt_at_pulse_end <= 0; write_squelch <= 0; end else begin countl <= (carry | ~trace_enable) ? 0 : (countl + 1'b1); counth <= trace_enable ? (carry ? (counth + 1'b1) : counth) : 0; if (write_enable) cnt_at_pulse_end <= counth; if (~trace_enable | (carry && (counth == stop_count))) write_squelch <= trace_enable; end endmodule