`timescale 1ns / 1ps

module tb_basic_counter;

    localparam period         = 20;
    localparam timeout_cycles = 3000;

    logic clk = 1'b0;

    always # (period / 2) clk = ~ clk;

    logic rst = '0;
    logic inhibit = '0;
    logic up = '0;
    logic binary = '0;
    logic [3:0] q_g;
    logic [3:0] q_c;
    logic co_n_g;
    logic co_n_c;
    int checks = 0;

    basic_counter dut_g
    (
        .clk          (clk),
        .rst          (rst),
        .inhibit      (inhibit),
        .up           (up),
        .binary       (binary),
        .q            (q_g),
        .co_n         (co_n_g)
    );

    basic_counter_chips dut_c
    (
        .clk          (clk),
        .rst          (rst),
        .inhibit      (inhibit),
        .up           (up),
        .binary       (binary),
        .q            (q_c),
        .co_n         (co_n_c)
    );

    task check (input logic [3:0] expected_q, input logic expected_co_n);
        if (q_g !== expected_q || q_c !== expected_q)
            $fatal (1, "q: generic=%h chips=%h expected=%h", q_g, q_c, expected_q);
        if (co_n_g !== expected_co_n || co_n_c !== expected_co_n)
            $fatal (1, "co_n: generic=%h chips=%h expected=%h", co_n_g, co_n_c, expected_co_n);
        checks = checks + 1;
    endtask

    initial
    begin
        $dumpfile ("trace.vcd");
        $dumpvars (0, tb_basic_counter);

        for (int mode = 0; mode < 2; mode ++)
            for (int direction = 0; direction < 2; direction ++)
            begin
                int expected;
                int modulus;

                @ (posedge clk);
                # 1;
                rst      = 1'b1;
                binary   = 1' (mode);
                up       = 1' (direction);
                inhibit  = 1'b0;
                expected = 0;
                modulus  = mode != 0 ? 16 : 10;
                # 1;
                check (0, up);
                rst = 1'b0;

                repeat (4 * modulus + 3)
                begin
                    @ (posedge clk);
                    if (~ inhibit)
                        expected = (expected + (direction != 0 ? 1 : modulus - 1)) % modulus;
                    # 1;
                    check (4' (expected), inhibit | ~ ((direction != 0)
                        ? expected == modulus - 1 : expected == 0));
                    inhibit = ~ inhibit;
                    # 1;  // Carry changes combinationally; count must hold.
                    check (4' (expected), inhibit | ~ ((direction != 0)
                        ? expected == modulus - 1 : expected == 0));
                end
                rst = 1'b1;
                # 1;
                check (0, inhibit | up);
            end

        $display ("PASS basic_counter: %0d independent checks", checks);
        $finish;
    end

    initial
    begin
        repeat (timeout_cycles) @ (posedge clk);
        $fatal (1, "Timeout in clock cycles");
    end

endmodule
