module test_history;
    reg [9:0] sw;
    reg [3:0] key;
    wire [9:0] lamps;
    history_detector dut(.SW(sw), .KEY(key), .LEDR(lamps));
    integer word, index, high_bits, low_bits, repeat_count, previous, bit_value;
    reg [9:0] expected;

    task clock_one;
        begin key[0] = 0; #1; key[0] = 1; #1; end
    endtask
    initial begin
        key = 15;
        for (word = 0; word < 256; word = word + 1) begin
            sw = 0; clock_one;
            if (lamps !== 0) begin $display("FAIL reset"); $finish; end
            low_bits = 0; high_bits = 0; repeat_count = 0; previous = -1; expected = 0;
            for (index = 7; index >= 0; index = index - 1) begin
                bit_value = (word >> index) & 1;
                sw = 1 + 2 * bit_value;
                #1;
                if (lamps !== expected) begin $display("FAIL unclocked input"); $finish; end
                clock_one;
                repeat_count = bit_value == previous ? repeat_count + 1 : 1;
                previous = bit_value;
                high_bits = (high_bits * 2 + 1 - bit_value) % 16;
                low_bits = (low_bits * 2 + bit_value) % 16;
                expected = 512 * (repeat_count >= 4) + 16 * high_bits + low_bits;
                if (lamps !== expected) begin
                    $display("FAIL word %h bit %d expected %h got %h", word, index, expected, lamps);
                    $finish;
                end
            end
        end
        $display("PASS 256 eight-sample inputs and all 2048 clock edges");
        $finish;
    end
endmodule
