`timescale 1ns / 1ps

module tb_basic_sipo;

    localparam period         = 20;
    localparam timeout_cycles = 3000;

    logic clk = 1'b0;

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

    logic rst = '0;
    logic serial = '0;
    logic [3:0] q_g;
    logic [3:0] q_c;
    int checks = 0;

    basic_sipo dut_g
    (
        .clk          (clk),
        .rst          (rst),
        .serial       (serial),
        .q            (q_g)
    );

    basic_sipo_chips dut_c
    (
        .clk          (clk),
        .rst          (rst),
        .serial       (serial),
        .q            (q_c)
    );

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

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

        @ (posedge clk);
        # 1;
        rst = 1'b1;
        # 1;
        check (0);
        rst = 1'b0;

        // Every four-bit word is shifted MSB first and observed at each edge.
        for (int word_value = 0; word_value < 16; word_value ++)
        begin
            logic [3:0] expected;
            expected = '0;
            rst      = 1'b1;
            # 1;
            check (0);
            rst = 1'b0;
            for (int bit_index = 3; bit_index >= 0; bit_index --)
            begin
                serial = 1' ((word_value >> bit_index) & 1);
                @ (posedge clk);
                expected = 4' (2 * int' (expected) + int' (serial));
                # 1;
                check (expected);
            end
            if (q_g !== 4' (word_value))
                $fatal (1, "Serial bit order");
        end
        rst = 1'b1;
        # 1;
        check (0);
        repeat (2) @ (posedge clk);
        # 1;
        check (0);

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

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

endmodule
