// CD4048B: multifunction expandable 8-input gate.
//
// Ports in pin order, named as in the datasheet.  The power pins, VSS (8)
// and VDD (16), are left out.
//
// The model follows the logic diagram of the TI datasheet: every input is
// inverted and XORed with Ka; each group of four goes into a NAND whose
// output is XORed with ~Kb; both groups and ~EXPAND go into a 3-input NAND,
// XORed with ~Kc.  Ka Kb Kc choose the function:
//
//   000 NOR   001 OR   010 OR/AND   011 OR/NAND
//   100 AND   101 NAND 110 AND/NOR  111 AND/OR
//
// Kd = 0 turns the output off (high impedance), so that several 4048s can
// share a bus.  Synthesizable while Kd is 1; in an FPGA, keep Kd at 1.

module cd4048
(
    output logic j,       // Pin 1:  output, 3-state
    input  logic kd,      // Pin 2:  1 = output on
    input  logic h,       // Pin 3
    input  logic g,       // Pin 4
    input  logic f,       // Pin 5
    input  logic e,       // Pin 6
    input  logic kb,      // Pin 7
                          // Pin 8:  VSS
    input  logic kc,      // Pin 9
    input  logic ka,      // Pin 10
    input  logic d,       // Pin 11
    input  logic c,       // Pin 12
    input  logic b,       // Pin 13
    input  logic a,       // Pin 14
    input  logic expand   // Pin 15: GND when not used
                          // Pin 16: VDD
);

    wire [7:0] in_x = ~ { h, g, f, e, d, c, b, a } ^ { 8 { ka } };

    wire group_1 = ~ (& in_x [3:0]) ^ ~ kb;  // A, B, C, D
    wire group_2 = ~ (& in_x [7:4]) ^ ~ kb;  // E, F, G, H

    wire inner = ~ (group_1 & group_2 & ~ expand);
    wire z     = inner ^ ~ kc;

    assign j = kd ? z : 1'bz;

endmodule
