// Exercise BB8: a FIFO of sixteen 3-bit words with a push and a pop button,
// like a 40105 with the two flip-flops of a 4013.
//
// Generic version that matches schematic 1, not tied to any chip.  Like the
// 4013, the design samples push and pop at the rising edge of clk, and it
// acts once per press: the first edge that sees push at 1 puts data at the
// end of the queue, the first edge that sees pop at 1 drops the word at the
// head.  head shows the oldest word while dor (data-out ready) is 1; dir
// (data-in ready) is 0 while all sixteen places are full.  A push into a
// full FIFO and a pop from an empty one are ignored.  rst empties the FIFO
// at once, without the clock.  Synthesizable.

module fifo_demo
(
    input  logic       clk,
    input  logic       rst,

    input  logic       push,
    input  logic       pop,
    input  logic [2:0] data,

    output logic [2:0] head,
    output logic       dor,    // data-out ready: the queue is not empty
    output logic       dir     // data-in ready: the queue is not full
);

    logic       push_q, pop_q;  // the buttons at the last clock edge

    // Write and read counters with one extra bit: equal when the queue is
    // empty, 16 apart when it is full

    logic [4:0] wr, rd;
    logic [2:0] word [0:15];

    wire do_push = push & ~ push_q & dir;
    wire do_pop  = pop  & ~ pop_q  & dor;

    always_ff @ (posedge clk or posedge rst)
        if (rst)
        begin
            push_q <= 1'b0;
            pop_q  <= 1'b0;
            wr     <= '0;
            rd     <= '0;
        end
        else
        begin
            push_q <= push;
            pop_q  <= pop;

            if (do_push)
                wr <= wr + 5'd1;

            if (do_pop)
                rd <= rd + 5'd1;
        end

    always_ff @ (posedge clk)
        if (do_push)
            word [wr [3:0]] <= data;

    assign dor  = wr != rd;
    assign dir  = wr != { ~ rd [4], rd [3:0] };
    assign head = word [rd [3:0]];

endmodule
