module test_product;
    reg [9:0] sw;
    reg [3:0] key;
    wire [9:0] leds;
    wire [6:0] h3,h2,h1,h0;
    reg [6:0] digit [0:15];
    integer a,b,old_b;
    tree_product dut(sw,key,leds,h3,h2,h1,h0);
    task clock_once;
        begin key[1]=0; #1; key[1]=1; #1; end
    endtask
    task check_product;
        input integer stored_a, stored_b;
        integer number;
        begin
            number = stored_a * stored_b;
            if ({h3,h2,h1,h0} !== {digit[(number>>12)&15],digit[(number>>8)&15],digit[(number>>4)&15],digit[number&15]}) begin
                $display("FAIL A=%0d B=%0d expected product %04h", stored_a, stored_b, number[15:0]);
                $finish;
            end
        end
    endtask
    initial begin
        digit[0] = 7'h40;
        digit[1] = 7'h79;
        digit[2] = 7'h24;
        digit[3] = 7'h30;
        digit[4] = 7'h19;
        digit[5] = 7'h12;
        digit[6] = 7'h02;
        digit[7] = 7'h78;
        digit[8] = 7'h00;
        digit[9] = 7'h10;
        digit[10] = 7'h08;
        digit[11] = 7'h03;
        digit[12] = 7'h46;
        digit[13] = 7'h21;
        digit[14] = 7'h06;
        digit[15] = 7'h0e;
        key=15; sw=0; key[0]=0; clock_once; key[0]=1;
        old_b=0;
        for (a=0; a<256; a=a+1) begin
            sw=512+a; clock_once;
            if (leds!==a) begin $display("FAIL A enable"); $finish; end
            for (b=0; b<256; b=b+1) begin
                sw=256+b; #1;
                if (leds!==old_b) begin $display("FAIL input isolation"); $finish; end
                clock_once; check_product(a,old_b);
                if (leds!==b) begin $display("FAIL B enable"); $finish; end
                sw=0; clock_once;
                check_product(a,b);
                if (leds!==0) begin $display("FAIL inactive display"); $finish; end
                old_b=b;
            end
        end
        key[0]=0; #1; check_product(255,255);
        clock_once; check_product(0,0);

        key[0]=1;
        sw=10'h2FF; clock_once;
        sw=10'h180; clock_once;
        sw=10'h3FF; #1;
        if (leds!==10'h0FF) begin $display("FAIL both enables must display stored A"); $finish; end
        clock_once; check_product(255,128);
        sw=0; clock_once; check_product(255,255);
        sw=10'h300; clock_once; check_product(255,255);
        if (leds!==0) begin $display("FAIL both enables must load zero into A"); $finish; end
        sw=0; clock_once; check_product(0,0);
        $display("PASS 65536 operand pairs, operand enables, output latency and synchronous reset");
        $finish;
    end
endmodule
