// Testbench for exercise B5.
//
// Runs the generic design (up_down_counter.sv) and the chip-level design
// (up_down_counter_chips.sv) side by side and compares both with a reference
// model.  Works with Icarus Verilog, Verilator (--binary) and Questa.
//
// Like the testbenches of Basics-Graphics-Music, it drives and samples
// signals only at rising clock edges.  It counts up and down in both modes,
// sees every wrap-around, and resets the counter in the middle of a count.
// It switches to decade mode only at counts 0-9, because the datasheet does
// not say what the 4029 does in decade mode at counts 10-15.

// Time units.  The design files have none: Yosys does not accept timeunit
// and timeprecision, and the Tiny Tapeout template sets `timescale 1ns / 1ps
// in its own testbench.  This line sets the same units here and for the
// design files compiled after it, so tb.sv comes first in the file list.

`timescale 1ns / 1ps

module tb;

    logic       clk;
    logic       rst;
    logic       up;
    logic       binary;

    wire  [3:0] q,           q_chips;
    wire        carry_out_n, carry_out_n_chips;

    up_down_counter i_generic
    (
        .clk         ( clk         ),
        .rst         ( rst         ),
        .up          ( up          ),
        .binary      ( binary      ),
        .q           ( q           ),
        .carry_out_n ( carry_out_n )
    );

    up_down_counter_chips i_chips
    (
        .clk         ( clk               ),
        .rst         ( rst               ),
        .up          ( up                ),
        .binary      ( binary            ),
        .q           ( q_chips           ),
        .carry_out_n ( carry_out_n_chips )
    );

    //------------------------------------------------------------------------
    // Clock with a period of 10 ns.
    // On the breadboard one period is about a second.

    initial
    begin
        clk = '0;

        forever
            # 5 clk = ~ clk;
    end

    //------------------------------------------------------------------------
    // Reference model: the count as an integer, with the remainder of the
    // division by the modulus.  rst sets 0 at once, without the clock.

    int count;

    wire [31:0] modulus = binary ? 32'd16 : 32'd10;

    always @ (posedge clk or posedge rst)
        if (rst)
            count <= 0;
        else if (up)
            count <= (count + 1) % modulus;
        else
            count <= (count + modulus - 1) % modulus;

    wire carry_expected = up ? count == modulus - 1 : count == 0;

    wire ok_generic = q       === 4' (count) && carry_out_n       === ~ carry_expected;
    wire ok_chips   = q_chips === 4' (count) && carry_out_n_chips === ~ carry_expected;

    //------------------------------------------------------------------------
    // Checking at every rising clock edge.  At the edge both designs and the
    // model still show the clock cycle that ends there, the same values that
    // a flip-flop would sample.

    // Initial values are fine in a testbench, and the checker samples rst at
    // the clock edge on purpose, although the designs reset asynchronously

    // verilator lint_off PROCASSINIT
    // verilator lint_off SYNCASYNCNET

    logic was_reset = 1'b0;
    logic done      = 1'b0;  // Set by the stimulus before $finish

    int cycle    = 0;
    int n_checks = 0;
    int n_errors = 0;

    logic [3:0] carry_seen = '0;  // Carry seen in: decade up, binary up, decade down, binary down

    always @ (posedge clk)
    begin
        if (rst)
            was_reset <= 1'b1;

        if ((rst | was_reset) & ~ done)
        begin
            cycle    <= cycle + 1;
            n_checks <= n_checks + 2;
            n_errors <= n_errors + (ok_generic ? 0 : 1) + (ok_chips ? 0 : 1)
                                 + (count >= 0 && count < int' (modulus) ? 0 : 1);

            if (~ rst & carry_expected)
                carry_seen [{ ~ up, binary }] <= 1'b1;

            $display ("%5d  %b   %s %s   %2d   %b    %b   %s  %s",
                cycle + 1, rst, up ? "up  " : "down", binary ? "bin" : "dec", q, q, carry_out_n,
                ok_generic ? "ok     " : "WRONG  ", ok_chips ? "ok   " : "WRONG");
        end
    end

    //------------------------------------------------------------------------
    // Driving the inputs

    task automatic run (input logic u, input logic bin, input int n);
        up     <= u;
        binary <= bin;
        repeat (n) @ (posedge clk);
    endtask

    initial
    begin
        $dumpfile ("tb.vcd");

        `ifdef __ICARUS__
            $dumpvars (0, tb);  // Without a scope Icarus also tries to dump $unit
        `else
            $dumpvars;
        `endif

        $display ("cycle  rst  mode      q   bits  ~CO   generic  chips");

        // Before reset the count is unknown, as after power-up

        up     <= '1;
        binary <= '0;
        rst    <= 'x;
        repeat (3) @ (posedge clk);
        rst    <= '1;
        repeat (3) @ (posedge clk);
        rst    <= '0;

        run (1, 0, 13);  // Decade, up:   1 ... 9, 0, 1, 2, 3
        run (1, 1, 14);  // Binary, up:   4 ... 15, 0, 1
        run (0, 1,  8);  // Binary, down: 0, 15, 14, 13, 12, 11, 10, 9
        run (0, 0, 12);  // Decade, down: 8 ... 0, 9, 8, 7

        // Reset in the middle of the count.  Both designs must go to 0 at
        // once, not at the next clock edge, like PRESET ENABLE of the 4029.

        rst <= '1;
        repeat (2) @ (posedge clk);
        rst <= '0;

        run (1, 0, 4);

        // Stop checking one clock edge before $finish, so that every
        // simulator reports the same number of checks

        done <= '1;
        @ (posedge clk);

        $finish;
    end

    //------------------------------------------------------------------------

    final
    begin
        if (n_errors == 0 && carry_seen == 4'b1111)
            $display ("PASS: %0d checks, no errors", n_checks);
        else
            $display ("FAIL: %0d errors in %0d checks, carry seen %b", n_errors, n_checks, carry_seen);
    end

endmodule
