module clk_divider #(
    parameter integer DIV_WIDTH = 8
)(
    input  wire clk,
    input  wire ce,
    input  wire reset,
    input  wire set,
    input  wire [DIV_WIDTH-1:0] divider,
    output wire active,
    output reg  slow_clk
);

    reg [DIV_WIDTH-1:0] counter;
    reg [DIV_WIDTH-1:0] compare;
    wire                match;

    reg [2:0] set_sync;
    reg       set_now;

    // Detect rising edge (with synchronizer)
    always @(posedge clk)
    begin
        set_sync <= { set_sync[1:0], set };
        set_now  <= ~set_sync[2] & set_sync[1];
    end

    assign active = set_sync[2];

    // Latch divider
    always @(posedge clk)
        if (set_now)
            compare <= divider;

    // Compare
    assign match = (counter == compare);

    // Counter
    always @(posedge clk or posedge reset)
        if (reset)
            counter <= 0;
        else if (ce)
            counter <= match ? 0 : (counter + 1);

    // Clock gen
    always @(posedge clk or posedge reset)
        if (reset)
            slow_clk <= 1'b0;
        else if (ce)
            slow_clk <= slow_clk ^ match;

endmodule // clk_divider