module bpm_calculator (
    input wire clk,
    input wire rst,
    input wire peak_in,
    output reg bpm_valid,
    output reg [8:0] bpm_out
);
    reg [99:0] peak_history;
    reg [6:0] beat_count;
    reg [6:0] sample_count;
    reg [6:0] next_count;

    always @(*) begin
        next_count = beat_count;

        if (sample_count < 7'd100) begin
            if (peak_in)
                next_count = beat_count + 7'd1;
        end else if (peak_in && !peak_history[99]) begin
            next_count = beat_count + 7'd1;
        end else if (!peak_in && peak_history[99]) begin
            next_count = beat_count - 7'd1;
        end
    end

    always @(posedge clk) begin
        if (rst) begin
            peak_history <= 100'b0;
            beat_count <= 7'd0;
            sample_count <= 7'd0;
            bpm_valid <= 1'b0;
            bpm_out <= 9'd0;
        end else begin
            peak_history <= {peak_history[98:0], peak_in};
            beat_count <= next_count;

            if (sample_count < 7'd100)
                sample_count <= sample_count + 7'd1;
            else
                sample_count <= 7'd100;

            if (sample_count == 7'd99) begin
                bpm_valid <= 1'b1;
                bpm_out <= next_count * 4'd12;
            end else if (sample_count >= 7'd100) begin
                bpm_valid <= 1'b1;
                bpm_out <= next_count * 4'd12;
            end else begin
                bpm_valid <= 1'b0;
                bpm_out <= 9'd0;
            end
        end
    end
endmodule
