`timescale 1ns / 1ps

module tb_basic_gates;

    localparam period         = 20;
    localparam timeout_cycles = 3000;

    logic clk = 1'b0;

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

    logic a = '0;
    logic b = '0;
    logic y_and_g;
    logic y_and_c;
    logic y_or_g;
    logic y_or_c;
    logic y_not_g;
    logic y_not_c;
    logic y_xor_g;
    logic y_xor_c;
    int checks = 0;

    basic_gates dut_g
    (
        .a            (a),
        .b            (b),
        .y_and        (y_and_g),
        .y_or         (y_or_g),
        .y_not        (y_not_g),
        .y_xor        (y_xor_g)
    );

    basic_gates_chips dut_c
    (
        .a            (a),
        .b            (b),
        .y_and        (y_and_c),
        .y_or         (y_or_c),
        .y_not        (y_not_c),
        .y_xor        (y_xor_c)
    );

    task check (input logic expected_y_and, input logic expected_y_or, input logic expected_y_not, input logic expected_y_xor);
        if (y_and_g !== expected_y_and || y_and_c !== expected_y_and)
            $fatal (1, "y_and: generic=%h chips=%h expected=%h", y_and_g, y_and_c, expected_y_and);
        if (y_or_g !== expected_y_or || y_or_c !== expected_y_or)
            $fatal (1, "y_or: generic=%h chips=%h expected=%h", y_or_g, y_or_c, expected_y_or);
        if (y_not_g !== expected_y_not || y_not_c !== expected_y_not)
            $fatal (1, "y_not: generic=%h chips=%h expected=%h", y_not_g, y_not_c, expected_y_not);
        if (y_xor_g !== expected_y_xor || y_xor_c !== expected_y_xor)
            $fatal (1, "y_xor: generic=%h chips=%h expected=%h", y_xor_g, y_xor_c, expected_y_xor);
        checks = checks + 1;
    endtask

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

        for (int i = 0; i < 4; i ++)
        begin
            @ (posedge clk);
            a = 1' (i / 2);
            b = 1' (i % 2);
            # 1;  // Combinational settling after input changes.
            case (i)
            0: check (0, 0, 1, 0);
            1: check (0, 1, 1, 1);
            2: check (0, 1, 0, 1);
            3: check (1, 1, 0, 0);
            endcase
        end

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

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

endmodule
