// SIMULATION ONLY. Ideal 4x16 FIFO pin behavior at settled edges.
// No ripple delays, electrical behavior or asynchronous boundary races.
// TS is tied low; simultaneous SI rising and SO falling use pre-edge flags.

module cd74hc40105
(
    input  p1_ts,
    input  p3_si,
    input  p4_d0,
    input  p5_d1,
    input  p6_d2,
    input  p7_d3,
    input  p9_rst,
    input  p15_so,
    output p2_dir,
    output p10_q3,
    output p11_q2,
    output p12_q1,
    output p13_q0,
    output p14_dor
);

    logic [3:0] memory [0:15];
    integer read_ptr = 0, write_ptr = 0, count = 0;
    logic si_old     = 0, so_old = 1;
    logic put, take;
    always @ (p3_si or p15_so or p9_rst)
    begin
        if (p9_rst)
        begin
            read_ptr  = 0;
            write_ptr = 0;
            count     = 0;
        end
        else
        begin
            put  = p3_si & ~ si_old & (count < 16);
            take = ~ p15_so & so_old & (count > 0);
            if (put)
            begin
                memory [write_ptr] = { p7_d3, p6_d2, p5_d1, p4_d0 };
                write_ptr          = (write_ptr + 1) % 16;
            end
            if (take)
                read_ptr = (read_ptr + 1) % 16;
            count = count + int' (put) - int' (take);
        end
        si_old = p3_si;
        so_old = p15_so;
    end
    assign p2_dir                             = count < 16;
    assign p14_dor                            = count != 0;
    assign { p10_q3, p11_q2, p12_q1, p13_q0 } = memory [read_ptr];

endmodule
