module test_accumulator;
    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 s,a,mode,signed_s,signed_a,mathematical,result;
    reg carry,overflow;
    signed_accumulator dut(sw,key,leds,h3,h2,h1,h0);
    task clock_once;
        begin key[1]=0; #1; key[1]=1; #1; 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;
        for (mode=0; mode<1; mode=mode+1)
            for (s=0; s<256; s=s+1)
                for (a=0; a<256; a=a+1) begin
                    key[0]=0; #1;
                    if (leds[9:8]!==0 || {h3,h2,h1,h0}!=={4{digit[0]}}) begin
                        $display("FAIL asynchronous reset"); $finish;
                    end
                    key[0]=1; sw=s; clock_once;
                    sw=a; clock_once;
                    sw=(mode<<8); #1;
                    signed_s=(s<128)?s:s-256;
                    signed_a=(a<128)?a:a-256;
                    mathematical=mode?signed_s-signed_a:signed_s+signed_a;
                    result=mode?s-a:s+a;
                    carry=mode?(s>=a):(result>255);
                    overflow=(mathematical < -128) || (mathematical > 127);
                    if (leds[7:0] !== result[7:0] || {h3,h2,h1,h0} !==
                        {digit[a>>4],digit[a&15],digit[s>>4],digit[s&15]}) begin
                        $display("FAIL preview/display S=%02h A=%02h subtract=%0d expected preview=%02h observed=%02h",
                                 s[7:0], a[7:0], mode, result[7:0], leds[7:0]); $finish;
                    end
                    clock_once;
                    if (leds[9:8] !== {overflow,carry}) begin
                        $display("FAIL flags S=%02h A=%02h subtract=%0d expected V/C=%b%b observed=%b",
                                 s[7:0], a[7:0], mode, overflow, carry, leds[9:8]);
                        $finish;
                    end
                    if ({h3,h2,h1,h0} !== {digit[0],digit[0],digit[(result>>4)&15],digit[result&15]}) begin
                        $display("FAIL registered display S=%02h A=%02h subtract=%0d",s[7:0],a[7:0],mode); $finish;
                    end
                end
        $display("PASS all accumulator states, operand pairs, flags and display outputs");
    end
endmodule
