--- xmlIO.c	Thu Mar 25 10:27:22 2010
+++ xmlIO-new.c	Mon Sep 20 12:26:58 2010
@@ -3457,6 +3457,53 @@
 	                   &chunk, str, &cons);
 	    if ((ret < 0) || (chunk == 0)) /* chunk==0 => nothing done */
 	        return(-1);
+        
+        /* Remove incomplete UTF-8 bytes... */
+		if (out->buffer->content[out->buffer->use + chunk - 1]  >= 0x80) {
+			/* There may be a problem. Let's see if the last UTF-8 char
+                    is complete */
+			size_t tmpLen = 0, expectedLen = 2;
+			unsigned char c = 0;
+
+			/* Find suspicious bytes. */
+			while ((c = out->buffer->content[out->buffer->use + chunk - tmpLen - 1])  >= 0x80) {
+				tmpLen++;
+				/*0xxxxxxx
+				  110yyyyy 10xxxxxx -> >=0xc0
+				  1110zzzz 10yyyyyy 10xxxxxx >=0xe0
+				  11110www 10zzzzzz 10yyyyyy 10xxxxxx >=0xf0*/
+				if ((tmpLen >= cons || tmpLen >= chunk) && c < 0xc0) {
+					/* We couldn't find first UTF-8 byte. */
+					xmlIOErr(XML_IO_ENCODER, NULL);
+					out->error = XML_IO_ENCODER;
+					return(-1);
+				}
+				if (c >= 0xc0) {
+					/* We found the first byte of the UTF-8 sequence,
+                           let's check its length. */
+					if (c >= 0xf0) {
+						expectedLen = 4;
+					} else if (c >= 0xe0) {
+						expectedLen = 3;
+					}
+					if (tmpLen != expectedLen) {
+						/* A problem found, can we do anything? */
+						if (tmpLen > expectedLen) {
+							/* No, sequence is too long. */
+							xmlIOErr(XML_IO_ENCODER, NULL);
+							out->error = XML_IO_ENCODER;
+							return(-1);
+						}
+						/* We remove the incomplete UTF-8 bytes. */
+						chunk -= tmpLen;
+						cons -= tmpLen;
+					}
+					break;
+				}
+
+			}
+		}
+        
 	    out->buffer->use += chunk;
 	    out->buffer->content[out->buffer->use] = 0;
 
