Folding line procedure that ensures multi-byte utf-8 sequences are not broken across lines

    TO-DO: This all seems odd. Is it still needed, especially in python3?

def foldOneLine(outbuf, input, lineLength = 75):
    """
    Folding line procedure that ensures multi-byte utf-8 sequences are not broken across lines

    TO-DO: This all seems odd. Is it still needed, especially in python3?
    """

    if len(input) < lineLength:
        # Optimize for unfolded line case
        try:
            outbuf.write(bytes(input, 'UTF-8'))
        except Exception:
            # fall back on py2 syntax
            outbuf.write(input)

    else:
        # Look for valid utf8 range and write that out
        start = 0
        written = 0
        while written < len(input):
            # Start max length -1 chars on from where we are
            offset = start + lineLength - 1
            if offset >= len(input):
                line = input[start:]
                try:
                    outbuf.write(bytes(line, 'UTF-8'))
                except Exception:
                    # fall back on py2 syntax
                    outbuf.write(line)
                written = len(input)
            else:
                # Check whether next char is valid utf8 lead byte
                # while (input[offset] > 0x7F) and ((ord(input[offset]) & 0xC0) == 0x80):
                #    # Step back until we have a valid char
                #    offset -= 1

                line = input[start:offset]
                try:
                    outbuf.write(bytes(line, 'UTF-8'))
                    outbuf.write(bytes("\r\n ", 'UTF-8'))
                except Exception:
                    # fall back on py2 syntax
                    outbuf.write(line)
                    outbuf.write("\r\n ")
                written += offset - start
                start = offset
    try:
        outbuf.write(bytes("\r\n", 'UTF-8'))
    except Exception:
        # fall back on py2 syntax
        outbuf.write("\r\n")