// Exercise B5: a 4-bit up/down counter, binary (0-15) or decade (0-9).
//
// Generic version that matches schematic 1: a 4-bit register with an
// asynchronous reset, the next-state logic that adds or subtracts 1 and
// wraps around, and the logic for the carry output.  Not tied to any chip.
// Synthesizable.

module up_down_counter
(
    input  logic       clk,
    input  logic       rst,          // 1 = count 0 at once, like PRESET ENABLE of the 4029 with JAM = 0
    input  logic       up,           // 1 = count up, 0 = count down
    input  logic       binary,       // 1 = count 0-15, 0 = count 0-9

    output logic [3:0] q,            // The count
    output logic       carry_out_n   // 0 at the last count: 9 or 15 up, 0 down
);

    wire [3:0] last = binary ? 4'd15 : 4'd9;

    //------------------------------------------------------------------------
    // Register and next-state logic

    always_ff @ (posedge clk or posedge rst)
        if (rst)
            q <= 4'd0;
        else if (up)
            q <= q == last ? 4'd0 : q + 4'd1;
        else
            q <= q == 4'd0 ? last : q - 4'd1;

    //------------------------------------------------------------------------
    // Carry: active low, like CARRY OUT of the 4029

    assign carry_out_n = ~ (up ? q == last : q == 4'd0);

endmodule
