module test_program;
    reg clk=0;
    reg [3:0] key=14;
    reg [9:0] sw=0;
    wire [9:0] leds;
    wire [6:0] h0,h1,h2,h3,h4,h5;
    wire [41:0] display={h5,h4,h3,h2,h1,h0};
    reg [6:0] glyphs[0:15];
    integer mode,step;
    reg [15:0] word;
    stack_cpu dut(clk,key,sw,leds,h0,h1,h2,h3,h4,h5);
    always #1 clk=~clk;

    // The program writes each digit separately. Wait until the whole word has settled.
    task observe_word;
        input [15:0] wanted;
        integer i,cycles,stable;
        reg [41:0] expected;
        begin
            expected={42{1'b1}};
            for(i=0;i<4;i=i+1)
                expected[7*i +: 7]=~glyphs[wanted[4*i +: 4]];
            stable=0;
            for(cycles=0;cycles<100000 && stable<256;cycles=cycles+1) begin
                @(negedge clk);
                if(display===expected) stable=stable+1;
                else stable=0;
            end
            if(stable<256 || (step>0 && leds!==sw)) begin
                $display("FAIL cumulative mode %0d step %0d expected %h, LED pins %h",mode,step,wanted,leds);
                $finish;
            end
            $display("step %0d: %h",step,wanted);
        end
    endtask

    initial begin
        glyphs[0]=63; glyphs[1]=6; glyphs[2]=91; glyphs[3]=79; glyphs[4]=102;
        glyphs[5]=109; glyphs[6]=125; glyphs[7]=7; glyphs[8]=127; glyphs[9]=103;
        glyphs[10]=119; glyphs[11]=124; glyphs[12]=57; glyphs[13]=94; glyphs[14]=121; glyphs[15]=113;
        if (!$value$plusargs("MODE=%d",mode)) mode=-1;
        repeat(5) @(negedge clk); key=15;
        if(mode==-1) begin
            sw=512;
            repeat(1800) @(negedge clk);
            if(leds!==85) begin $display("FAIL stack, shifts or carry, LEDs %h",leds); $finish; end
        end else begin
            if(mode<0 || mode>3) begin $display("FAIL choose mode 0 through 3"); $finish; end
            sw=513+(mode<<5);
            word=16'h9010;
            step=0;
            observe_word(word);
            for(step=1;step<=5;step=step+1) begin
                case(mode)
                    0: word=word<<1;
                    1: word=word>>1;
                    2: word=$signed(word)>>>1;
                    3: word={word[0],word[15:1]};
                endcase
                observe_word(word);
            end
        end
        $display("PASS assembly program"); $finish;
    end
endmodule
