module run_states #(parameter INVERT_A = 1'b0) (
    input wire clock, reset_n, sample,
    output reg [8:0] state
);
    wire start = state[0] ^ INVERT_A;
    wire start_zero = start | (|state[8:5]);
    wire start_one = start | (|state[4:1]);
    wire [8:0] following;
    assign following[0] = INVERT_A;
    assign following[1] = ~sample & start_zero;
    assign following[2] = ~sample & state[1];
    assign following[3] = ~sample & state[2];
    assign following[4] = ~sample & state[3]; // TODO: retain a match on the next zero.
    assign following[5] = sample & start_one;
    assign following[6] = sample & state[5];
    assign following[7] = sample & state[6];
    assign following[8] = sample & (state[7] | state[8]);

    always @(posedge clock)
        if (!reset_n) state <= {8'b0, ~INVERT_A};
        else state <= following;
endmodule

module one_hot_runs(input wire [9:0] SW, input wire [3:0] KEY, output wire [9:0] LEDR);
    wire [8:0] ordinary, modified;
    run_states #(.INVERT_A(1'b0)) first(KEY[0], SW[0], SW[1], ordinary);
    run_states #(.INVERT_A(1'b1)) second(KEY[0], SW[0], SW[1], modified);
    wire [8:0] visible_state = SW[2] ? modified : ordinary;
    assign LEDR = {visible_state[4] | visible_state[8], visible_state};
endmodule
