`timescale 1ns / 1ps

module tb;

    localparam period       = 20;
    localparam vector_count = 512;
    logic [14:0] vectors [0:vector_count-1];
    logic [2:0] expected, check_mask;
    logic clk = 1'b0;

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

    logic [1:0] a   = '0;
    logic [1:0] b   = '0;
    logic [1:0] c   = '0;
    logic [2:0] sel = '0;
    logic ya_rtl;
    logic ya_chips;
    logic yb_rtl;
    logic yb_chips;
    logic yc_rtl;
    logic yc_chips;

    mux_4053 dut_rtl
    (
        .a            (a),
        .b            (b),
        .c            (c),
        .sel          (sel),
        .ya           (ya_rtl),
        .yb           (yb_rtl),
        .yc           (yc_rtl)
    );

    mux_4053_chips dut_chips
    (
        .a            (a),
        .b            (b),
        .c            (c),
        .sel          (sel),
        .ya           (ya_chips),
        .yb           (yb_chips),
        .yc           (yc_chips)
    );

    initial
    begin
        $readmemh ("vectors.hex", vectors);
        @ (posedge clk);
        # 1;
        for (int i = 0; i < vector_count; i ++)
        begin
            a          = vectors [i] [0 +: 2];
            b          = vectors [i] [2 +: 2];
            c          = vectors [i] [4 +: 2];
            sel        = vectors [i] [6 +: 3];
            expected   = vectors [i] [9 +: 3];
            check_mask = vectors [i] [12 +: 3];
            @ (posedge clk);
            # 1;  // Allow nonblocking state and combinational outputs to settle.
            if (({ yc_rtl, yb_rtl, ya_rtl } & check_mask) !== (expected & check_mask))
                $fatal (1, "mux_4053_rtl vector %0d got=%h expected=%h mask=%h", i, { yc_rtl, yb_rtl, ya_rtl }, expected, check_mask);
            if (({ yc_chips, yb_chips, ya_chips } & check_mask) !== (expected & check_mask))
                $fatal (1, "mux_4053_chips vector %0d got=%h expected=%h mask=%h", i, { yc_chips, yb_chips, ya_chips }, expected, check_mask);
        end
        $display ("PASS mux_4053: 512 oracle vectors");
        $finish;
    end

    initial
    begin
        repeat (vector_count * 3 + 20) @ (posedge clk);
        $fatal (1, "Cycle watchdog");
    end

endmodule
