module popcount64_threshold (
    input  wire        clk,
    input  wire        rst,
    input  wire [63:0] data_in,
    input  wire [5:0]  threshold,
    output reg  [6:0]  count_out,
    output reg         threshold_exceeded
);
    reg [6:0] count_stage0;
    reg [6:0] count_stage1;
    reg [5:0] threshold_stage0;
    reg [5:0] threshold_stage1;

    integer i;
    reg [6:0] popcount_comb;

    always @(*) begin
        popcount_comb = 7'd0;
        for (i = 0; i < 64; i = i + 1)
            popcount_comb = popcount_comb + data_in[i];
    end

    always @(posedge clk) begin
        if (rst) begin
            count_stage0 <= 7'd0;
            count_stage1 <= 7'd0;
            threshold_stage0 <= 6'd0;
            threshold_stage1 <= 6'd0;
            count_out <= 7'd0;
            threshold_exceeded <= 1'b0;
        end else begin
            count_stage0 <= popcount_comb;
            count_stage1 <= count_stage0;
            threshold_stage0 <= threshold;
            threshold_stage1 <= threshold_stage0;
            count_out <= count_stage1;
            threshold_exceeded <= (count_stage1 > {1'b0, threshold_stage1});
        end
    end
endmodule
