module bcd_gates(
    input wire [9:0] SW,
    output wire [9:0] LEDR,
    output wire [6:0] HEX5, HEX3, HEX1, HEX0
);
    wire [3:0] x, y;
    wire invalid;
    assign x = SW[7:4];
    assign y = SW[3:0];
    assign invalid = (x[3] & (x[2] | x[1])) | (y[3] & (y[2] | y[1]));
    wire [3:0] raw, ones_digit;
    wire [4:0] carry;
    wire tens_digit, carry2, carry3;
    assign carry[0] = SW[8];

    genvar i;
    generate
        for (i = 0; i < 4; i = i + 1) begin : binary_columns
            assign raw[i] = x[i] ^ y[i] ^ carry[i];
            assign carry[i+1] = (x[i] & y[i]) | ((x[i] ^ y[i]) & carry[i]);
        end
    endgenerate
    assign LEDR = {invalid, 4'b0000, carry[4], raw};
    // Implement decimal carry and correction using Boolean gates.
    assign tens_digit = 1'b0;
    assign ones_digit = raw;
    bcd_gates_segment show_x(.x(x), .pins(HEX5));
    bcd_gates_segment show_y(.x(y), .pins(HEX3));
    bcd_gates_segment show_tens(.x({3'b000, tens_digit}), .pins(HEX1));
    bcd_gates_segment show_ones(.x(ones_digit), .pins(HEX0));
endmodule

module bcd_gates_segment(input wire [3:0] x, output wire [6:0] pins);
    assign pins[0] = (~x[0] & ~x[1] & x[2]) | (x[0] & ~x[1] & ~x[2] & ~x[3]);
    assign pins[1] = (~x[0] & x[1] & x[2]) | (x[0] & ~x[1] & x[2]);
    assign pins[2] = (~x[0] & x[1] & ~x[2]);
    assign pins[3] = (~x[0] & ~x[1] & x[2]) | (x[0] & ~x[1] & ~x[2] & ~x[3]) | (x[0] & x[1] & x[2]);
    assign pins[4] = (~x[1] & x[2]) | x[0];
    assign pins[5] = (x[1] & ~x[2]) | (x[0] & ~x[2] & ~x[3]) | (x[0] & x[1]);
    assign pins[6] = (~x[1] & ~x[2] & ~x[3]) | (x[0] & x[1] & x[2]);
endmodule
