// Exercise BB10: a 4-bit adder and subtractor, as built from the 40181 ALU
// with sub driving its function select and carry inputs.
//
// Generic version that matches schematic 1, not tied to any chip.  With
// sub = 0, f = a + b; with sub = 1, f = a - b, computed as a + ~b + 1, the
// way the ALU does it.  carry_n is the carry out of the 40181, active low:
// in addition it is 0 when the sum does not fit into 4 bits; in
// subtraction it is 0 when a >= b and 1 when a < b, that is, when f is
// negative.  all_ones is the A=B output of the 40181: 1 when f is 1111.
// Synthesizable.

module add_sub
(
    input  logic [3:0] a,
    input  logic [3:0] b,
    input  logic       sub,

    output logic [3:0] f,
    output logic       carry_n,
    output logic       all_ones
);

    wire [3:0] b_in  = sub ? ~ b : b;
    wire [4:0] total = { 1'b0, a } + { 1'b0, b_in } + { 4'b0, sub };

    assign f        = total [3:0];
    assign carry_n  = ~ total [4];
    assign all_ones = & f;

endmodule
