// 自复制检测器 - 检测CA中是否发生了自复制
module replication_detector #(
    parameter GRID_W = 80,
    parameter GRID_H = 80,
    parameter PATTERN_W = 10,
    parameter PATTERN_H = 10
)(
    input  wire             clk,
    input  wire             rst_n,
    input  wire [2:0]       grid [0:GRID_W*GRID_H-1],
    output wire [7:0]       copy_count,
    output wire             replication_event
);
    // 滑动窗口模式匹配
    reg [7:0] matches;
    reg [11:0] window [0:PATTERN_W*PATTERN_H-1];
    integer x, y, dx, dy;
    always @(posedge clk or negedge rst_n) begin
        if (!rst_n) matches <= 8'd0;
        else begin
            matches <= 8'd0;
            for (y = 0; y <= GRID_H-PATTERN_H; y = y + PATTERN_H/2) begin
                for (x = 0; x <= GRID_W-PATTERN_W; x = x + PATTERN_W/2) begin
                    // 提取窗口并与模板比较
                    reg match;
                    match = 1'b1;
                    for (dy = 0; dy < PATTERN_H; dy = dy + 1)
                        for (dx = 0; dx < PATTERN_W; dx = dx + 1)
                            if (grid[(y+dy)*GRID_W+x+dx] != window[dy*PATTERN_W+dx])
                                match = 1'b0;
                    if (match) matches <= matches + 8'd1;
                end
            end
        end
    end
    assign copy_count = matches;
    assign replication_event = (matches > 8'd1);
endmodule