// Exercise B9: a 4-bit adder whose two numbers and sum are shown on three
// 7-segment displays.
//
// Generic version that matches schematic 1: four full adders in a chain
// (a ripple-carry adder) and three BCD-to-7-segment decoders that draw the
// digits like the 4511, not tied to any chip.  Synthesizable.

module adder_display
(
    input  logic [3:0] a,            // The first number, from buttons A4-A1
    input  logic [3:0] b,            // The second number, from buttons B4-B1

    output logic [3:0] sum,          // a + b without the carry
    output logic       carry,        // The fifth bit of the sum: 1 when a + b > 15

    output logic [6:0] abcdefg_a,    // Segments a-g of each display: abcdefg [6] is a
    output logic [6:0] abcdefg_b,
    output logic [6:0] abcdefg_sum
);

    //------------------------------------------------------------------------
    // Four full adders.  Each adds one bit of a, one bit of b and the carry
    // from the bit below, and passes its own carry to the bit above.

    logic [4:0] c;

    assign c [0] = 1'b0;  // The carry into bit 0, like CARRY IN of the 4008 tied to GND

    for (genvar i = 0; i < 4; i ++)
    begin : full_adder
        assign sum [i]   = a [i] ^ b [i] ^ c [i];
        assign c [i + 1] = a [i] & b [i] | (a [i] ^ b [i]) & c [i];
    end

    assign carry = c [4];

    //------------------------------------------------------------------------
    // Three decoders.  Like the 4511, codes 10-15 blank the display, so the
    // sum shows only up to 9.

    function automatic logic [6:0] decode (input logic [3:0] code);
        case (code)
        4'd0:    decode = 7'b111_1110;
        4'd1:    decode = 7'b011_0000;
        4'd2:    decode = 7'b110_1101;
        4'd3:    decode = 7'b111_1001;
        4'd4:    decode = 7'b011_0011;
        4'd5:    decode = 7'b101_1011;
        4'd6:    decode = 7'b001_1111;
        4'd7:    decode = 7'b111_0000;
        4'd8:    decode = 7'b111_1111;
        4'd9:    decode = 7'b111_0011;
        default: decode = 7'b000_0000;
        endcase
    endfunction

    assign abcdefg_a   = decode (a);
    assign abcdefg_b   = decode (b);
    assign abcdefg_sum = decode (sum);

endmodule
