module analyser ( input wire clock, frame, reset, input wire [12:0] cfg_data, input wire [1:0] uwt_flag, input wire [11:0] uwt_data, output wire ana_good, output wire [11:0] ana_data, output wire [11:0] ana_base ); reg state_reg, state_next; reg [4:0] counter_reg, counter_next; reg good_reg, good_next; reg [11:0] data_reg, data_next; reg [19:0] buffer_reg [31:0]; reg [19:0] buffer_next [31:0]; wire [19:0] sample = {8'd0, uwt_data}; wire [11:0] baseline = buffer_reg[31][16:5]; wire counter_max = (&counter_reg); integer i; always @(posedge clock) begin if (reset) begin state_reg <= 1'b0; counter_reg <= 5'd0; good_reg <= 1'b0; data_reg <= 12'd0; for(i = 0; i <= 31; i = i + 1) begin buffer_reg[i] <= 20'hfffff; end end else begin state_reg <= state_next; counter_reg <= counter_next; good_reg <= good_next; data_reg <= data_next; for(i = 0; i <= 31; i = i + 1) begin buffer_reg[i] <= buffer_next[i]; end end end always @* begin state_next = state_reg; counter_next = counter_reg; good_next = good_reg; data_next = data_reg; for(i = 0; i <= 31; i = i + 1) begin buffer_next[i] = buffer_reg[i]; end case (state_reg) 0: // skip first 32 samples begin if (frame) begin counter_next = counter_reg + 5'd1; if (counter_max) begin state_next = 1'b1; end end end 1: begin if (frame) begin if (cfg_data[12]) begin if (uwt_data > baseline) begin data_next = uwt_data - baseline; end else begin data_next = 12'd0; end end else begin if (uwt_data > cfg_data[11:0]) begin data_next = uwt_data - cfg_data[11:0]; end else begin data_next = 12'd0; end end for(i = 0; i < 31; i = i + 1) begin buffer_next[i+1] = buffer_reg[i] + sample; end buffer_next[0] = sample; good_next = uwt_flag[0] & counter_max; // skip first 32 baseline samples // skip 32 samples after peak if (counter_max) begin if (uwt_flag[0]) begin counter_next = 5'd0; end end else begin counter_next = counter_reg + 5'd1; end end end endcase end assign ana_good = good_reg; assign ana_data = data_reg; assign ana_base = baseline; endmodule