// Exercise M9: a bit-mask merge, D = A AND Ka OR B AND Kb, built twice: as
// the 4019 does it (output d) and from separate AND and OR gates (output
// e).
//
// Generic version that matches schematic 1, not tied to any chip.  Both
// outputs are the same function, so they must always be equal; the
// testbench checks that.  Synthesizable.

module mask_merge
(
    input  logic [3:0] a,    // a [0] is A1
    input  logic [3:0] b,    // b [0] is B1
    input  logic       ka,
    input  logic       kb,

    output logic [3:0] d,    // As the 4019: four AND-OR select gates
    output logic [3:0] e     // From gates: eight AND and four OR
);

    // The 4019: each bit selects A, B, both or neither

    assign d = a & { 4 { ka } } | b & { 4 { kb } };

    // The same from basic gates, bit by bit

    for (genvar k = 0; k < 4; k ++)
    begin : bit_k
        wire a_term = a [k] & ka;  // A 4081 gate
        wire b_term = b [k] & kb;  // A gate of the other 4081

        assign e [k] = a_term | b_term;  // A 4071 gate
    end

endmodule
