// Exercise BB1: the 4048 multifunction expandable 8-input gate.
//
// Generic version that matches the function table of the datasheet:
// Ka, Kb and Kc choose one of eight functions of the inputs A-H, which
// come in two groups of four.  Not tied to any chip.  Synthesizable.

module multifunction_gate
(
    input  logic       a,
    input  logic       b,
    input  logic       c,
    input  logic       d,
    input  logic [3:0] rest,  // E-H, rest [0] is E
    input  logic [2:0] k,     // k [0] is Ka, k [1] Kb, k [2] Kc

    output logic       j
);

    wire [3:0] group_1 = { d, c, b, a };
    wire [3:0] group_2 = rest;

    wire or_1  = | group_1;
    wire or_2  = | group_2;
    wire and_1 = & group_1;
    wire and_2 = & group_2;

    always_comb
        case ({ k [0], k [1], k [2] })   // Ka Kb Kc, as in the datasheet
        3'b000:  j = ~ (or_1 | or_2);    // NOR
        3'b001:  j =    or_1 | or_2;     // OR
        3'b010:  j =    or_1 & or_2;     // OR/AND
        3'b011:  j = ~ (or_1 & or_2);    // OR/NAND
        3'b100:  j =    and_1 & and_2;   // AND
        3'b101:  j = ~ (and_1 & and_2);  // NAND
        3'b110:  j = ~ (and_1 | and_2);  // AND/NOR
        default: j =    and_1 | and_2;   // AND/OR
        endcase

endmodule
