module test_cpu;
    reg clk=0, reset_n=1, run=0;
    reg [15:0] data_in=0;
    reg [2:0] probe=0;
    wire [15:0] view;
    wire done, busy;
    course_cpu dut(clk,reset_n,run,data_in,probe,view,done,busy);
    reg [15:0] model [0:7];
    reg [15:0] instruction, operand, snapshot;
    integer i, dst, src, op, immediate, value, tests;
    task tick;
        begin #2; clk=1; #2; clk=0; #1; end
    endtask
    task check;
        input expected_done, expected_busy;
        begin
            if (done !== expected_done || busy !== expected_busy || view !== model[probe]) begin
                $display("FAIL instruction %h r%0d expected %h observed %h done/busy %b%b",
                         instruction,probe,model[probe],view,done,busy);
                $finish;
            end
        end
    endtask
    initial begin
        #1; reset_n=0; #1; reset_n=1; tests=0;
        for (i=0;i<8;i=i+1) model[i]=0;
        // A separate architectural model computes the expected result for each instruction.
        for (i=0;i<512;i=i+1) begin
            dst=(i/4)%8; src=(i/32+3)%8; op=i%4;
            immediate=(i/32)%2 || op==1;
            value=(i*89+257)%512;
            instruction=(op<<13)|(immediate<<12)|(dst<<9)|(immediate?value:src);
            probe=dst;data_in=instruction;run=0; tick; check(0,0);
            run=1; tick; run=0; data_in=~instruction; #1;
            operand=immediate?(value>=256?value-512:value):model[src];
            snapshot=model[dst];
            if (op>=2) begin check(0,1); tick; check(0,1); tick; end
            check(1,1);
            case(op)
                0: model[dst]=operand;
                1: model[dst]=(value & 255)<<8;
                2: model[dst]=snapshot+operand;
                3: model[dst]=snapshot-operand;
            endcase
            tick; check(0,0);
            for (probe=0;probe<7;probe=probe+1) begin #1; check(0,0); end
            #1; check(0,0);tests=tests+1;
        end
        $display("PASS %0d instructions, eight register readbacks per instruction",tests);
        $finish;
    end
endmodule
