// CD4511B: BCD-to-7-segment latch, decoder and driver.
//
// Ports in pin order, named as in the datasheet: BCD inputs A-D (A is the
// lowest bit), segment outputs a-g.  The power pins, VSS (8) and VDD (16),
// are left out.  Synthesizable; LATCH ENABLE makes a latch, which FPGA
// tools accept but warn about.
//
// The outputs drive a common-cathode display through resistors: 1 lights
// the segment.  Codes 10 to 15 blank the display.  The chip draws 6 without
// the top segment and 9 without the bottom one.
//
// LAMP TEST (active low) lights all segments; BLANKING (active low) turns
// them all off; LAMP TEST wins.  LATCH ENABLE: 0 = the decoder follows the
// inputs, 1 = it keeps the code it had when LATCH ENABLE rose.

module cd4511
(
    input  logic bcd_b,         // Pin 1
    input  logic bcd_c,         // Pin 2
    input  logic lamp_test_n,   // Pin 3:  0 = all segments on
    input  logic blank_n,       // Pin 4:  0 = all segments off
    input  logic latch_enable,  // Pin 5:  1 = hold the code
    input  logic bcd_d,         // Pin 6
    input  logic bcd_a,         // Pin 7
                                // Pin 8:  VSS
    output logic seg_e,         // Pin 9
    output logic seg_d,         // Pin 10
    output logic seg_c,         // Pin 11
    output logic seg_b,         // Pin 12
    output logic seg_a,         // Pin 13
    output logic seg_g,         // Pin 14
    output logic seg_f          // Pin 15
                                // Pin 16: VDD
);

    logic [3:0] code;

    // This is a latch, but Verilator 5 does not see it and warns
    // verilator lint_off NOLATCH

    always_latch
        if (~ latch_enable)
            code = { bcd_d, bcd_c, bcd_b, bcd_a };

    logic [6:0] abcdefg;

    always_comb
        if (~ lamp_test_n)
            abcdefg = 7'b111_1111;
        else if (~ blank_n)
            abcdefg = 7'b000_0000;
        else
            case (code)
            4'd0:    abcdefg = 7'b111_1110;
            4'd1:    abcdefg = 7'b011_0000;
            4'd2:    abcdefg = 7'b110_1101;
            4'd3:    abcdefg = 7'b111_1001;
            4'd4:    abcdefg = 7'b011_0011;
            4'd5:    abcdefg = 7'b101_1011;
            4'd6:    abcdefg = 7'b001_1111;  // No top segment
            4'd7:    abcdefg = 7'b111_0000;
            4'd8:    abcdefg = 7'b111_1111;
            4'd9:    abcdefg = 7'b111_0011;  // No bottom segment
            default: abcdefg = 7'b000_0000;  // 10-15: blank
            endcase

    assign { seg_a, seg_b, seg_c, seg_d, seg_e, seg_f, seg_g } = abcdefg;

endmodule
