def chunkit(msg, maxsend, minsend=0, pad='\n'):
    """
    chunkit iterates over a msg returning chunks of at most maxsend
    size, and of at least minsend size if non-zero. Padding will be
    added if required. This function currently requires that maxsend
    is at least large enough to hold 2 minsend chunks.
    """
    assert maxsend >= 2 * minsend
    sz = len(msg)
    nchunks = sz // maxsend
    lastmax = sz % maxsend
    if sz == 0:
        return
    elif nchunks == 1 and lastmax == 0:
        yield msg
        return
    elif nchunks == 0:
        assert lastmax != 0
        if lastmax < minsend:
            msg = msg + pad * (minsend - lastmax)
        yield msg
        return
    nchunks -= 1
    penultmax = maxsend
    if lastmax == 0:
        lastmax = maxsend
        nchunks -= 1
    elif lastmax < minsend:
        penultmax -= minsend - lastmax
        lastmax = minsend
    left = 0
    for unused in range(0, nchunks):
        yield msg[left:left + maxsend]
        left += maxsend
    right = left + penultmax
    yield msg[left:right]
    yield msg[right:]
