module test_cascade_bcd;
    reg clk=0;
    reg [9:0] sw=0;
    reg [3:0] key=14;
    wire [6:0] h2,h1,h0;
    reg [6:0] digit [0:9];
    integer n;
    cascade_bcd #(.CYCLES_PER_SECOND(2)) dut(clk,sw,key,h2,h1,h0);
    task edge_and_wait;
        begin #1; clk=1; #1; clk=0; #1; end
    endtask
    function [7:0] display_digit;
        input [6:0] segments;
        integer i;
        begin
            display_digit = "?";
            for (i = 0; i < 10; i = i + 1)
                if (segments === digit[i]) display_digit = "0" + i;
        end
    endfunction
    task check;
        input integer number;
        begin
            if ({h2,h1,h0} !== {digit[number/100],digit[(number/10)%10],digit[number%10]}) begin
                $display("FAIL expected %03d, observed %c%c%c", number,
                         display_digit(h2), display_digit(h1), display_digit(h0));
                $finish;
            end
        end
    endtask
    initial begin
        {digit[0],digit[1],digit[2],digit[3],digit[4]} = {7'h40,7'h79,7'h24,7'h30,7'h19};
        {digit[5],digit[6],digit[7],digit[8],digit[9]} = {7'h12,7'h02,7'h78,7'h00,7'h10};
        repeat(5) edge_and_wait; check(0);
        key[0]=1; repeat(2) edge_and_wait;
        for (n=0; n<1001; n=n+1) begin
            edge_and_wait; check(n%1000);
            edge_and_wait; check((n+1)%1000);
        end
        sw[9]=1; repeat(4) edge_and_wait; check(998);
        key[0]=0; repeat(4) edge_and_wait; check(0);
        key[0]=1; repeat(4) edge_and_wait; check(998);
        sw[9]=0; sw[8]=1; repeat(4) edge_and_wait; check(98);
        $display("PASS all 1000 digits, wrap, clock enable and preset/reset priority");
    end
endmodule
