// CD4029B: presettable up/down counter, binary or decade (BCD).
//
// Ports in pin order, named as in the datasheet.  The power pins, VSS (8)
// and VDD (16), are left out.
//
// The count advances on the rising edge of CLOCK while CARRY IN is low.
// UP/DOWN: 1 = count up, 0 = count down.  BINARY/DECADE: 1 = 0 to 15,
// 0 = 0 to 9.  PRESET ENABLE is active high and asynchronous: while it is
// 1 the count takes the value of the JAM inputs at once, without the clock.
// CARRY OUT is active low: it is 0 at the last count (15 or 9 up, 0 down)
// while CARRY IN is low.
//
// Synthesizable by tools that support an asynchronous load, such as Yosys.
// The model loads JAM when PRESET ENABLE rises; with the JAM inputs tied,
// as in the exercises, that is the same as the chip.  For an FPGA tie the
// JAM inputs to 0: then the load is an ordinary asynchronous reset.
//
// The datasheet does not say what the chip does in decade mode at counts
// 10 to 15, which it reaches when you switch from binary to decade.  The
// model counts up from them to 15 and then 0, and down as usual.

module cd4029
(
    input  logic preset_enable,  // Pin 1:  1 = count = JAM at once
    output logic q4,             // Pin 2
    input  logic jam4,           // Pin 3
    input  logic jam1,           // Pin 4
    input  logic carry_in_n,     // Pin 5:  0 = count, 1 = hold
    output logic q1,             // Pin 6
    output logic carry_out_n,    // Pin 7:  0 at the last count
                                 // Pin 8:  VSS
    input  logic binary_decade,  // Pin 9:  1 = binary, 0 = decade
    input  logic up_down,        // Pin 10: 1 = up, 0 = down
    output logic q2,             // Pin 11
    input  logic jam2,           // Pin 12
    input  logic jam3,           // Pin 13
    output logic q3,             // Pin 14
    input  logic clock           // Pin 15
                                 // Pin 16: VDD
);

    logic [3:0] count;

    wire  [3:0] jam  = { jam4, jam3, jam2, jam1 };
    wire  [3:0] last = binary_decade ? 4'd15 : 4'd9;

    always_ff @ (posedge clock or posedge preset_enable)
        if (preset_enable)
            count <= jam;
        else if (~ carry_in_n)
        begin
            if (up_down)
                count <= count == last  ? 4'd0 : count + 4'd1;
            else
                count <= count == 4'd0  ? last : count - 4'd1;
        end

    assign { q4, q3, q2, q1 } = count;

    assign carry_out_n = carry_in_n | (up_down ? count != last : count != 4'd0);

endmodule
