// Exercise BB6: an 8-to-3 priority encoder, like the 4532, whose output is
// shown on a 7-segment display through a decoder, like the 4511.
//
// Generic version that matches schematic 1, not tied to any chip.
// Synthesizable.

module priority_encoder
(
    input  logic [7:0] d,        // d [7] has the highest priority

    output logic [2:0] q,        // The number of the highest input at 1
    output logic       gs,       // Group select: some input is 1
    output logic       eo,       // Enable out: no input is 1
    output logic [6:0] abcdefg   // Segments a-g: abcdefg [6] is a, the top one
);

    //------------------------------------------------------------------------
    // The encoder: scan from the lowest input up, so that a higher input that
    // is 1 overwrites a lower one.  The loop is unrolled by synthesis.

    always_comb
    begin
        q = 3'd0;

        for (int i = 0; i < 8; i ++)
            if (d [i])
                q = 3' (i);
    end

    assign gs =   | d;
    assign eo = ~| d;

    //------------------------------------------------------------------------
    // The decoder: the digits 0-7 as the 4511 draws them.  Its 6 has no top
    // segment.

    always_comb
        case (q)
        3'd0:    abcdefg = 7'b111_1110;
        3'd1:    abcdefg = 7'b011_0000;
        3'd2:    abcdefg = 7'b110_1101;
        3'd3:    abcdefg = 7'b111_1001;
        3'd4:    abcdefg = 7'b011_0011;
        3'd5:    abcdefg = 7'b101_1011;
        3'd6:    abcdefg = 7'b001_1111;
        default: abcdefg = 7'b111_0000;
        endcase

endmodule
