// Exercise BB3: a 4-bit magnitude comparator, like the 4063.
//
// Generic version that matches schematic 1, not tied to any chip.  It
// compares A and B the way a person does: from the most significant bit
// down, the first bit where they differ decides.  Synthesizable.

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

    output logic       a_gt_b,
    output logic       a_eq_b,
    output logic       a_lt_b
);

    always_comb
    begin
        a_gt_b = 1'b0;
        a_lt_b = 1'b0;

        // The loop is unrolled by synthesis into four stages of gates.
        // Once one output is 1, the lower bits no longer matter.

        for (int i = 3; i >= 0; i --)
            if (~ a_gt_b & ~ a_lt_b)
            begin
                a_gt_b =   a [i] & ~ b [i];
                a_lt_b = ~ a [i] &   b [i];
            end
    end

    assign a_eq_b = ~ a_gt_b & ~ a_lt_b;

endmodule
