// Synthesizable ideal functional model; physical power pins omitted.
// Exercise subset: JAM pins 3,4,12,13 are tied LOW physically.
// PE loads zero asynchronously. Dynamic JAM and illegal BCD states are
// outside this model. Reset before changing BINARY/DECADE mode.

module cd4029b
(
    input              p1_pe,
    input              p5_ci_n,
    input              p9_binary,
    input              p10_up,
    input              p15_clk,
    output             p2_q4,
    output             p6_q1,
    output             p7_co_n,
    output             p11_q2,
    output             p14_q3
);

    logic [3:0] count;

    always_ff @ (posedge p15_clk or posedge p1_pe)
        if (p1_pe)
            count <= '0;
        else if (~ p5_ci_n)
        begin
            if (p10_up)
            begin
                if (~ p9_binary && count == 4'd9)
                    count <= '0;
                else
                    count <= count + 1'b1;
            end
            else if (~ p9_binary && count == 4'd0)
                count <= 4'd9;
            else
                count <= count - 1'b1;
        end

    assign { p2_q4, p14_q3, p11_q2, p6_q1 } = count;
    assign p7_co_n = p5_ci_n | ~ (p10_up
        ? (p9_binary ? count == 4'd15 : count == 4'd9)
        : count == 4'd0);

endmodule
