import struct


def sum_complement(fw, max_size):
    """Calculates the checksum of a firmware file using the sum complement
    method of adding each 32-bit word and the returning the two's complement
    as the checksum.

    Parameters
    ----------
    fw : file
        The firmware file (a binary buffer - e.g. a file opened in 'rb' mode)
    max_size : int
        The maximum size of the firmware file.

    Returns
    -------
    int
        The correction needed to make the checksum of the file == 0.
    """
    checksum = 0
    size = 0

    while True:
        word = fw.read(4)
        if not word:
            break
        checksum += struct.unpack("I", word)[0]
        size += 4

    if size > max_size:
        raise ValueError("File is too large")

    for _ in range(size, max_size, 4):
        checksum += 0xFFFFFFFF

    checksum &= 0xFFFFFFFF
    correction = checksum and (1 << 32) - checksum or 0

    return correction