module test_stack;
    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];
    reg [15:0] result;
    reg [41:0] expected;
    integer op,n,i;
    stack_cpu dut(clk,key,sw,leds,h0,h1,h2,h3,h4,h5);
    always #1 clk=~clk;
    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]=111;
        glyphs[10]=119; glyphs[11]=124; glyphs[12]=57; glyphs[13]=94; glyphs[14]=121; glyphs[15]=113;
        repeat(5) @(negedge clk); key=15;
        for(op=0;op<4;op=op+1) begin
            for(n=0;n<16;n=n+1) begin
                sw=512+32*op+n;
                case(op)
                    0: result=16'h9010 << n;
                    1: result=16'h9010 >> n;
                    2: result=$signed(16'h9010) >>> n;
                    3: result=(16'h9010 >> n)|(16'h9010 << (16-n));
                endcase
                expected={42{1'b1}};
                for(i=0;i<4;i=i+1) expected[7*i +: 7] = ~glyphs[result[4*i +: 4]];
                // Two complete passes exercise nested calls with a reused stack.
                repeat(2400) @(negedge clk);
                if(display!==expected || leds!==(32*op+n)) begin
                    $display("FAIL mode %d amount %d expected %h pins %h lamps %h",op,n,result,display,leds); $finish;
                end
            end
        end
        $display("PASS all 64 operation/amount pairs, nested calls, LIFO stack and hexadecimal output"); $finish;
    end
endmodule
