module test_paced;
    reg clk=0;
    reg [3:0] key=14;
    reg [9:0] switches=0;
    wire [9:0] lamps;
    integer start_cycle, cycle=0, fast_period, slow_period;
    integer setting, expected_period, measured_period;
    reg [9:0] saved;
    paced_cpu #(.ISSUE_BITS(3)) dut(clk,key,switches,lamps,,,,,,);
    always #1 clk=~clk;
    always @(posedge clk) cycle=cycle+1;
    task wait_count;
        input integer count;
        integer deadline;
        begin
            deadline = cycle + 500000;
            while(lamps!==count && cycle<deadline) @(negedge clk);
            if(lamps!==count) begin $display("FAIL counter timeout %d",count); $finish; end
        end
    endtask
    initial begin
        repeat(5) @(negedge clk);
        key=15; switches=512; wait_count(1); start_cycle=cycle;
        wait_count(2); fast_period=cycle-start_cycle;
        switches=0; repeat(64) @(negedge clk); saved=lamps;
        repeat(2 * fast_period) @(negedge clk);
        if(lamps!==saved) begin $display("FAIL held count"); $finish; end
        switches=519; wait_count(3); start_cycle=cycle;
        wait_count(4); slow_period=cycle-start_cycle;
        if(slow_period < fast_period*7 || slow_period > fast_period*8) begin
            $display("FAIL switch-dependent periods: %d and %d cycles",fast_period,slow_period); $finish;
        end
        if(fast_period != 8264 || slow_period != 65776) begin
            $display("FAIL absolute periods: %d and %d cycles; check the inner loop and divider",fast_period,slow_period);
            $finish;
        end
        for (setting = 1; setting < 7; setting = setting + 1) begin
            key = 14; switches = setting; repeat(10) @(negedge clk);
            key = 15; switches = 512 + setting;
            wait_count(1); start_cycle = cycle;
            wait_count(2); measured_period = cycle - start_cycle;
            // Six fixed instructions and 1,027 per outer pass, eight clocks each.
            expected_period = 8 * (6 + 1027 * (setting + 1));
            if (measured_period != expected_period) begin
                $display("FAIL intermediate setting %0d: expected %0d cycles, measured %0d",
                         setting, expected_period, measured_period);
                $finish;
            end
        end
        key=14; repeat(10) @(negedge clk);
        if(lamps!==0) begin $display("FAIL reset"); $finish; end
        $display("PASS fast %0d slow %0d cycles; all eight settings, halt and reset", fast_period,slow_period); $finish;
    end
endmodule
