def chunk(line,chunksize,delimiter=None):
    """Chop a string into 'chunks' no greater than a specified size

    Given a string, return a list where each item is a substring
    no longer than the specified 'chunksize'.

    If delimiter is not None then the chunking will attempt to
    chop the substrings on that delimiter. If a delimiter can't be
    located (or not is specified) then the substrings will all
    be of length 'chunksize'.

    """
    chunks = []
    # Loop over and chop up string until the remainder is shorter
    # than chunksize
    while len(line) > chunksize:
        if delimiter is not None:
            try:
                # Locate nearest delimiter before the chunksize limit
                i = line[:chunksize].rindex(' ')
            except ValueError:
                # Unable to locate delimiter so split on the chunksize
                # limit
                i = chunksize
        else:
            i = chunksize
        chunks.append(line[:i])
        line = line[i:]
    # Append the remainder and return
    chunks.append(line)
    return chunks