module ecg_r_peak_detector (
    input wire clk,
    input wire rst,
    input wire [11:0] sample_in,
    input wire [11:0] threshold,
    output reg peak_out
);
    reg [11:0] sample_d1;
    reg [11:0] sample_d2;
    reg [11:0] sample_d3;
    reg [11:0] sample_d4;
    reg [11:0] threshold_d1;
    reg [11:0] threshold_d2;
    reg [2:0] sample_count;
    reg [5:0] refractory_count;
    reg candidate_peak;

    always @(*) begin
        candidate_peak = 1'b0;

        if (sample_count >= 3'd4) begin
            if ((sample_d2 >= threshold_d2) &&
                (sample_d2 > sample_d4) &&
                (sample_d2 > sample_d3) &&
                (sample_d2 > sample_d1) &&
                (sample_d2 > sample_in) &&
                (refractory_count == 6'd0)) begin
                candidate_peak = 1'b1;
            end
        end
    end

    always @(posedge clk) begin
        if (rst) begin
            sample_d1 <= 12'd0;
            sample_d2 <= 12'd0;
            sample_d3 <= 12'd0;
            sample_d4 <= 12'd0;
            threshold_d1 <= 12'd0;
            threshold_d2 <= 12'd0;
            sample_count <= 3'd0;
            refractory_count <= 6'd0;
            peak_out <= 1'b0;
        end else begin
            peak_out <= candidate_peak;

            sample_d4 <= sample_d3;
            sample_d3 <= sample_d2;
            sample_d2 <= sample_d1;
            sample_d1 <= sample_in;

            threshold_d2 <= threshold_d1;
            threshold_d1 <= threshold;

            if (sample_count < 3'd5)
                sample_count <= sample_count + 3'd1;
            else
                sample_count <= 3'd5;

            if (candidate_peak) begin
                refractory_count <= 6'd49;
            end else if ((sample_count >= 3'd4) && (refractory_count != 6'd0)) begin
                refractory_count <= refractory_count - 6'd1;
            end
        end
    end
endmodule
