// Exercise BB7: a decade counter with ten decoded outputs, like the 4017.
//
// Generic version that matches schematic 1, not tied to any chip.  It counts
// clock edges from 0 to 9 in a 4-bit register and decodes the count, so
// that exactly one of the outputs q is 1.  The 4017 does the same with a
// 5-bit Johnson counter inside; section 2 of the page compares the two.
// rst sets the count to 0 at once, without the clock.  Synthesizable.

module decade_counter
(
    input  logic       clk,
    input  logic       rst,

    output logic [9:0] q,          // q [k] is 1 at count k
    output logic       carry_out   // 1 for counts 0-4, 0 for counts 5-9
);

    logic [3:0] count;

    always_ff @ (posedge clk or posedge rst)
        if (rst)
            count <= 4'd0;
        else if (count == 4'd9)
            count <= 4'd0;
        else
            count <= count + 4'd1;

    assign q         = 10'b1 << count;
    assign carry_out = count < 4'd5;

endmodule
