import hashlib


def applyIVFCLevel(hash, data, dataBlockSize):
    """ Poisons unhashed data of a IVFC level using the hash from the previous level """
    hashPos = 0
    dataPos = 0
    output = bytearray()
    dataLen = len(data)
    while (hashPos < len(hash)):
        hashChunk = hash[hashPos: hashPos + 0x20]
        tranSize = min(dataLen, dataBlockSize)
        dataChunk = data[dataPos: dataPos + tranSize]
        dataChunkAlign = dataChunk + b'\x00' * (dataBlockSize - tranSize)
        if hashlib.sha256(dataChunkAlign).digest() == hashChunk:
            output.extend(dataChunk)
        else:
            # fill unhashed data with 0xDD
            output.extend(b'\xDD' * len(dataChunk))
        hashPos += 0x20
        dataPos += dataBlockSize
        dataLen -= tranSize
        if dataLen <= 0:
            break
    return output