Upgrade libxml2 to 2.7.3 to patch some vulnerabilities.
diff --git a/HTMLparser.c b/HTMLparser.c
index 38af5e3..24b0fc0 100644
--- a/HTMLparser.c
+++ b/HTMLparser.c
@@ -2143,6 +2143,7 @@
     cur->refs = NULL;
     cur->_private = NULL;
     cur->charset = XML_CHAR_ENCODING_UTF8;
+    cur->properties = XML_DOC_HTML | XML_DOC_USERBUILT;
     if ((ExternalID != NULL) ||
 	(URI != NULL))
 	xmlCreateIntSubset(cur, BAD_CAST "html", ExternalID, URI);
@@ -2767,6 +2768,7 @@
     xmlChar buf[HTML_PARSER_BIG_BUFFER_SIZE + 5];
     int nbchar = 0;
     int cur, l;
+    int chunk = 0;
 
     SHRINK;
     cur = CUR_CHAR(l);
@@ -2797,6 +2799,12 @@
 	    nbchar = 0;
 	}
 	NEXTL(l);
+        chunk++;
+        if (chunk > HTML_PARSER_BUFFER_SIZE) {
+            chunk = 0;
+            SHRINK;
+            GROW;
+        }
 	cur = CUR_CHAR(l);
 	if (cur == 0) {
 	    SHRINK;
@@ -3115,9 +3123,9 @@
 	        val = val * 16 + (CUR - 'A') + 10;
 	    else {
 	        htmlParseErr(ctxt, XML_ERR_INVALID_HEX_CHARREF,
-		             "htmlParseCharRef: invalid hexadecimal value\n",
+		             "htmlParseCharRef: missing semicolumn\n",
 			     NULL, NULL);
-		return(0);
+		break;
 	    }
 	    NEXT;
 	}
@@ -3130,9 +3138,9 @@
 	        val = val * 10 + (CUR - '0');
 	    else {
 	        htmlParseErr(ctxt, XML_ERR_INVALID_DEC_CHARREF,
-		             "htmlParseCharRef: invalid decimal value\n",
+		             "htmlParseCharRef: missing semicolumn\n",
 			     NULL, NULL);
-		return(0);
+		break;
 	    }
 	    NEXT;
 	}
@@ -3423,7 +3431,7 @@
  *
  * [NS 10] EmptyElement ::= '<' QName (S Attribute)* S? '/>'
  *
- * Returns 0 in case of success and -1 in case of error.
+ * Returns 0 in case of success, -1 in case of error and 1 if discarded
  */
 
 static int
@@ -3436,6 +3444,7 @@
     int maxatts;
     int meta = 0;
     int i;
+    int discardtag = 0;
 
     if ((ctxt == NULL) || (ctxt->input == NULL)) {
 	htmlParseErr(ctxt, XML_ERR_INTERNAL_ERROR,
@@ -3480,14 +3489,16 @@
 	htmlParseErr(ctxt, XML_HTML_STRUCURE_ERROR,
 	             "htmlParseStartTag: misplaced <html> tag\n",
 		     name, NULL);
-	return 0;
+	discardtag = 1;
+	ctxt->depth++;
     }
     if ((ctxt->nameNr != 1) && 
 	(xmlStrEqual(name, BAD_CAST"head"))) {
 	htmlParseErr(ctxt, XML_HTML_STRUCURE_ERROR,
 	             "htmlParseStartTag: misplaced <head> tag\n",
 		     name, NULL);
-	return 0;
+	discardtag = 1;
+	ctxt->depth++;
     }
     if (xmlStrEqual(name, BAD_CAST"body")) {
 	int indx;
@@ -3496,9 +3507,8 @@
 		htmlParseErr(ctxt, XML_HTML_STRUCURE_ERROR,
 		             "htmlParseStartTag: misplaced <body> tag\n",
 			     name, NULL);
-		while ((IS_CHAR_CH(CUR)) && (CUR != '>'))
-		    NEXT;
-		return 0;
+		discardtag = 1;
+		ctxt->depth++;
 	    }
 	}
     }
@@ -3597,12 +3607,14 @@
     /*
      * SAX: Start of Element !
      */
-    htmlnamePush(ctxt, name);
-    if ((ctxt->sax != NULL) && (ctxt->sax->startElement != NULL)) {
-	if (nbatts != 0)
-            ctxt->sax->startElement(ctxt->userData, name, atts);
-	else
-            ctxt->sax->startElement(ctxt->userData, name, NULL);
+    if (!discardtag) {
+	htmlnamePush(ctxt, name);
+	if ((ctxt->sax != NULL) && (ctxt->sax->startElement != NULL)) {
+	    if (nbatts != 0)
+		ctxt->sax->startElement(ctxt->userData, name, atts);
+	    else
+		ctxt->sax->startElement(ctxt->userData, name, NULL);
+	}
     }
 
     if (atts != NULL) {
@@ -3612,7 +3624,7 @@
 	}
     }
 
-    return 0;
+    return(discardtag);
 }
 
 /**
@@ -3647,7 +3659,6 @@
     name = htmlParseHTMLName(ctxt);
     if (name == NULL)
         return (0);
-
     /*
      * We should definitely be at the ending "S? '>'" part
      */
@@ -3668,6 +3679,18 @@
         NEXT;
 
     /*
+     * if we ignored misplaced tags in htmlParseStartTag don't pop them
+     * out now.
+     */
+    if ((ctxt->depth > 0) &&
+        (xmlStrEqual(name, BAD_CAST "html") ||
+         xmlStrEqual(name, BAD_CAST "body") ||
+	 xmlStrEqual(name, BAD_CAST "head"))) {
+	ctxt->depth--;
+	return (0);
+    }
+
+    /*
      * If the name read is not one of the element in the parsing stack
      * then return, it's just an error.
      */
@@ -3991,7 +4014,7 @@
 
     failed = htmlParseStartTag(ctxt);
     name = ctxt->name;
-    if (failed || (name == NULL)) {
+    if ((failed == -1) || (name == NULL)) {
 	if (CUR == '>')
 	    NEXT;
         return;
@@ -4097,6 +4120,8 @@
 
 int
 htmlParseDocument(htmlParserCtxtPtr ctxt) {
+    xmlChar start[4];
+    xmlCharEncoding enc;
     xmlDtdPtr dtd;
 
     xmlInitParser();
@@ -4116,6 +4141,23 @@
     if ((ctxt->sax) && (ctxt->sax->setDocumentLocator))
         ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator);
 
+    if ((ctxt->encoding == (const xmlChar *)XML_CHAR_ENCODING_NONE) &&
+        ((ctxt->input->end - ctxt->input->cur) >= 4)) {
+	/*
+	 * Get the 4 first bytes and decode the charset
+	 * if enc != XML_CHAR_ENCODING_NONE
+	 * plug some encoding conversion routines.
+	 */
+	start[0] = RAW;
+	start[1] = NXT(1);
+	start[2] = NXT(2);
+	start[3] = NXT(3);
+	enc = xmlDetectCharEncoding(&start[0], 4);
+	if (enc != XML_CHAR_ENCODING_NONE) {
+	    xmlSwitchEncoding(ctxt, enc);
+	}
+    }
+
     /*
      * Wipe out everything which is before the first '<'
      */
@@ -4135,10 +4177,10 @@
     while (((CUR == '<') && (NXT(1) == '!') &&
             (NXT(2) == '-') && (NXT(3) == '-')) ||
 	   ((CUR == '<') && (NXT(1) == '?'))) {
-        htmlParseComment(ctxt);	   
-        htmlParsePI(ctxt);	   
+        htmlParseComment(ctxt);
+        htmlParsePI(ctxt);
 	SKIP_BLANKS;
-    }	   
+    }
 
 
     /*
@@ -4893,7 +4935,7 @@
 
 		failed = htmlParseStartTag(ctxt);
 		name = ctxt->name;
-		if (failed ||
+		if ((failed == -1) ||
 		    (name == NULL)) {
 		    if (CUR == '>')
 			NEXT;
@@ -5957,8 +5999,12 @@
         xmlCharEncodingHandlerPtr hdlr;
 
 	hdlr = xmlFindCharEncodingHandler(encoding);
-	if (hdlr != NULL)
+	if (hdlr != NULL) {
 	    xmlSwitchToEncoding(ctxt, hdlr);
+	    if (ctxt->input->encoding != NULL)
+	      xmlFree((xmlChar *) ctxt->input->encoding);
+            ctxt->input->encoding = xmlStrdup((xmlChar *)encoding);
+        }
     }
     if ((URL != NULL) && (ctxt->input != NULL) &&
         (ctxt->input->filename == NULL))
diff --git a/HTMLtree.c b/HTMLtree.c
index e79d118..37999f7 100644
--- a/HTMLtree.c
+++ b/HTMLtree.c
@@ -316,6 +316,11 @@
 }
 
 #ifdef LIBXML_OUTPUT_ENABLED
+/*
+ * private routine exported from xmlIO.c
+ */
+xmlOutputBufferPtr
+xmlAllocOutputBufferInternal(xmlCharEncodingHandlerPtr encoder);
 /************************************************************************
  *									*
  * 			Output error handlers				*
@@ -566,7 +571,7 @@
     if (handler == NULL)
 	handler = xmlFindCharEncodingHandler("ascii");
 
-    buf = xmlAllocOutputBuffer(handler);
+    buf = xmlAllocOutputBufferInternal(handler);
     if (buf == NULL) {
 	*mem = NULL;
 	*size = 0;
diff --git a/SAX2.c b/SAX2.c
index 9739831..164409c 100644
--- a/SAX2.c
+++ b/SAX2.c
@@ -11,6 +11,7 @@
 #include "libxml.h"
 #include <stdlib.h>
 #include <string.h>
+#include <limits.h>
 #include <libxml/xmlmemory.h>
 #include <libxml/tree.h>
 #include <libxml/parser.h>
@@ -26,6 +27,11 @@
 #include <libxml/HTMLtree.h>
 #include <libxml/globals.h>
 
+/* Define SIZE_T_MAX unless defined through <limits.h>. */
+#ifndef SIZE_T_MAX
+# define SIZE_T_MAX     ((size_t)-1)
+#endif /* !SIZE_T_MAX */
+
 /* #define DEBUG_SAX2 */
 /* #define DEBUG_SAX2_TREE */
 
@@ -580,7 +586,8 @@
 	    return(NULL);
 	}
 	ret->owner = 1;
-	ret->checked = 1;
+	if (ret->checked == 0)
+	    ret->checked = 1;
     }
     return(ret);
 }
@@ -957,6 +964,8 @@
 #ifdef LIBXML_HTML_ENABLED
 	if (ctxt->myDoc == NULL)
 	    ctxt->myDoc = htmlNewDocNoDtD(NULL, NULL);
+	ctxt->myDoc->properties = XML_DOC_HTML;
+	ctxt->myDoc->parseFlags = ctxt->options;
 	if (ctxt->myDoc == NULL) {
 	    xmlSAX2ErrMemory(ctxt, "xmlSAX2StartDocument");
 	    return;
@@ -972,6 +981,10 @@
     } else {
 	doc = ctxt->myDoc = xmlNewDoc(ctxt->version);
 	if (doc != NULL) {
+	    doc->properties = 0;
+	    if (ctxt->options & XML_PARSE_OLD10)
+	        doc->properties |= XML_DOC_OLD10;
+	    doc->parseFlags = ctxt->options;
 	    if (ctxt->encoding != NULL)
 		doc->encoding = xmlStrdup(ctxt->encoding);
 	    else
@@ -1837,6 +1850,9 @@
     } else
 	ret->content = (xmlChar *) intern;
 
+    if (ctxt->input != NULL)
+        ret->line = ctxt->input->line;
+
     if ((__xmlRegisterCallbacks) && (xmlRegisterNodeDefaultValue))
 	xmlRegisterNodeDefaultValue(ret);
     return(ret);
@@ -2366,7 +2382,9 @@
     xmlGenericError(xmlGenericErrorContext,
 	    "add xmlSAX2Reference %s to %s \n", name, ctxt->node->name);
 #endif
-    xmlAddChild(ctxt->node, ret);
+    if (xmlAddChild(ctxt->node, ret) == NULL) {
+        xmlFreeNode(ret);
+    }
 }
 
 /**
@@ -2443,9 +2461,19 @@
 	               (xmlDictOwns(ctxt->dict, lastChild->content))) {
 		lastChild->content = xmlStrdup(lastChild->content);
 	    }
+            if (((size_t)ctxt->nodelen + (size_t)len > XML_MAX_TEXT_LENGTH) &&
+                ((ctxt->options & XML_PARSE_HUGE) == 0)) {
+                xmlSAX2ErrMemory(ctxt, "xmlSAX2Characters: huge text node");
+                return;
+            }
+	    if ((size_t)ctxt->nodelen > SIZE_T_MAX - (size_t)len || 
+	        (size_t)ctxt->nodemem + (size_t)len > SIZE_T_MAX / 2) {
+                xmlSAX2ErrMemory(ctxt, "xmlSAX2Characters overflow prevented");
+                return;
+	    }
 	    if (ctxt->nodelen + len >= ctxt->nodemem) {
 		xmlChar *newbuf;
-		int size;
+		size_t size;
 
 		size = ctxt->nodemem + len;
 		size *= 2;
diff --git a/catalog.c b/catalog.c
index ee3f8f2..af84b7c 100644
--- a/catalog.c
+++ b/catalog.c
@@ -2616,6 +2616,8 @@
 	return(ret);
     if (sysID != NULL)
 	ret = xmlCatalogGetSGMLSystem(catal->sgml, sysID);
+    if (ret != NULL)
+	return(ret);
     return(NULL);
 }
 
@@ -2912,7 +2914,7 @@
 
 	sgml = xmlCatalogSGMLResolve(catal, NULL, URI);
 	if (sgml != NULL)
-            sgml = xmlStrdup(sgml);
+            ret = xmlStrdup(sgml);
     }
     return(ret);
 }
diff --git a/config.h b/config.h
index 1848ef0..af849ae 100644
--- a/config.h
+++ b/config.h
@@ -1,3 +1,7 @@
+/* config.h.  Generated from config.h.in by configure.  */
+/* config.h.in.  Generated from configure.in by autoheader.  */
+#define PACKAGE "libxml2"
+#define VERSION "2.7.3"
 /* #undef HAVE_LIBZ */
 /* #undef HAVE_LIBM */
 #define HAVE_ISINF 
@@ -71,7 +75,7 @@
 #define HAVE_FTIME 1
 
 /* Define if getaddrinfo is there */
-/* #undef HAVE_GETADDRINFO */
+/* #undef HAVE_GETADDRINFO  */
 
 /* Define to 1 if you have the `gettimeofday' function. */
 #define HAVE_GETTIMEOFDAY 1
@@ -82,6 +86,9 @@
 /* Define to 1 if you have the <inttypes.h> header file. */
 #define HAVE_INTTYPES_H 1
 
+/* Define to 1 if you have the <inttypes.h.h> header file. */
+/* #undef HAVE_INTTYPES_H_H */
+
 /* Define if isinf is there */
 #define HAVE_ISINF 
 
@@ -101,7 +108,7 @@
 /* #undef HAVE_LIBREADLINE */
 
 /* Have compression library */
-//#define HAVE_LIBZ 1
+/* #undef HAVE_LIBZ */
 
 /* Define to 1 if you have the <limits.h> header file. */
 #define HAVE_LIMITS_H 1
@@ -109,6 +116,9 @@
 /* Define to 1 if you have the `localtime' function. */
 #define HAVE_LOCALTIME 1
 
+/* Define to 1 if you have the <malloc.h> header file. */
+/* #undef HAVE_MALLOC_H 1 Already defined in AndroidConfig.h */
+
 /* Define to 1 if you have the <math.h> header file. */
 #define HAVE_MATH_H 1
 
@@ -232,10 +242,61 @@
 #define HAVE_VSPRINTF 1
 
 /* Define to 1 if you have the <zlib.h> header file. */
-//#define HAVE_ZLIB_H 1
+/* #undef HAVE_ZLIB_H */
 
 /* Define to 1 if you have the `_stat' function. */
 /* #undef HAVE__STAT */
 
 /* Whether __va_copy() is available */
 /* #undef HAVE___VA_COPY */
+
+/* Define as const if the declaration of iconv() needs const. */
+/* #undef ICONV_CONST */
+
+/* Name of package */
+#define PACKAGE "libxml2"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT ""
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME ""
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING ""
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME ""
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION ""
+
+/* Define to 1 if the C compiler supports function prototypes. */
+#define PROTOTYPES 1
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Support for IPv6 */
+/* #undef SUPPORT_IP6 */
+
+/* Version number of package */
+#define VERSION "2.7.3"
+
+/* Determine what socket length (socklen_t) data type is */
+#define XML_SOCKLEN_T socklen_t
+
+/* Using the Win32 Socket implementation */
+/* #undef _WINSOCKAPI_ */
+
+/* Define like PROTOTYPES; this can be used by system headers. */
+#define __PROTOTYPES 1
+
+/* Win32 Std C name mangling work-around */
+/* #undef snprintf */
+
+/* ss_family is not defined here, use __ss_family instead */
+/* #undef ss_family */
+
+/* Win32 Std C name mangling work-around */
+/* #undef vsnprintf */
diff --git a/debugXML.c b/debugXML.c
index 3985ad3..de6fd6c 100644
--- a/debugXML.c
+++ b/debugXML.c
@@ -320,7 +320,8 @@
     }
     if (node->next == NULL) {
 	if ((node->parent != NULL) && (node->type != XML_ATTRIBUTE_NODE) &&
-	    (node->parent->last != node))
+	    (node->parent->last != node) &&
+	    (node->parent->type == XML_ELEMENT_NODE))
 	    xmlDebugErr(ctxt, XML_CHECK_NO_NEXT,
                     "Node has no next and not last of parent list\n");
     } else {
@@ -3244,6 +3245,7 @@
                             "Unknown command %s\n", command);
         }
         free(cmdline);          /* not xmlFree here ! */
+	cmdline = NULL;
     }
 #ifdef LIBXML_XPATH_ENABLED
     xmlXPathFreeContext(ctxt->pctxt);
diff --git a/dict.c b/dict.c
index 3b4054f..0e07e8d 100644
--- a/dict.c
+++ b/dict.c
@@ -20,18 +20,48 @@
 #include "libxml.h"
 
 #include <string.h>
+#ifdef HAVE_STDINT_H
+#include <stdint.h>
+#else
+#ifdef HAVE_INTTYPES_H
+#include <inttypes.h>
+#elif defined(WIN32)
+typedef unsigned __int32 uint32_t;
+#endif
+#endif
 #include <libxml/tree.h>
 #include <libxml/dict.h>
 #include <libxml/xmlmemory.h>
 #include <libxml/xmlerror.h>
 #include <libxml/globals.h>
 
-#define MAX_HASH_LEN 4
+/* #define DEBUG_GROW */
+/* #define DICT_DEBUG_PATTERNS */
+
+#define MAX_HASH_LEN 3
 #define MIN_DICT_SIZE 128
 #define MAX_DICT_HASH 8 * 2048
+#define WITH_BIG_KEY
 
-/* #define ALLOW_REMOVAL */
-/* #define DEBUG_GROW */
+#ifdef WITH_BIG_KEY
+#define xmlDictComputeKey(dict, name, len)			\
+    (((dict)->size == MIN_DICT_SIZE) ?				\
+     xmlDictComputeFastKey(name, len) :				\
+     xmlDictComputeBigKey(name, len))
+
+#define xmlDictComputeQKey(dict, prefix, plen, name, len)	\
+    (((prefix) == NULL) ?					\
+      (xmlDictComputeKey(dict, name, len)) :			\
+      (((dict)->size == MIN_DICT_SIZE) ?			\
+       xmlDictComputeFastQKey(prefix, plen, name, len) :	\
+       xmlDictComputeBigQKey(prefix, plen, name, len)))
+
+#else /* !WITH_BIG_KEY */
+#define xmlDictComputeKey(dict, name, len)			\
+        xmlDictComputeFastKey(name, len)
+#define xmlDictComputeQKey(dict, prefix, plen, name, len)	\
+        xmlDictComputeFastQKey(prefix, plen, name, len)
+#endif /* WITH_BIG_KEY */
 
 /*
  * An entry in the dictionnary
@@ -43,6 +73,7 @@
     const xmlChar *name;
     int len;
     int valid;
+    unsigned long okey;
 };
 
 typedef struct _xmlDictStrings xmlDictStrings;
@@ -60,7 +91,6 @@
  */
 struct _xmlDict {
     int ref_counter;
-    xmlRMutexPtr mutex;
 
     struct _xmlDictEntry *dict;
     int size;
@@ -130,6 +160,9 @@
     const xmlChar *ret;
     int size = 0; /* + sizeof(_xmlDictStrings) == 1024 */
 
+#ifdef DICT_DEBUG_PATTERNS
+    fprintf(stderr, "-");
+#endif
     pool = dict->strings;
     while (pool != NULL) {
 	if (pool->end - pool->free > namelen)
@@ -154,12 +187,16 @@
 	pool->end = &pool->array[size];
 	pool->next = dict->strings;
 	dict->strings = pool;
+#ifdef DICT_DEBUG_PATTERNS
+        fprintf(stderr, "+");
+#endif
     }
 found_pool:
     ret = pool->free;
     memcpy(pool->free, name, namelen);
     pool->free += namelen;
     *(pool->free++) = 0;
+    pool->nbStrings++;
     return(ret);
 }
 
@@ -167,6 +204,7 @@
  * xmlDictAddQString:
  * @dict: the dictionnary
  * @prefix: the prefix of the userdata
+ * @plen: the prefix length
  * @name: the name of the userdata
  * @len: the length of the name, if -1 it is recomputed
  *
@@ -175,20 +213,21 @@
  * Returns the pointer of the local string, or NULL in case of error.
  */
 static const xmlChar *
-xmlDictAddQString(xmlDictPtr dict, const xmlChar *prefix,
+xmlDictAddQString(xmlDictPtr dict, const xmlChar *prefix, int plen,
                  const xmlChar *name, int namelen)
 {
     xmlDictStringsPtr pool;
     const xmlChar *ret;
     int size = 0; /* + sizeof(_xmlDictStrings) == 1024 */
-    int plen;
 
     if (prefix == NULL) return(xmlDictAddString(dict, name, namelen));
-    plen = xmlStrlen(prefix);
 
+#ifdef DICT_DEBUG_PATTERNS
+    fprintf(stderr, "=");
+#endif
     pool = dict->strings;
     while (pool != NULL) {
-	if (pool->end - pool->free > namelen)
+	if (pool->end - pool->free > namelen + plen + 1)
 	    goto found_pool;
 	if (pool->size > size) size = pool->size;
 	pool = pool->next;
@@ -199,8 +238,8 @@
     if (pool == NULL) {
         if (size == 0) size = 1000;
 	else size *= 4; /* exponential growth */
-        if (size < 4 * namelen) 
-	    size = 4 * namelen; /* just in case ! */
+        if (size < 4 * (namelen + plen + 1))
+	    size = 4 * (namelen + plen + 1); /* just in case ! */
 	pool = (xmlDictStringsPtr) xmlMalloc(sizeof(xmlDictStrings) + size);
 	if (pool == NULL)
 	    return(NULL);
@@ -210,27 +249,106 @@
 	pool->end = &pool->array[size];
 	pool->next = dict->strings;
 	dict->strings = pool;
+#ifdef DICT_DEBUG_PATTERNS
+        fprintf(stderr, "+");
+#endif
     }
 found_pool:
     ret = pool->free;
     memcpy(pool->free, prefix, plen);
     pool->free += plen;
     *(pool->free++) = ':';
-    namelen -= plen + 1;
     memcpy(pool->free, name, namelen);
     pool->free += namelen;
     *(pool->free++) = 0;
+    pool->nbStrings++;
     return(ret);
 }
 
+#ifdef WITH_BIG_KEY
 /*
- * xmlDictComputeKey:
- * Calculate the hash key
+ * xmlDictComputeBigKey:
+ *
+ * Calculate a hash key using a good hash function that works well for
+ * larger hash table sizes.
+ *
+ * Hash function by "One-at-a-Time Hash" see
+ * http://burtleburtle.net/bob/hash/doobs.html
+ */
+
+static uint32_t
+xmlDictComputeBigKey(const xmlChar* data, int namelen) {
+    uint32_t hash;
+    int i;
+
+    if (namelen <= 0 || data == NULL) return(0);
+
+    hash = 0;
+
+    for (i = 0;i < namelen; i++) {
+        hash += data[i];
+	hash += (hash << 10);
+	hash ^= (hash >> 6);
+    }
+    hash += (hash << 3);
+    hash ^= (hash >> 11);
+    hash += (hash << 15);
+
+    return hash;
+}
+
+/*
+ * xmlDictComputeBigQKey:
+ *
+ * Calculate a hash key for two strings using a good hash function
+ * that works well for larger hash table sizes.
+ *
+ * Hash function by "One-at-a-Time Hash" see
+ * http://burtleburtle.net/bob/hash/doobs.html
+ *
+ * Neither of the two strings must be NULL.
  */
 static unsigned long
-xmlDictComputeKey(const xmlChar *name, int namelen) {
+xmlDictComputeBigQKey(const xmlChar *prefix, int plen,
+                      const xmlChar *name, int len)
+{
+    uint32_t hash;
+    int i;
+
+    hash = 0;
+
+    for (i = 0;i < plen; i++) {
+        hash += prefix[i];
+	hash += (hash << 10);
+	hash ^= (hash >> 6);
+    }
+    hash += ':';
+    hash += (hash << 10);
+    hash ^= (hash >> 6);
+
+    for (i = 0;i < len; i++) {
+        hash += name[i];
+	hash += (hash << 10);
+	hash ^= (hash >> 6);
+    }
+    hash += (hash << 3);
+    hash ^= (hash >> 11);
+    hash += (hash << 15);
+
+    return hash;
+}
+#endif /* WITH_BIG_KEY */
+
+/*
+ * xmlDictComputeFastKey:
+ *
+ * Calculate a hash key using a fast hash function that works well
+ * for low hash table fill.
+ */
+static unsigned long
+xmlDictComputeFastKey(const xmlChar *name, int namelen) {
     unsigned long value = 0L;
-    
+
     if (name == NULL) return(0);
     value = *name;
     value <<= 5;
@@ -254,24 +372,24 @@
 }
 
 /*
- * xmlDictComputeQKey:
- * Calculate the hash key
+ * xmlDictComputeFastQKey:
+ *
+ * Calculate a hash key for two strings using a fast hash function
+ * that works well for low hash table fill.
+ *
+ * Neither of the two strings must be NULL.
  */
 static unsigned long
-xmlDictComputeQKey(const xmlChar *prefix, const xmlChar *name, int len)
+xmlDictComputeFastQKey(const xmlChar *prefix, int plen,
+                       const xmlChar *name, int len)
 {
     unsigned long value = 0L;
-    int plen;
-    
-    if (prefix == NULL)
-        return(xmlDictComputeKey(name, len));
 
-    plen = xmlStrlen(prefix);
     if (plen == 0)
 	value += 30 * (unsigned long) ':';
     else
 	value += 30 * (*prefix);
-    
+
     if (len > 10) {
         value += name[len - (plen + 1 + 1)];
         len = 10;
@@ -326,7 +444,11 @@
     if (!xmlDictInitialized)
         if (!xmlInitializeDict())
             return(NULL);
- 
+
+#ifdef DICT_DEBUG_PATTERNS
+    fprintf(stderr, "C");
+#endif
+
     dict = xmlMalloc(sizeof(xmlDict));
     if (dict) {
         dict->ref_counter = 1;
@@ -337,11 +459,8 @@
 	dict->strings = NULL;
 	dict->subdict = NULL;
         if (dict->dict) {
-            if ((dict->mutex = xmlNewRMutex()) != NULL) {
-                memset(dict->dict, 0, MIN_DICT_SIZE * sizeof(xmlDictEntry));
-                return(dict);
-            }
-            xmlFree(dict->dict);
+	    memset(dict->dict, 0, MIN_DICT_SIZE * sizeof(xmlDictEntry));
+	    return(dict);
         }
         xmlFree(dict);
     }
@@ -362,8 +481,11 @@
 xmlDictPtr
 xmlDictCreateSub(xmlDictPtr sub) {
     xmlDictPtr dict = xmlDictCreate();
-  
+
     if ((dict != NULL) && (sub != NULL)) {
+#ifdef DICT_DEBUG_PATTERNS
+        fprintf(stderr, "R");
+#endif
         dict->subdict = sub;
 	xmlDictReference(dict->subdict);
     }
@@ -402,14 +524,16 @@
  */
 static int
 xmlDictGrow(xmlDictPtr dict, int size) {
-    unsigned long key;
+    unsigned long key, okey;
     int oldsize, i;
     xmlDictEntryPtr iter, next;
     struct _xmlDictEntry *olddict;
 #ifdef DEBUG_GROW
     unsigned long nbElem = 0;
 #endif
-  
+    int ret = 0;
+    int keep_keys = 1;
+
     if (dict == NULL)
 	return(-1);
     if (size < 8)
@@ -417,11 +541,17 @@
     if (size > 8 * 2048)
 	return(-1);
 
+#ifdef DICT_DEBUG_PATTERNS
+    fprintf(stderr, "*");
+#endif
+
     oldsize = dict->size;
     olddict = dict->dict;
     if (olddict == NULL)
         return(-1);
-  
+    if (oldsize == MIN_DICT_SIZE)
+        keep_keys = 0;
+
     dict->dict = xmlMalloc(size * sizeof(xmlDictEntry));
     if (dict->dict == NULL) {
 	dict->dict = olddict;
@@ -431,17 +561,44 @@
     dict->size = size;
 
     /*	If the two loops are merged, there would be situations where
-	a new entry needs to allocated and data copied into it from 
-	the main dict. So instead, we run through the array twice, first
-	copying all the elements in the main array (where we can't get
-	conflicts) and then the rest, so we only free (and don't allocate)
+	a new entry needs to allocated and data copied into it from
+	the main dict. It is nicer to run through the array twice, first
+	copying all the elements in the main array (less probability of
+	allocate) and then the rest, so we only free in the second loop.
     */
     for (i = 0; i < oldsize; i++) {
-	if (olddict[i].valid == 0) 
+	if (olddict[i].valid == 0)
 	    continue;
-	key = xmlDictComputeKey(olddict[i].name, olddict[i].len) % dict->size;
-	memcpy(&(dict->dict[key]), &(olddict[i]), sizeof(xmlDictEntry));
-	dict->dict[key].next = NULL;
+
+	if (keep_keys)
+	    okey = olddict[i].okey;
+	else
+	    okey = xmlDictComputeKey(dict, olddict[i].name, olddict[i].len);
+	key = okey % dict->size;
+
+	if (dict->dict[key].valid == 0) {
+	    memcpy(&(dict->dict[key]), &(olddict[i]), sizeof(xmlDictEntry));
+	    dict->dict[key].next = NULL;
+	    dict->dict[key].okey = okey;
+	} else {
+	    xmlDictEntryPtr entry;
+
+	    entry = xmlMalloc(sizeof(xmlDictEntry));
+	    if (entry != NULL) {
+		entry->name = olddict[i].name;
+		entry->len = olddict[i].len;
+		entry->okey = okey;
+		entry->next = dict->dict[key].next;
+		entry->valid = 1;
+		dict->dict[key].next = entry;
+	    } else {
+	        /*
+		 * we don't have much ways to alert from herei
+		 * result is loosing an entry and unicity garantee
+		 */
+	        ret = -1;
+	    }
+	}
 #ifdef DEBUG_GROW
 	nbElem++;
 #endif
@@ -456,15 +613,21 @@
 	     * put back the entry in the new dict
 	     */
 
-	    key = xmlDictComputeKey(iter->name, iter->len) % dict->size;
+	    if (keep_keys)
+		okey = iter->okey;
+	    else
+		okey = xmlDictComputeKey(dict, iter->name, iter->len);
+	    key = okey % dict->size;
 	    if (dict->dict[key].valid == 0) {
 		memcpy(&(dict->dict[key]), iter, sizeof(xmlDictEntry));
 		dict->dict[key].next = NULL;
 		dict->dict[key].valid = 1;
+		dict->dict[key].okey = okey;
 		xmlFree(iter);
 	    } else {
-	    	iter->next = dict->dict[key].next;
-	    	dict->dict[key].next = iter;
+		iter->next = dict->dict[key].next;
+		iter->okey = okey;
+		dict->dict[key].next = iter;
 	    }
 
 #ifdef DEBUG_GROW
@@ -482,7 +645,7 @@
 	    "xmlDictGrow : from %d to %d, %d elems\n", oldsize, size, nbElem);
 #endif
 
-    return(0);
+    return(ret);
 }
 
 /**
@@ -545,7 +708,6 @@
 	xmlFree(pool);
 	pool = nextp;
     }
-    xmlFreeRMutex(dict->mutex);
     xmlFree(dict);
 }
 
@@ -570,12 +732,12 @@
 	return(NULL);
 
     if (len < 0)
-        len = xmlStrlen(name);
+        len = strlen((const char *) name);
 
     /*
      * Check for duplicate and insertion location.
      */
-    okey = xmlDictComputeKey(name, len);
+    okey = xmlDictComputeKey(dict, name, len);
     key = okey % dict->size;
     if (dict->dict[key].valid == 0) {
 	insert = NULL;
@@ -583,55 +745,66 @@
 	for (insert = &(dict->dict[key]); insert->next != NULL;
 	     insert = insert->next) {
 #ifdef __GNUC__
-	    if (insert->len == len) {
+	    if ((insert->okey == okey) && (insert->len == len)) {
 		if (!memcmp(insert->name, name, len))
 		    return(insert->name);
 	    }
 #else
-	    if ((insert->len == len) &&
+	    if ((insert->okey == okey) && (insert->len == len) &&
 	        (!xmlStrncmp(insert->name, name, len)))
 		return(insert->name);
 #endif
 	    nbi++;
 	}
 #ifdef __GNUC__
-	if (insert->len == len) {
+	if ((insert->okey == okey) && (insert->len == len)) {
 	    if (!memcmp(insert->name, name, len))
 		return(insert->name);
 	}
 #else
-	if ((insert->len == len) &&
+	if ((insert->okey == okey) && (insert->len == len) &&
 	    (!xmlStrncmp(insert->name, name, len)))
 	    return(insert->name);
 #endif
     }
 
     if (dict->subdict) {
-	key = okey % dict->subdict->size;
+        unsigned long skey;
+
+        /* we cannot always reuse the same okey for the subdict */
+        if (((dict->size == MIN_DICT_SIZE) &&
+	     (dict->subdict->size != MIN_DICT_SIZE)) ||
+            ((dict->size != MIN_DICT_SIZE) &&
+	     (dict->subdict->size == MIN_DICT_SIZE)))
+	    skey = xmlDictComputeKey(dict->subdict, name, len);
+	else
+	    skey = okey;
+
+	key = skey % dict->subdict->size;
 	if (dict->subdict->dict[key].valid != 0) {
 	    xmlDictEntryPtr tmp;
 
 	    for (tmp = &(dict->subdict->dict[key]); tmp->next != NULL;
 		 tmp = tmp->next) {
 #ifdef __GNUC__
-		if (tmp->len == len) {
+		if ((tmp->okey == skey) && (tmp->len == len)) {
 		    if (!memcmp(tmp->name, name, len))
 			return(tmp->name);
 		}
 #else
-		if ((tmp->len == len) &&
+		if ((tmp->okey == skey) && (tmp->len == len) &&
 		    (!xmlStrncmp(tmp->name, name, len)))
 		    return(tmp->name);
 #endif
 		nbi++;
 	    }
 #ifdef __GNUC__
-	    if (tmp->len == len) {
+	    if ((tmp->okey == skey) && (tmp->len == len)) {
 		if (!memcmp(tmp->name, name, len))
 		    return(tmp->name);
 	    }
 #else
-	    if ((tmp->len == len) &&
+	    if ((tmp->okey == skey) && (tmp->len == len) &&
 		(!xmlStrncmp(tmp->name, name, len)))
 		return(tmp->name);
 #endif
@@ -653,6 +826,7 @@
     entry->len = len;
     entry->next = NULL;
     entry->valid = 1;
+    entry->okey = okey;
 
 
     if (insert != NULL) 
@@ -661,8 +835,10 @@
     dict->nbElems++;
 
     if ((nbi > MAX_HASH_LEN) &&
-        (dict->size <= ((MAX_DICT_HASH / 2) / MAX_HASH_LEN)))
-	xmlDictGrow(dict, MAX_HASH_LEN * 2 * dict->size);
+        (dict->size <= ((MAX_DICT_HASH / 2) / MAX_HASH_LEN))) {
+	if (xmlDictGrow(dict, MAX_HASH_LEN * 2 * dict->size) != 0)
+	    return(NULL);
+    }
     /* Note that entry may have been freed at this point by xmlDictGrow */
 
     return(ret);
@@ -687,12 +863,12 @@
 	return(NULL);
 
     if (len < 0)
-        len = xmlStrlen(name);
+        len = strlen((const char *) name);
 
     /*
      * Check for duplicate and insertion location.
      */
-    okey = xmlDictComputeKey(name, len);
+    okey = xmlDictComputeKey(dict, name, len);
     key = okey % dict->size;
     if (dict->dict[key].valid == 0) {
 	insert = NULL;
@@ -700,60 +876,70 @@
 	for (insert = &(dict->dict[key]); insert->next != NULL;
 	     insert = insert->next) {
 #ifdef __GNUC__
-	    if (insert->len == len) {
+	    if ((insert->okey == okey) && (insert->len == len)) {
 		if (!memcmp(insert->name, name, len))
 		    return(insert->name);
 	    }
 #else
-	    if ((insert->len == len) &&
+	    if ((insert->okey == okey) && (insert->len == len) &&
 	        (!xmlStrncmp(insert->name, name, len)))
 		return(insert->name);
 #endif
 	    nbi++;
 	}
 #ifdef __GNUC__
-	if (insert->len == len) {
+	if ((insert->okey == okey) && (insert->len == len)) {
 	    if (!memcmp(insert->name, name, len))
 		return(insert->name);
 	}
 #else
-	if ((insert->len == len) &&
+	if ((insert->okey == okey) && (insert->len == len) &&
 	    (!xmlStrncmp(insert->name, name, len)))
 	    return(insert->name);
 #endif
     }
 
     if (dict->subdict) {
-	key = okey % dict->subdict->size;
+        unsigned long skey;
+
+        /* we cannot always reuse the same okey for the subdict */
+        if (((dict->size == MIN_DICT_SIZE) &&
+	     (dict->subdict->size != MIN_DICT_SIZE)) ||
+            ((dict->size != MIN_DICT_SIZE) &&
+	     (dict->subdict->size == MIN_DICT_SIZE)))
+	    skey = xmlDictComputeKey(dict->subdict, name, len);
+	else
+	    skey = okey;
+
+	key = skey % dict->subdict->size;
 	if (dict->subdict->dict[key].valid != 0) {
 	    xmlDictEntryPtr tmp;
 
 	    for (tmp = &(dict->subdict->dict[key]); tmp->next != NULL;
 		 tmp = tmp->next) {
 #ifdef __GNUC__
-		if (tmp->len == len) {
+		if ((tmp->okey == skey) && (tmp->len == len)) {
 		    if (!memcmp(tmp->name, name, len))
 			return(tmp->name);
 		}
 #else
-		if ((tmp->len == len) &&
+		if ((tmp->okey == skey) && (tmp->len == len) &&
 		    (!xmlStrncmp(tmp->name, name, len)))
 		    return(tmp->name);
 #endif
 		nbi++;
 	    }
 #ifdef __GNUC__
-	    if (tmp->len == len) {
+	    if ((tmp->okey == skey) && (tmp->len == len)) {
 		if (!memcmp(tmp->name, name, len))
 		    return(tmp->name);
 	    }
 #else
-	    if ((tmp->len == len) &&
+	    if ((tmp->okey == skey) && (tmp->len == len) &&
 		(!xmlStrncmp(tmp->name, name, len)))
 		return(tmp->name);
 #endif
 	}
-	key = okey % dict->size;
     }
 
     /* not found */
@@ -763,7 +949,7 @@
 /**
  * xmlDictQLookup:
  * @dict: the dictionnary
- * @prefix: the prefix 
+ * @prefix: the prefix
  * @name: the name
  *
  * Add the QName @prefix:@name to the hash @dict if not present.
@@ -776,54 +962,67 @@
     xmlDictEntryPtr entry;
     xmlDictEntryPtr insert;
     const xmlChar *ret;
-    int len;
+    int len, plen, l;
 
     if ((dict == NULL) || (name == NULL))
 	return(NULL);
+    if (prefix == NULL)
+        return(xmlDictLookup(dict, name, -1));
 
-    len = xmlStrlen(name);
-    if (prefix != NULL)
-        len += 1 + xmlStrlen(prefix);
+    l = len = strlen((const char *) name);
+    plen = strlen((const char *) prefix);
+    len += 1 + plen;
 
     /*
      * Check for duplicate and insertion location.
      */
-    okey = xmlDictComputeQKey(prefix, name, len);
+    okey = xmlDictComputeQKey(dict, prefix, plen, name, l);
     key = okey % dict->size;
     if (dict->dict[key].valid == 0) {
 	insert = NULL;
     } else {
 	for (insert = &(dict->dict[key]); insert->next != NULL;
 	     insert = insert->next) {
-	    if ((insert->len == len) &&
+	    if ((insert->okey == okey) && (insert->len == len) &&
 	        (xmlStrQEqual(prefix, name, insert->name)))
 		return(insert->name);
 	    nbi++;
 	}
-	if ((insert->len == len) &&
+	if ((insert->okey == okey) && (insert->len == len) &&
 	    (xmlStrQEqual(prefix, name, insert->name)))
 	    return(insert->name);
     }
 
     if (dict->subdict) {
-	key = okey % dict->subdict->size;
+        unsigned long skey;
+
+        /* we cannot always reuse the same okey for the subdict */
+        if (((dict->size == MIN_DICT_SIZE) &&
+	     (dict->subdict->size != MIN_DICT_SIZE)) ||
+            ((dict->size != MIN_DICT_SIZE) &&
+	     (dict->subdict->size == MIN_DICT_SIZE)))
+	    skey = xmlDictComputeQKey(dict->subdict, prefix, plen, name, l);
+	else
+	    skey = okey;
+
+	key = skey % dict->subdict->size;
 	if (dict->subdict->dict[key].valid != 0) {
 	    xmlDictEntryPtr tmp;
 	    for (tmp = &(dict->subdict->dict[key]); tmp->next != NULL;
 		 tmp = tmp->next) {
-		if ((tmp->len == len) &&
+		if ((tmp->okey == skey) && (tmp->len == len) &&
 		    (xmlStrQEqual(prefix, name, tmp->name)))
 		    return(tmp->name);
 		nbi++;
 	    }
-	    if ((tmp->len == len) &&
+	    if ((tmp->okey == skey) && (tmp->len == len) &&
 		(xmlStrQEqual(prefix, name, tmp->name)))
 		return(tmp->name);
 	}
 	key = okey % dict->size;
     }
 
-    ret = xmlDictAddQString(dict, prefix, name, len);
+    ret = xmlDictAddQString(dict, prefix, plen, name, l);
     if (ret == NULL)
         return(NULL);
     if (insert == NULL) {
@@ -837,6 +1036,7 @@
     entry->len = len;
     entry->next = NULL;
     entry->valid = 1;
+    entry->okey = okey;
 
     if (insert != NULL) 
 	insert->next = entry;
diff --git a/elfgcchack.h b/elfgcchack.h
index cd9605c..14cad6d 100644
--- a/elfgcchack.h
+++ b/elfgcchack.h
@@ -1991,6 +1991,18 @@
 #endif
 #endif
 
+#if defined(LIBXML_TREE_ENABLED)
+#ifdef bottom_tree
+#undef xmlChildElementCount
+extern __typeof (xmlChildElementCount) xmlChildElementCount __attribute((alias("xmlChildElementCount__internal_alias")));
+#else
+#ifndef xmlChildElementCount
+extern __typeof (xmlChildElementCount) xmlChildElementCount__internal_alias __attribute((visibility("hidden")));
+#define xmlChildElementCount xmlChildElementCount__internal_alias
+#endif
+#endif
+#endif
+
 #ifdef bottom_encoding
 #undef xmlCleanupCharEncodingHandlers
 extern __typeof (xmlCleanupCharEncodingHandlers) xmlCleanupCharEncodingHandlers __attribute((alias("xmlCleanupCharEncodingHandlers__internal_alias")));
@@ -3419,6 +3431,18 @@
 #endif
 #endif
 
+#if defined(LIBXML_TREE_ENABLED)
+#ifdef bottom_tree
+#undef xmlFirstElementChild
+extern __typeof (xmlFirstElementChild) xmlFirstElementChild __attribute((alias("xmlFirstElementChild__internal_alias")));
+#else
+#ifndef xmlFirstElementChild
+extern __typeof (xmlFirstElementChild) xmlFirstElementChild__internal_alias __attribute((visibility("hidden")));
+#define xmlFirstElementChild xmlFirstElementChild__internal_alias
+#endif
+#endif
+#endif
+
 #ifdef bottom_valid
 #undef xmlFreeAttributeTable
 extern __typeof (xmlFreeAttributeTable) xmlFreeAttributeTable __attribute((alias("xmlFreeAttributeTable__internal_alias")));
@@ -4759,6 +4783,18 @@
 #endif
 #endif
 
+#if defined(LIBXML_TREE_ENABLED)
+#ifdef bottom_tree
+#undef xmlLastElementChild
+extern __typeof (xmlLastElementChild) xmlLastElementChild __attribute((alias("xmlLastElementChild__internal_alias")));
+#else
+#ifndef xmlLastElementChild
+extern __typeof (xmlLastElementChild) xmlLastElementChild__internal_alias __attribute((visibility("hidden")));
+#define xmlLastElementChild xmlLastElementChild__internal_alias
+#endif
+#endif
+#endif
+
 #ifdef bottom_parserInternals
 #undef xmlLineNumbersDefault
 extern __typeof (xmlLineNumbersDefault) xmlLineNumbersDefault __attribute((alias("xmlLineNumbersDefault__internal_alias")));
@@ -5162,6 +5198,16 @@
 #endif
 
 #ifdef bottom_xmlmemory
+#undef xmlMemDisplayLast
+extern __typeof (xmlMemDisplayLast) xmlMemDisplayLast __attribute((alias("xmlMemDisplayLast__internal_alias")));
+#else
+#ifndef xmlMemDisplayLast
+extern __typeof (xmlMemDisplayLast) xmlMemDisplayLast__internal_alias __attribute((visibility("hidden")));
+#define xmlMemDisplayLast xmlMemDisplayLast__internal_alias
+#endif
+#endif
+
+#ifdef bottom_xmlmemory
 #undef xmlMemFree
 extern __typeof (xmlMemFree) xmlMemFree __attribute((alias("xmlMemFree__internal_alias")));
 #else
@@ -6043,6 +6089,16 @@
 #endif
 #endif
 
+#ifdef bottom_entities
+#undef xmlNewEntity
+extern __typeof (xmlNewEntity) xmlNewEntity __attribute((alias("xmlNewEntity__internal_alias")));
+#else
+#ifndef xmlNewEntity
+extern __typeof (xmlNewEntity) xmlNewEntity__internal_alias __attribute((visibility("hidden")));
+#define xmlNewEntity xmlNewEntity__internal_alias
+#endif
+#endif
+
 #ifdef bottom_parserInternals
 #undef xmlNewEntityInputStream
 extern __typeof (xmlNewEntityInputStream) xmlNewEntityInputStream __attribute((alias("xmlNewEntityInputStream__internal_alias")));
@@ -6367,6 +6423,18 @@
 #endif
 #endif
 
+#if defined(LIBXML_TREE_ENABLED)
+#ifdef bottom_tree
+#undef xmlNextElementSibling
+extern __typeof (xmlNextElementSibling) xmlNextElementSibling __attribute((alias("xmlNextElementSibling__internal_alias")));
+#else
+#ifndef xmlNextElementSibling
+extern __typeof (xmlNextElementSibling) xmlNextElementSibling__internal_alias __attribute((visibility("hidden")));
+#define xmlNextElementSibling xmlNextElementSibling__internal_alias
+#endif
+#endif
+#endif
+
 #ifdef bottom_xmlIO
 #undef xmlNoNetExternalEntityLoader
 extern __typeof (xmlNoNetExternalEntityLoader) xmlNoNetExternalEntityLoader __attribute((alias("xmlNoNetExternalEntityLoader__internal_alias")));
@@ -7769,6 +7837,18 @@
 #endif
 #endif
 
+#if defined(LIBXML_TREE_ENABLED)
+#ifdef bottom_tree
+#undef xmlPreviousElementSibling
+extern __typeof (xmlPreviousElementSibling) xmlPreviousElementSibling __attribute((alias("xmlPreviousElementSibling__internal_alias")));
+#else
+#ifndef xmlPreviousElementSibling
+extern __typeof (xmlPreviousElementSibling) xmlPreviousElementSibling__internal_alias __attribute((visibility("hidden")));
+#define xmlPreviousElementSibling xmlPreviousElementSibling__internal_alias
+#endif
+#endif
+#endif
+
 #ifdef bottom_uri
 #undef xmlPrintURI
 extern __typeof (xmlPrintURI) xmlPrintURI __attribute((alias("xmlPrintURI__internal_alias")));
@@ -9843,6 +9923,18 @@
 
 #if defined(LIBXML_SCHEMAS_ENABLED)
 #ifdef bottom_xmlschemas
+#undef xmlSchemaValidCtxtGetParserCtxt
+extern __typeof (xmlSchemaValidCtxtGetParserCtxt) xmlSchemaValidCtxtGetParserCtxt __attribute((alias("xmlSchemaValidCtxtGetParserCtxt__internal_alias")));
+#else
+#ifndef xmlSchemaValidCtxtGetParserCtxt
+extern __typeof (xmlSchemaValidCtxtGetParserCtxt) xmlSchemaValidCtxtGetParserCtxt__internal_alias __attribute((visibility("hidden")));
+#define xmlSchemaValidCtxtGetParserCtxt xmlSchemaValidCtxtGetParserCtxt__internal_alias
+#endif
+#endif
+#endif
+
+#if defined(LIBXML_SCHEMAS_ENABLED)
+#ifdef bottom_xmlschemas
 #undef xmlSchemaValidateDoc
 extern __typeof (xmlSchemaValidateDoc) xmlSchemaValidateDoc __attribute((alias("xmlSchemaValidateDoc__internal_alias")));
 #else
@@ -10119,6 +10211,18 @@
 
 #if defined(LIBXML_SCHEMATRON_ENABLED)
 #ifdef bottom_schematron
+#undef xmlSchematronSetValidStructuredErrors
+extern __typeof (xmlSchematronSetValidStructuredErrors) xmlSchematronSetValidStructuredErrors __attribute((alias("xmlSchematronSetValidStructuredErrors__internal_alias")));
+#else
+#ifndef xmlSchematronSetValidStructuredErrors
+extern __typeof (xmlSchematronSetValidStructuredErrors) xmlSchematronSetValidStructuredErrors__internal_alias __attribute((visibility("hidden")));
+#define xmlSchematronSetValidStructuredErrors xmlSchematronSetValidStructuredErrors__internal_alias
+#endif
+#endif
+#endif
+
+#if defined(LIBXML_SCHEMATRON_ENABLED)
+#ifdef bottom_schematron
 #undef xmlSchematronValidateDoc
 extern __typeof (xmlSchematronValidateDoc) xmlSchematronValidateDoc __attribute((alias("xmlSchematronValidateDoc__internal_alias")));
 #else
diff --git a/encoding.c b/encoding.c
index 002eeba..e2df797 100644
--- a/encoding.c
+++ b/encoding.c
@@ -1703,7 +1703,7 @@
     }
     icv_inlen = *inlen;
     icv_outlen = *outlen;
-    ret = iconv(cd, (char **) &icv_in, &icv_inlen, &icv_out, &icv_outlen);
+    ret = iconv(cd, (ICONV_CONST char **) &icv_in, &icv_inlen, &icv_out, &icv_outlen);
     *inlen -= icv_inlen;
     *outlen -= icv_outlen;
     if ((icv_inlen != 0) || (ret == -1)) {
@@ -1768,9 +1768,10 @@
      * echo '<?xml version="1.0" encoding="UCS4"?>' | wc -c => 38
      * 45 chars should be sufficient to reach the end of the encoding
      * declaration without going too far inside the document content.
+     * on UTF-16 this means 90bytes, on UCS4 this means 180
      */
-    if (toconv > 45)
-	toconv  = 45;
+    if (toconv > 180)
+	toconv  = 180;
     if (toconv * 2 >= written) {
         xmlBufferGrow(out, toconv);
 	written = out->size - out->use - 1;
@@ -1991,16 +1992,18 @@
     toconv = in->use;
     if (toconv == 0)
 	return(0);
-    if (toconv * 2 >= written) {
-        xmlBufferGrow(out, toconv * 2);
+    if (toconv * 4 >= written) {
+        xmlBufferGrow(out, toconv * 4);
 	written = out->size - out->use - 1;
     }
     if (handler->output != NULL) {
 	ret = handler->output(&out->content[out->use], &written,
 	                      in->content, &toconv);
-	xmlBufferShrink(in, toconv);
-	out->use += written;
-	writtentot += written;
+	if (written > 0) {
+	    xmlBufferShrink(in, toconv);
+	    out->use += written;
+	    writtentot += written;
+	} 
 	out->content[out->use] = 0;
     }
 #ifdef LIBXML_ICONV_ENABLED
diff --git a/entities.c b/entities.c
index 91a3978..c171e97 100644
--- a/entities.c
+++ b/entities.c
@@ -139,45 +139,19 @@
 }
 
 /*
- * xmlAddEntity : register a new entity for an entities table.
+ * xmlCreateEntity:
+ *
+ * internal routine doing the entity node strutures allocations
  */
 static xmlEntityPtr
-xmlAddEntity(xmlDtdPtr dtd, const xmlChar *name, int type,
-	  const xmlChar *ExternalID, const xmlChar *SystemID,
-	  const xmlChar *content) {
-    xmlDictPtr dict = NULL;
-    xmlEntitiesTablePtr table = NULL;
+xmlCreateEntity(xmlDictPtr dict, const xmlChar *name, int type,
+	        const xmlChar *ExternalID, const xmlChar *SystemID,
+	        const xmlChar *content) {
     xmlEntityPtr ret;
 
-    if (name == NULL)
-	return(NULL);
-    if (dtd == NULL)
-	return(NULL);
-    if (dtd->doc != NULL)
-        dict = dtd->doc->dict;
-
-    switch (type) {
-        case XML_INTERNAL_GENERAL_ENTITY:
-        case XML_EXTERNAL_GENERAL_PARSED_ENTITY:
-        case XML_EXTERNAL_GENERAL_UNPARSED_ENTITY:
-	    if (dtd->entities == NULL)
-		dtd->entities = xmlHashCreateDict(0, dict);
-	    table = dtd->entities;
-	    break;
-        case XML_INTERNAL_PARAMETER_ENTITY:
-        case XML_EXTERNAL_PARAMETER_ENTITY:
-	    if (dtd->pentities == NULL)
-		dtd->pentities = xmlHashCreateDict(0, dict);
-	    table = dtd->pentities;
-	    break;
-        case XML_INTERNAL_PREDEFINED_ENTITY:
-	    return(NULL);
-    }
-    if (table == NULL)
-	return(NULL);
     ret = (xmlEntityPtr) xmlMalloc(sizeof(xmlEntity));
     if (ret == NULL) {
-        xmlEntitiesErrMemory("xmlAddEntity:: malloc failed");
+        xmlEntitiesErrMemory("xmlCreateEntity: malloc failed");
 	return(NULL);
     }
     memset(ret, 0, sizeof(xmlEntity));
@@ -216,6 +190,50 @@
 			the defining entity */
     ret->orig = NULL;
     ret->owner = 0;
+
+    return(ret);
+}
+
+/*
+ * xmlAddEntity : register a new entity for an entities table.
+ */
+static xmlEntityPtr
+xmlAddEntity(xmlDtdPtr dtd, const xmlChar *name, int type,
+	  const xmlChar *ExternalID, const xmlChar *SystemID,
+	  const xmlChar *content) {
+    xmlDictPtr dict = NULL;
+    xmlEntitiesTablePtr table = NULL;
+    xmlEntityPtr ret;
+
+    if (name == NULL)
+	return(NULL);
+    if (dtd == NULL)
+	return(NULL);
+    if (dtd->doc != NULL)
+        dict = dtd->doc->dict;
+
+    switch (type) {
+        case XML_INTERNAL_GENERAL_ENTITY:
+        case XML_EXTERNAL_GENERAL_PARSED_ENTITY:
+        case XML_EXTERNAL_GENERAL_UNPARSED_ENTITY:
+	    if (dtd->entities == NULL)
+		dtd->entities = xmlHashCreateDict(0, dict);
+	    table = dtd->entities;
+	    break;
+        case XML_INTERNAL_PARAMETER_ENTITY:
+        case XML_EXTERNAL_PARAMETER_ENTITY:
+	    if (dtd->pentities == NULL)
+		dtd->pentities = xmlHashCreateDict(0, dict);
+	    table = dtd->pentities;
+	    break;
+        case XML_INTERNAL_PREDEFINED_ENTITY:
+	    return(NULL);
+    }
+    if (table == NULL)
+	return(NULL);
+    ret = xmlCreateEntity(dict, name, type, ExternalID, SystemID, content);
+    if (ret == NULL)
+        return(NULL);
     ret->doc = dtd->doc;
 
     if (xmlHashAddEntry(table, name, ret)) {
@@ -363,6 +381,44 @@
 }
 
 /**
+ * xmlNewEntity:
+ * @doc:  the document
+ * @name:  the entity name
+ * @type:  the entity type XML_xxx_yyy_ENTITY
+ * @ExternalID:  the entity external ID if available
+ * @SystemID:  the entity system ID if available
+ * @content:  the entity content
+ *
+ * Create a new entity, this differs from xmlAddDocEntity() that if
+ * the document is NULL or has no internal subset defined, then an
+ * unlinked entity structure will be returned, it is then the responsability
+ * of the caller to link it to the document later or free it when not needed
+ * anymore.
+ *
+ * Returns a pointer to the entity or NULL in case of error
+ */
+xmlEntityPtr
+xmlNewEntity(xmlDocPtr doc, const xmlChar *name, int type,
+	     const xmlChar *ExternalID, const xmlChar *SystemID,
+	     const xmlChar *content) {
+    xmlEntityPtr ret;
+    xmlDictPtr dict;
+
+    if ((doc != NULL) && (doc->intSubset != NULL)) {
+	return(xmlAddDocEntity(doc, name, type, ExternalID, SystemID, content));
+    }
+    if (doc != NULL)
+        dict = doc->dict;
+    else
+        dict = NULL;
+    ret = xmlCreateEntity(dict, name, type, ExternalID, SystemID, content);
+    if (ret == NULL)
+        return(NULL);
+    ret->doc = doc;
+    return(ret);
+}
+
+/**
  * xmlGetEntityFromTable:
  * @table:  an entity table
  * @name:  the entity name
diff --git a/error.c b/error.c
index 722ffbb..5f03d94 100644
--- a/error.c
+++ b/error.c
@@ -31,7 +31,7 @@
 								\
     size = 150;							\
 								\
-    while (1) {							\
+    while (size < 64000) {					\
 	va_start(ap, msg);					\
   	chars = vsnprintf(str, size, msg, ap);			\
 	va_end(ap);						\
diff --git a/globals.c b/globals.c
index 636ff87..cbc6625 100644
--- a/globals.c
+++ b/globals.c
@@ -60,7 +60,7 @@
 	xmlFreeMutex(xmlThrDefMutex);
 	xmlThrDefMutex = NULL;
     }
-	__xmlGlobalInitMutexDestroy();
+    __xmlGlobalInitMutexDestroy();
 }
 
 /************************************************************************
diff --git a/include/libxml/c14n.h b/include/libxml/c14n.h
index 9f4c6c0..a8aa737 100644
--- a/include/libxml/c14n.h
+++ b/include/libxml/c14n.h
@@ -2,30 +2,30 @@
  * Summary: Provide Canonical XML and Exclusive XML Canonicalization
  * Description: the c14n modules provides a
  *
- * "Canonical XML" implementation 
+ * "Canonical XML" implementation
  * http://www.w3.org/TR/xml-c14n
- * 
+ *
  * and an
  *
  * "Exclusive XML Canonicalization" implementation
  * http://www.w3.org/TR/xml-exc-c14n
- 
+
  * Copy: See Copyright for the status of this software.
- * 
+ *
  * Author: Aleksey Sanin <aleksey@aleksey.com>
  */
 #ifndef __XML_C14N_H__
-#define __XML_C14N_H__    
+#define __XML_C14N_H__
 #ifdef LIBXML_C14N_ENABLED
 #ifdef LIBXML_OUTPUT_ENABLED
 
 #ifdef __cplusplus
 extern "C" {
-#endif /* __cplusplus */ 
+#endif /* __cplusplus */
 
 #include <libxml/xmlversion.h>
 #include <libxml/tree.h>
-#include <libxml/xpath.h> 
+#include <libxml/xpath.h>
 
 /*
  * XML Canonicazation
@@ -37,28 +37,28 @@
  * Canonical form of an XML document could be created if and only if
  *  a) default attributes (if any) are added to all nodes
  *  b) all character and parsed entity references are resolved
- * In order to achive this in libxml2 the document MUST be loaded with 
+ * In order to achive this in libxml2 the document MUST be loaded with
  * following global setings:
- *    
+ *
  *    xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS;
  *    xmlSubstituteEntitiesDefault(1);
  *
  * or corresponding parser context setting:
  *    xmlParserCtxtPtr ctxt;
- *    
- *    ... 
+ *
+ *    ...
  *    ctxt->loadsubset = XML_DETECT_IDS | XML_COMPLETE_ATTRS;
  *    ctxt->replaceEntities = 1;
  *    ...
  */
 
 
-XMLPUBFUN int XMLCALL 		
+XMLPUBFUN int XMLCALL
 		xmlC14NDocSaveTo	(xmlDocPtr doc,
 					 xmlNodeSetPtr nodes,
 					 int exclusive,
 					 xmlChar **inclusive_ns_prefixes,
-					 int with_comments, 
+					 int with_comments,
 					 xmlOutputBufferPtr buf);
 
 XMLPUBFUN int XMLCALL
@@ -66,7 +66,7 @@
 					 xmlNodeSetPtr nodes,
 					 int exclusive,
 					 xmlChar **inclusive_ns_prefixes,
-					 int with_comments, 
+					 int with_comments,
 					 xmlChar **doc_txt_ptr);
 
 XMLPUBFUN int XMLCALL
@@ -74,7 +74,7 @@
 					 xmlNodeSetPtr nodes,
 					 int exclusive,
 					 xmlChar **inclusive_ns_prefixes,
-					 int with_comments, 
+					 int with_comments,
 					 const char* filename,
 					 int compression);
 
@@ -82,17 +82,27 @@
 /**
  * This is the core C14N function
  */
-typedef int (*xmlC14NIsVisibleCallback)	(void* user_data, 
+/**
+ * xmlC14NIsVisibleCallback:
+ * @user_data: user data
+ * @node: the curent node
+ * @parent: the parent node
+ *
+ * Signature for a C14N callback on visible nodes
+ *
+ * Returns 1 if the node should be included
+ */
+typedef int (*xmlC14NIsVisibleCallback)	(void* user_data,
 					 xmlNodePtr node,
 					 xmlNodePtr parent);
 
 XMLPUBFUN int XMLCALL
 		xmlC14NExecute		(xmlDocPtr doc,
 					 xmlC14NIsVisibleCallback is_visible_callback,
-					 void* user_data,				 
+					 void* user_data,
 					 int exclusive,
 					 xmlChar **inclusive_ns_prefixes,
-					 int with_comments, 
+					 int with_comments,
 					 xmlOutputBufferPtr buf);
 
 #ifdef __cplusplus
diff --git a/include/libxml/entities.h b/include/libxml/entities.h
index fdd7222..cefb97f 100644
--- a/include/libxml/entities.h
+++ b/include/libxml/entities.h
@@ -57,6 +57,8 @@
     const xmlChar           *URI;	/* the full URI as computed */
     int                    owner;	/* does the entity own the childrens */
     int			 checked;	/* was the entity content checked */
+					/* this is also used to count entites
+					 * references done from that entity */
 };
 
 /*
@@ -72,9 +74,17 @@
  */
 
 #ifdef LIBXML_LEGACY_ENABLED
-XMLPUBFUN void XMLCALL		
+XMLPUBFUN void XMLCALL
 		xmlInitializePredefinedEntities	(void);
 #endif /* LIBXML_LEGACY_ENABLED */
+
+XMLPUBFUN xmlEntityPtr XMLCALL
+			xmlNewEntity		(xmlDocPtr doc,
+						 const xmlChar *name,
+						 int type,
+						 const xmlChar *ExternalID,
+						 const xmlChar *SystemID,
+						 const xmlChar *content);
 XMLPUBFUN xmlEntityPtr XMLCALL
 			xmlAddDocEntity		(xmlDocPtr doc,
 						 const xmlChar *name,
@@ -82,53 +92,53 @@
 						 const xmlChar *ExternalID,
 						 const xmlChar *SystemID,
 						 const xmlChar *content);
-XMLPUBFUN xmlEntityPtr XMLCALL		
+XMLPUBFUN xmlEntityPtr XMLCALL
 			xmlAddDtdEntity		(xmlDocPtr doc,
 						 const xmlChar *name,
 						 int type,
 						 const xmlChar *ExternalID,
 						 const xmlChar *SystemID,
 						 const xmlChar *content);
-XMLPUBFUN xmlEntityPtr XMLCALL		
+XMLPUBFUN xmlEntityPtr XMLCALL
 			xmlGetPredefinedEntity	(const xmlChar *name);
-XMLPUBFUN xmlEntityPtr XMLCALL		
+XMLPUBFUN xmlEntityPtr XMLCALL
 			xmlGetDocEntity		(xmlDocPtr doc,
 						 const xmlChar *name);
-XMLPUBFUN xmlEntityPtr XMLCALL		
+XMLPUBFUN xmlEntityPtr XMLCALL
 			xmlGetDtdEntity		(xmlDocPtr doc,
 						 const xmlChar *name);
-XMLPUBFUN xmlEntityPtr XMLCALL		
+XMLPUBFUN xmlEntityPtr XMLCALL
 			xmlGetParameterEntity	(xmlDocPtr doc,
 						 const xmlChar *name);
 #ifdef LIBXML_LEGACY_ENABLED
-XMLPUBFUN const xmlChar * XMLCALL		
+XMLPUBFUN const xmlChar * XMLCALL
 			xmlEncodeEntities	(xmlDocPtr doc,
 						 const xmlChar *input);
 #endif /* LIBXML_LEGACY_ENABLED */
-XMLPUBFUN xmlChar * XMLCALL		
+XMLPUBFUN xmlChar * XMLCALL
 			xmlEncodeEntitiesReentrant(xmlDocPtr doc,
 						 const xmlChar *input);
-XMLPUBFUN xmlChar * XMLCALL		
+XMLPUBFUN xmlChar * XMLCALL
 			xmlEncodeSpecialChars	(xmlDocPtr doc,
 						 const xmlChar *input);
-XMLPUBFUN xmlEntitiesTablePtr XMLCALL	
+XMLPUBFUN xmlEntitiesTablePtr XMLCALL
 			xmlCreateEntitiesTable	(void);
 #ifdef LIBXML_TREE_ENABLED
-XMLPUBFUN xmlEntitiesTablePtr XMLCALL	
+XMLPUBFUN xmlEntitiesTablePtr XMLCALL
 			xmlCopyEntitiesTable	(xmlEntitiesTablePtr table);
 #endif /* LIBXML_TREE_ENABLED */
-XMLPUBFUN void XMLCALL			
+XMLPUBFUN void XMLCALL
 			xmlFreeEntitiesTable	(xmlEntitiesTablePtr table);
 #ifdef LIBXML_OUTPUT_ENABLED
-XMLPUBFUN void XMLCALL			
+XMLPUBFUN void XMLCALL
 			xmlDumpEntitiesTable	(xmlBufferPtr buf,
 						 xmlEntitiesTablePtr table);
-XMLPUBFUN void XMLCALL			
+XMLPUBFUN void XMLCALL
 			xmlDumpEntityDecl	(xmlBufferPtr buf,
 						 xmlEntityPtr ent);
 #endif /* LIBXML_OUTPUT_ENABLED */
 #ifdef LIBXML_LEGACY_ENABLED
-XMLPUBFUN void XMLCALL			
+XMLPUBFUN void XMLCALL
 			xmlCleanupPredefinedEntities(void);
 #endif /* LIBXML_LEGACY_ENABLED */
 
diff --git a/include/libxml/globals.h b/include/libxml/globals.h
index 1173a8f..57e25fa 100644
--- a/include/libxml/globals.h
+++ b/include/libxml/globals.h
@@ -28,8 +28,32 @@
 XMLPUBFUN void XMLCALL xmlInitGlobals(void);
 XMLPUBFUN void XMLCALL xmlCleanupGlobals(void);
 
+/**
+ * xmlParserInputBufferCreateFilenameFunc:
+ * @URI: the URI to read from
+ * @enc: the requested source encoding
+ *
+ * Signature for the function doing the lookup for a suitable input method
+ * corresponding to an URI.
+ *
+ * Returns the new xmlParserInputBufferPtr in case of success or NULL if no
+ *         method was found.
+ */
 typedef xmlParserInputBufferPtr (*xmlParserInputBufferCreateFilenameFunc) (const char *URI, xmlCharEncoding enc);
+
+/**
+ * xmlOutputBufferCreateFilenameFunc:
+ * @URI: the URI to write to
+ * @enc: the requested target encoding
+ *
+ * Signature for the function doing the lookup for a suitable output method
+ * corresponding to an URI.
+ *
+ * Returns the new xmlOutputBufferPtr in case of success or NULL if no
+ *         method was found.
+ */
 typedef xmlOutputBufferPtr (*xmlOutputBufferCreateFilenameFunc) (const char *URI, xmlCharEncodingHandlerPtr encoder, int compression);
+
 XMLPUBFUN xmlParserInputBufferCreateFilenameFunc
 XMLCALL xmlParserInputBufferCreateFilenameDefault (xmlParserInputBufferCreateFilenameFunc func);
 XMLPUBFUN xmlOutputBufferCreateFilenameFunc
@@ -73,12 +97,24 @@
 #undef  xmlParserInputBufferCreateFilenameValue
 #undef  xmlOutputBufferCreateFilenameValue
 
+/**
+ * xmlRegisterNodeFunc:
+ * @node: the current node
+ *
+ * Signature for the registration callback of a created node
+ */
 typedef void (*xmlRegisterNodeFunc) (xmlNodePtr node);
+/**
+ * xmlDeregisterNodeFunc:
+ * @node: the current node
+ *
+ * Signature for the deregistration callback of a discarded node
+ */
 typedef void (*xmlDeregisterNodeFunc) (xmlNodePtr node);
 
 typedef struct _xmlGlobalState xmlGlobalState;
 typedef xmlGlobalState *xmlGlobalStatePtr;
-struct _xmlGlobalState 
+struct _xmlGlobalState
 {
 	const char *xmlParserVersion;
 
@@ -114,8 +150,8 @@
 	int xmlIndentTreeOutput;
 	const char *xmlTreeIndentString;
 
-  	xmlRegisterNodeFunc xmlRegisterNodeDefaultValue;
-  	xmlDeregisterNodeFunc xmlDeregisterNodeDefaultValue;
+	xmlRegisterNodeFunc xmlRegisterNodeDefaultValue;
+	xmlDeregisterNodeFunc xmlDeregisterNodeDefaultValue;
 
 	xmlMallocFunc xmlMallocAtomic;
 	xmlError xmlLastError;
@@ -143,9 +179,9 @@
 XMLPUBFUN xmlDeregisterNodeFunc XMLCALL xmlDeregisterNodeDefault(xmlDeregisterNodeFunc func);
 XMLPUBFUN xmlDeregisterNodeFunc XMLCALL xmlThrDefDeregisterNodeDefault(xmlDeregisterNodeFunc func);
 
-XMLPUBFUN xmlOutputBufferCreateFilenameFunc XMLCALL 
+XMLPUBFUN xmlOutputBufferCreateFilenameFunc XMLCALL
 	xmlThrDefOutputBufferCreateFilenameDefault(xmlOutputBufferCreateFilenameFunc func);
-XMLPUBFUN xmlParserInputBufferCreateFilenameFunc XMLCALL 
+XMLPUBFUN xmlParserInputBufferCreateFilenameFunc XMLCALL
 	xmlThrDefParserInputBufferCreateFilenameDefault(xmlParserInputBufferCreateFilenameFunc func);
 
 /** DOC_DISABLE */
diff --git a/include/libxml/parser.h b/include/libxml/parser.h
index fe63bda..567addb 100644
--- a/include/libxml/parser.h
+++ b/include/libxml/parser.h
@@ -297,6 +297,8 @@
      */
     xmlError          lastError;
     xmlParserMode     parseMode;    /* the parser mode */
+    unsigned long    nbentities;    /* number of entities references */
+    unsigned long  sizeentities;    /* size of parsed entities */
 };
 
 /**
@@ -592,7 +594,7 @@
  * Display and format a warning messages, callback.
  */
 typedef void (XMLCDECL *warningSAXFunc) (void *ctx,
-				const char *msg, ...);
+				const char *msg, ...) ATTRIBUTE_PRINTF(2,3);
 /**
  * errorSAXFunc:
  * @ctx:  an XML parser context
@@ -602,7 +604,7 @@
  * Display and format an error messages, callback.
  */
 typedef void (XMLCDECL *errorSAXFunc) (void *ctx,
-				const char *msg, ...);
+				const char *msg, ...) ATTRIBUTE_PRINTF(2,3);
 /**
  * fatalErrorSAXFunc:
  * @ctx:  an XML parser context
@@ -614,7 +616,7 @@
  *       get all the callbacks for errors.
  */
 typedef void (XMLCDECL *fatalErrorSAXFunc) (void *ctx,
-				const char *msg, ...);
+				const char *msg, ...) ATTRIBUTE_PRINTF(2,3);
 /**
  * isStandaloneSAXFunc:
  * @ctx:  the user data (XML parser context)
@@ -1089,9 +1091,13 @@
     XML_PARSE_NSCLEAN	= 1<<13,/* remove redundant namespaces declarations */
     XML_PARSE_NOCDATA	= 1<<14,/* merge CDATA as text nodes */
     XML_PARSE_NOXINCNODE= 1<<15,/* do not generate XINCLUDE START/END nodes */
-    XML_PARSE_COMPACT   = 1<<16 /* compact small text nodes; no modification of
+    XML_PARSE_COMPACT   = 1<<16,/* compact small text nodes; no modification of
                                    the tree allowed afterwards (will possibly
 				   crash if you try to modify the tree) */
+    XML_PARSE_OLD10	= 1<<17,/* parse using XML-1.0 before update 5 */
+    XML_PARSE_NOBASEFIX = 1<<18,/* do not fixup XINCLUDE xml:base uris */
+    XML_PARSE_HUGE      = 1<<19, /* relax any hardcoded limit from the parser */
+    XML_PARSE_OLDSAX    = 1<<20 /* parse using SAX2 interface from before 2.7.0 */
 } xmlParserOption;
 
 XMLPUBFUN void XMLCALL
diff --git a/include/libxml/parserInternals.h b/include/libxml/parserInternals.h
index 7ac0ce6..a5e75b5 100644
--- a/include/libxml/parserInternals.h
+++ b/include/libxml/parserInternals.h
@@ -24,18 +24,27 @@
 /**
  * xmlParserMaxDepth:
  *
- * arbitrary depth limit for the XML documents that we allow to 
- * process. This is not a limitation of the parser but a safety 
- * boundary feature.
+ * arbitrary depth limit for the XML documents that we allow to
+ * process. This is not a limitation of the parser but a safety
+ * boundary feature, use XML_PARSE_HUGE option to override it.
  */
 XMLPUBVAR unsigned int xmlParserMaxDepth;
 
- /**
-  * XML_MAX_NAMELEN:
-  *
-  * Identifiers can be longer, but this will be more costly
-  * at runtime.
-  */
+/**
+ * XML_MAX_TEXT_LENGTH:
+ *
+ * Maximum size allowed for a single text node when building a tree.
+ * This is not a limitation of the parser but a safety boundary feature,
+ * use XML_PARSE_HUGE option to override it.
+ */
+#define XML_MAX_TEXT_LENGTH 10000000
+
+/**
+ * XML_MAX_NAMELEN:
+ *
+ * Identifiers can be longer, but this will be more costly
+ * at runtime.
+ */
 #define XML_MAX_NAMELEN 100
 
 /**
@@ -321,7 +330,7 @@
 XMLPUBFUN xmlParserInputPtr XMLCALL	
 			xmlNewEntityInputStream	(xmlParserCtxtPtr ctxt,
 						 xmlEntityPtr entity);
-XMLPUBFUN void XMLCALL			
+XMLPUBFUN int XMLCALL			
 			xmlPushInput		(xmlParserCtxtPtr ctxt,
 						 xmlParserInputPtr input);
 XMLPUBFUN xmlChar XMLCALL			
diff --git a/include/libxml/relaxng.h b/include/libxml/relaxng.h
index 6acd467..d3e39e0 100644
--- a/include/libxml/relaxng.h
+++ b/include/libxml/relaxng.h
@@ -25,11 +25,28 @@
 
 
 /**
+ * xmlRelaxNGValidityErrorFunc:
+ * @ctx: the validation context
+ * @msg: the message
+ * @...: extra arguments
+ *
+ * Signature of an error callback from a Relax-NG validation
+ */
+typedef void (XMLCDECL *xmlRelaxNGValidityErrorFunc) (void *ctx, const char *msg, ...) ATTRIBUTE_PRINTF(2,3);
+
+/**
+ * xmlRelaxNGValidityWarningFunc:
+ * @ctx: the validation context
+ * @msg: the message
+ * @...: extra arguments
+ *
+ * Signature of a warning callback from a Relax-NG validation
+ */
+typedef void (XMLCDECL *xmlRelaxNGValidityWarningFunc) (void *ctx, const char *msg, ...) ATTRIBUTE_PRINTF(2,3);
+
+/**
  * A schemas validation context
  */
-typedef void (XMLCDECL *xmlRelaxNGValidityErrorFunc) (void *ctx, const char *msg, ...);
-typedef void (XMLCDECL *xmlRelaxNGValidityWarningFunc) (void *ctx, const char *msg, ...);
-
 typedef struct _xmlRelaxNGParserCtxt xmlRelaxNGParserCtxt;
 typedef xmlRelaxNGParserCtxt *xmlRelaxNGParserCtxtPtr;
 
@@ -97,27 +114,27 @@
 
 XMLPUBFUN int XMLCALL
 		    xmlRelaxNGInitTypes		(void);
-XMLPUBFUN void XMLCALL			
+XMLPUBFUN void XMLCALL
 		    xmlRelaxNGCleanupTypes	(void);
 
 /*
  * Interfaces for parsing.
  */
-XMLPUBFUN xmlRelaxNGParserCtxtPtr XMLCALL 
+XMLPUBFUN xmlRelaxNGParserCtxtPtr XMLCALL
 		    xmlRelaxNGNewParserCtxt	(const char *URL);
-XMLPUBFUN xmlRelaxNGParserCtxtPtr XMLCALL 
+XMLPUBFUN xmlRelaxNGParserCtxtPtr XMLCALL
 		    xmlRelaxNGNewMemParserCtxt	(const char *buffer,
 						 int size);
-XMLPUBFUN xmlRelaxNGParserCtxtPtr XMLCALL   
+XMLPUBFUN xmlRelaxNGParserCtxtPtr XMLCALL
 		    xmlRelaxNGNewDocParserCtxt	(xmlDocPtr doc);
 
 XMLPUBFUN int XMLCALL
 		    xmlRelaxParserSetFlag	(xmlRelaxNGParserCtxtPtr ctxt,
-		    				 int flag);
+						 int flag);
 
-XMLPUBFUN void XMLCALL		
+XMLPUBFUN void XMLCALL
 		    xmlRelaxNGFreeParserCtxt	(xmlRelaxNGParserCtxtPtr ctxt);
-XMLPUBFUN void XMLCALL			
+XMLPUBFUN void XMLCALL
 		    xmlRelaxNGSetParserErrors(xmlRelaxNGParserCtxtPtr ctxt,
 					 xmlRelaxNGValidityErrorFunc err,
 					 xmlRelaxNGValidityWarningFunc warn,
@@ -132,12 +149,12 @@
 					 xmlRelaxNGParserCtxtPtr ctxt,
 					 xmlStructuredErrorFunc serror,
 					 void *ctx);
-XMLPUBFUN xmlRelaxNGPtr XMLCALL	
+XMLPUBFUN xmlRelaxNGPtr XMLCALL
 		    xmlRelaxNGParse		(xmlRelaxNGParserCtxtPtr ctxt);
-XMLPUBFUN void XMLCALL		
+XMLPUBFUN void XMLCALL
 		    xmlRelaxNGFree		(xmlRelaxNGPtr schema);
 #ifdef LIBXML_OUTPUT_ENABLED
-XMLPUBFUN void XMLCALL		
+XMLPUBFUN void XMLCALL
 		    xmlRelaxNGDump		(FILE *output,
 					 xmlRelaxNGPtr schema);
 XMLPUBFUN void XMLCALL
@@ -147,12 +164,12 @@
 /*
  * Interfaces for validating
  */
-XMLPUBFUN void XMLCALL		
+XMLPUBFUN void XMLCALL
 		    xmlRelaxNGSetValidErrors(xmlRelaxNGValidCtxtPtr ctxt,
 					 xmlRelaxNGValidityErrorFunc err,
 					 xmlRelaxNGValidityWarningFunc warn,
 					 void *ctx);
-XMLPUBFUN int XMLCALL	
+XMLPUBFUN int XMLCALL
 		    xmlRelaxNGGetValidErrors(xmlRelaxNGValidCtxtPtr ctxt,
 					 xmlRelaxNGValidityErrorFunc *err,
 					 xmlRelaxNGValidityWarningFunc *warn,
@@ -160,29 +177,29 @@
 XMLPUBFUN void XMLCALL
 			xmlRelaxNGSetValidStructuredErrors(xmlRelaxNGValidCtxtPtr ctxt,
 					  xmlStructuredErrorFunc serror, void *ctx);
-XMLPUBFUN xmlRelaxNGValidCtxtPtr XMLCALL	
+XMLPUBFUN xmlRelaxNGValidCtxtPtr XMLCALL
 		    xmlRelaxNGNewValidCtxt	(xmlRelaxNGPtr schema);
-XMLPUBFUN void XMLCALL			
+XMLPUBFUN void XMLCALL
 		    xmlRelaxNGFreeValidCtxt	(xmlRelaxNGValidCtxtPtr ctxt);
-XMLPUBFUN int XMLCALL			
+XMLPUBFUN int XMLCALL
 		    xmlRelaxNGValidateDoc	(xmlRelaxNGValidCtxtPtr ctxt,
-					 	 xmlDocPtr doc);
+						 xmlDocPtr doc);
 /*
  * Interfaces for progressive validation when possible
  */
-XMLPUBFUN int XMLCALL	
+XMLPUBFUN int XMLCALL
 		    xmlRelaxNGValidatePushElement	(xmlRelaxNGValidCtxtPtr ctxt,
 					 xmlDocPtr doc,
 					 xmlNodePtr elem);
-XMLPUBFUN int XMLCALL	
+XMLPUBFUN int XMLCALL
 		    xmlRelaxNGValidatePushCData	(xmlRelaxNGValidCtxtPtr ctxt,
 					 const xmlChar *data,
 					 int len);
-XMLPUBFUN int XMLCALL	
+XMLPUBFUN int XMLCALL
 		    xmlRelaxNGValidatePopElement	(xmlRelaxNGValidCtxtPtr ctxt,
 					 xmlDocPtr doc,
 					 xmlNodePtr elem);
-XMLPUBFUN int XMLCALL	
+XMLPUBFUN int XMLCALL
 		    xmlRelaxNGValidateFullElement	(xmlRelaxNGValidCtxtPtr ctxt,
 					 xmlDocPtr doc,
 					 xmlNodePtr elem);
diff --git a/include/libxml/schematron.h b/include/libxml/schematron.h
index 6eaa699..f442826 100644
--- a/include/libxml/schematron.h
+++ b/include/libxml/schematron.h
@@ -25,6 +25,7 @@
     XML_SCHEMATRON_OUT_QUIET = 1 << 0,	/* quiet no report */
     XML_SCHEMATRON_OUT_TEXT = 1 << 1,	/* build a textual report */
     XML_SCHEMATRON_OUT_XML = 1 << 2,	/* output SVRL */
+    XML_SCHEMATRON_OUT_ERROR = 1 << 3,  /* output via xmlStructuredErrorFunc */
     XML_SCHEMATRON_OUT_FILE = 1 << 8,	/* output to a file descriptor */
     XML_SCHEMATRON_OUT_BUFFER = 1 << 9,	/* output to a buffer */
     XML_SCHEMATRON_OUT_IO = 1 << 10	/* output to I/O mechanism */
@@ -37,11 +38,28 @@
 typedef xmlSchematron *xmlSchematronPtr;
 
 /**
- * A schemas validation context
+ * xmlSchematronValidityErrorFunc:
+ * @ctx: the validation context
+ * @msg: the message
+ * @...: extra arguments
+ *
+ * Signature of an error callback from a Schematron validation
  */
 typedef void (*xmlSchematronValidityErrorFunc) (void *ctx, const char *msg, ...);
+
+/**
+ * xmlSchematronValidityWarningFunc:
+ * @ctx: the validation context
+ * @msg: the message
+ * @...: extra arguments
+ *
+ * Signature of a warning callback from a Schematron validation
+ */
 typedef void (*xmlSchematronValidityWarningFunc) (void *ctx, const char *msg, ...);
 
+/**
+ * A schemas validation context
+ */
 typedef struct _xmlSchematronParserCtxt xmlSchematronParserCtxt;
 typedef xmlSchematronParserCtxt *xmlSchematronParserCtxtPtr;
 
@@ -81,12 +99,12 @@
 /*
  * Interfaces for validating
  */
-/******
 XMLPUBFUN void XMLCALL
 	    xmlSchematronSetValidStructuredErrors(
 	                                  xmlSchematronValidCtxtPtr ctxt,
 					  xmlStructuredErrorFunc serror,
 					  void *ctx);
+/******
 XMLPUBFUN void XMLCALL		
 	    xmlSchematronSetValidErrors	(xmlSchematronValidCtxtPtr ctxt,
 					 xmlSchematronValidityErrorFunc err,
diff --git a/include/libxml/threads.h b/include/libxml/threads.h
index f81f982..d31f16a 100644
--- a/include/libxml/threads.h
+++ b/include/libxml/threads.h
@@ -36,40 +36,40 @@
 #ifdef __cplusplus
 extern "C" {
 #endif
-XMLPUBFUN xmlMutexPtr XMLCALL		
+XMLPUBFUN xmlMutexPtr XMLCALL
 			xmlNewMutex	(void);
-XMLPUBFUN void XMLCALL			
+XMLPUBFUN void XMLCALL
 			xmlMutexLock	(xmlMutexPtr tok);
-XMLPUBFUN void XMLCALL			
+XMLPUBFUN void XMLCALL
 			xmlMutexUnlock	(xmlMutexPtr tok);
-XMLPUBFUN void XMLCALL			
+XMLPUBFUN void XMLCALL
 			xmlFreeMutex	(xmlMutexPtr tok);
 
-XMLPUBFUN xmlRMutexPtr XMLCALL		
+XMLPUBFUN xmlRMutexPtr XMLCALL
 			xmlNewRMutex	(void);
-XMLPUBFUN void XMLCALL			
+XMLPUBFUN void XMLCALL
 			xmlRMutexLock	(xmlRMutexPtr tok);
-XMLPUBFUN void XMLCALL			
+XMLPUBFUN void XMLCALL
 			xmlRMutexUnlock	(xmlRMutexPtr tok);
-XMLPUBFUN void XMLCALL			
+XMLPUBFUN void XMLCALL
 			xmlFreeRMutex	(xmlRMutexPtr tok);
 
 /*
  * Library wide APIs.
  */
-XMLPUBFUN void XMLCALL			
+XMLPUBFUN void XMLCALL
 			xmlInitThreads	(void);
-XMLPUBFUN void XMLCALL			
+XMLPUBFUN void XMLCALL
 			xmlLockLibrary	(void);
-XMLPUBFUN void XMLCALL			
+XMLPUBFUN void XMLCALL
 			xmlUnlockLibrary(void);
-XMLPUBFUN int XMLCALL			
+XMLPUBFUN int XMLCALL
 			xmlGetThreadId	(void);
-XMLPUBFUN int XMLCALL			
+XMLPUBFUN int XMLCALL
 			xmlIsMainThread	(void);
-XMLPUBFUN void XMLCALL			
+XMLPUBFUN void XMLCALL
 			xmlCleanupThreads(void);
-XMLPUBFUN xmlGlobalStatePtr XMLCALL	
+XMLPUBFUN xmlGlobalStatePtr XMLCALL
 			xmlGetGlobalState(void);
 
 #if defined(HAVE_WIN32_THREADS) && !defined(HAVE_COMPILER_TLS) && defined(LIBXML_STATIC_FOR_DLL)
diff --git a/include/libxml/tree.h b/include/libxml/tree.h
index 0e1d47c..b733589 100644
--- a/include/libxml/tree.h
+++ b/include/libxml/tree.h
@@ -71,9 +71,10 @@
  */
 
 typedef enum {
-    XML_BUFFER_ALLOC_DOUBLEIT,
-    XML_BUFFER_ALLOC_EXACT,
-    XML_BUFFER_ALLOC_IMMUTABLE
+    XML_BUFFER_ALLOC_DOUBLEIT,	/* double each time one need to grow */
+    XML_BUFFER_ALLOC_EXACT,	/* grow only to the minimal size */
+    XML_BUFFER_ALLOC_IMMUTABLE, /* immutable buffer */
+    XML_BUFFER_ALLOC_IO		/* special allocation scheme used for I/O */
 } xmlBufferAllocationScheme;
 
 /**
@@ -88,6 +89,7 @@
     unsigned int use;		/* The buffer size used */
     unsigned int size;		/* The buffer size */
     xmlBufferAllocationScheme alloc; /* The realloc method */
+    xmlChar *contentIO;		/* in IO mode we may have a different base */
 };
 
 /**
@@ -482,6 +484,23 @@
 #define XML_GET_LINE(n)						\
     (xmlGetLineNo(n))
 
+/**
+ * xmlDocProperty
+ *
+ * Set of properties of the document as found by the parser
+ * Some of them are linked to similary named xmlParserOption
+ */
+typedef enum {
+    XML_DOC_WELLFORMED		= 1<<0, /* document is XML well formed */
+    XML_DOC_NSVALID		= 1<<1, /* document is Namespace valid */
+    XML_DOC_OLD10		= 1<<2, /* parsed with old XML-1.0 parser */
+    XML_DOC_DTDVALID		= 1<<3, /* DTD validation was successful */
+    XML_DOC_XINCLUDE		= 1<<4, /* XInclude substitution was done */
+    XML_DOC_USERBUILT		= 1<<5, /* Document was built using the API
+                                           and not by parsing an instance */
+    XML_DOC_INTERNAL		= 1<<6, /* built for internal processing */
+    XML_DOC_HTML		= 1<<7  /* parsed or built HTML document */
+} xmlDocProperties;
 
 /**
  * xmlDoc:
@@ -521,6 +540,10 @@
 				   actually an xmlCharEncoding */
     struct _xmlDict *dict;      /* dict used to allocate names or NULL */
     void           *psvi;	/* for type/PSVI informations */
+    int             parseFlags;	/* set of xmlParserOption used to parse the
+				   document */
+    int             properties;	/* set of xmlDocProperties for this document
+				   set at the end of parsing */
 };
 
 
@@ -1202,6 +1225,22 @@
 					 int deep,
 					 int options);
 
+#ifdef LIBXML_TREE_ENABLED
+/*
+ * 5 interfaces from DOM ElementTraversal, but different in entities
+ * traversal.
+ */
+XMLPUBFUN unsigned long XMLCALL
+            xmlChildElementCount        (xmlNodePtr parent);
+XMLPUBFUN xmlNodePtr XMLCALL
+            xmlNextElementSibling       (xmlNodePtr node);
+XMLPUBFUN xmlNodePtr XMLCALL
+            xmlFirstElementChild        (xmlNodePtr parent);
+XMLPUBFUN xmlNodePtr XMLCALL
+            xmlLastElementChild         (xmlNodePtr parent);
+XMLPUBFUN xmlNodePtr XMLCALL
+            xmlPreviousElementSibling   (xmlNodePtr node);
+#endif
 #ifdef __cplusplus
 }
 #endif
diff --git a/include/libxml/uri.h b/include/libxml/uri.h
index 49ed105..db48262 100644
--- a/include/libxml/uri.h
+++ b/include/libxml/uri.h
@@ -49,43 +49,43 @@
  * xmlChar *	xmlNodeGetBase	(xmlDocPtr doc,
  *                               xmlNodePtr cur);
  */
-XMLPUBFUN xmlURIPtr XMLCALL	
+XMLPUBFUN xmlURIPtr XMLCALL
 		xmlCreateURI		(void);
-XMLPUBFUN xmlChar * XMLCALL	
+XMLPUBFUN xmlChar * XMLCALL
 		xmlBuildURI		(const xmlChar *URI,
-	                         	 const xmlChar *base);
-XMLPUBFUN xmlChar * XMLCALL	
+					 const xmlChar *base);
+XMLPUBFUN xmlChar * XMLCALL
 		xmlBuildRelativeURI	(const xmlChar *URI,
-	                         	 const xmlChar *base);
-XMLPUBFUN xmlURIPtr XMLCALL	
+					 const xmlChar *base);
+XMLPUBFUN xmlURIPtr XMLCALL
 		xmlParseURI		(const char *str);
-XMLPUBFUN xmlURIPtr XMLCALL	
+XMLPUBFUN xmlURIPtr XMLCALL
 		xmlParseURIRaw		(const char *str,
 					 int raw);
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 		xmlParseURIReference	(xmlURIPtr uri,
 					 const char *str);
-XMLPUBFUN xmlChar * XMLCALL	
+XMLPUBFUN xmlChar * XMLCALL
 		xmlSaveUri		(xmlURIPtr uri);
-XMLPUBFUN void XMLCALL		
+XMLPUBFUN void XMLCALL
 		xmlPrintURI		(FILE *stream,
 					 xmlURIPtr uri);
-XMLPUBFUN xmlChar * XMLCALL       
+XMLPUBFUN xmlChar * XMLCALL
 		xmlURIEscapeStr         (const xmlChar *str,
- 					 const xmlChar *list);
-XMLPUBFUN char * XMLCALL		
+					 const xmlChar *list);
+XMLPUBFUN char * XMLCALL
 		xmlURIUnescapeString	(const char *str,
 					 int len,
 					 char *target);
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 		xmlNormalizeURIPath	(char *path);
-XMLPUBFUN xmlChar * XMLCALL	
+XMLPUBFUN xmlChar * XMLCALL
 		xmlURIEscape		(const xmlChar *str);
-XMLPUBFUN void XMLCALL		
+XMLPUBFUN void XMLCALL
 		xmlFreeURI		(xmlURIPtr uri);
-XMLPUBFUN xmlChar* XMLCALL	
+XMLPUBFUN xmlChar* XMLCALL
 		xmlCanonicPath		(const xmlChar *path);
-XMLPUBFUN xmlChar* XMLCALL	
+XMLPUBFUN xmlChar* XMLCALL
 		xmlPathToURI		(const xmlChar *path);
 
 #ifdef __cplusplus
diff --git a/include/libxml/valid.h b/include/libxml/valid.h
index 7492d28..f1892b0 100644
--- a/include/libxml/valid.h
+++ b/include/libxml/valid.h
@@ -41,7 +41,7 @@
  */
 typedef void (XMLCDECL *xmlValidityErrorFunc) (void *ctx,
 			     const char *msg,
-			     ...);
+			     ...) ATTRIBUTE_PRINTF(2,3);
 
 /**
  * xmlValidityWarningFunc:
@@ -56,7 +56,7 @@
  */
 typedef void (XMLCDECL *xmlValidityWarningFunc) (void *ctx,
 			       const char *msg,
-			       ...);
+			       ...) ATTRIBUTE_PRINTF(2,3);
 
 #ifdef IN_LIBXML
 /**
diff --git a/include/libxml/xmlerror.h b/include/libxml/xmlerror.h
index c5f2164..7cce9c3 100644
--- a/include/libxml/xmlerror.h
+++ b/include/libxml/xmlerror.h
@@ -61,7 +61,8 @@
     XML_FROM_CHECK,	/* The error checking module */
     XML_FROM_WRITER,	/* The xmlwriter module */
     XML_FROM_MODULE,	/* The dynamically loaded module module*/
-    XML_FROM_I18N 	/* The module handling character conversion */
+    XML_FROM_I18N,	/* The module handling character conversion */
+    XML_FROM_SCHEMATRONV	/* The Schematron validator module */
 } xmlErrorDomain;
 
 /**
@@ -202,11 +203,14 @@
     XML_ERR_NOTATION_PROCESSING, /* 105 */
     XML_WAR_NS_COLUMN, /* 106 */
     XML_WAR_ENTITY_REDEFINED, /* 107 */
+    XML_ERR_UNKNOWN_VERSION, /* 108 */
+    XML_ERR_VERSION_MISMATCH, /* 109 */
     XML_NS_ERR_XML_NAMESPACE = 200,
     XML_NS_ERR_UNDEFINED_NAMESPACE, /* 201 */
     XML_NS_ERR_QNAME, /* 202 */
     XML_NS_ERR_ATTRIBUTE_REDEFINED, /* 203 */
     XML_NS_ERR_EMPTY, /* 204 */
+    XML_NS_ERR_COLON, /* 205 */
     XML_DTD_ATTRIBUTE_DEFAULT = 500,
     XML_DTD_ATTRIBUTE_REDEFINED, /* 501 */
     XML_DTD_ATTRIBUTE_VALUE, /* 502 */
@@ -248,6 +252,7 @@
     XML_DTD_STANDALONE_DEFAULTED, /* 538 */
     XML_DTD_XMLID_VALUE, /* 539 */
     XML_DTD_XMLID_TYPE, /* 540 */
+    XML_DTD_DUP_TOKEN, /* 541 */
     XML_HTML_STRUCURE_ERROR = 800,
     XML_HTML_UNKNOWN_TAG, /* 801 */
     XML_RNGP_ANYNAME_ATTR_ANCESTOR = 1000,
@@ -398,6 +403,7 @@
     XML_TREE_INVALID_HEX = 1300,
     XML_TREE_INVALID_DEC, /* 1301 */
     XML_TREE_UNTERMINATED_ENTITY, /* 1302 */
+    XML_TREE_NOT_UTF8, /* 1303 */
     XML_SAVE_NOT_UTF8 = 1400,
     XML_SAVE_CHAR_INVALID, /* 1401 */
     XML_SAVE_NO_DOCTYPE, /* 1402 */
@@ -639,7 +645,7 @@
     XML_SCHEMAV_CVC_ELT_4_3, /* 1852 */
     XML_SCHEMAV_CVC_ELT_5_1_1, /* 1853 */
     XML_SCHEMAV_CVC_ELT_5_1_2, /* 1854 */
-    XML_SCHEMAV_CVC_ELT_5_2_1, /* 1855 */  
+    XML_SCHEMAV_CVC_ELT_5_2_1, /* 1855 */
     XML_SCHEMAV_CVC_ELT_5_2_2_1, /* 1856 */
     XML_SCHEMAV_CVC_ELT_5_2_2_2_1, /* 1857 */
     XML_SCHEMAV_CVC_ELT_5_2_2_2_2, /* 1858 */
@@ -664,7 +670,7 @@
     XML_SCHEMAV_CVC_IDC, /* 1877 */
     XML_SCHEMAV_CVC_WILDCARD, /* 1878 */
     XML_SCHEMAV_MISC, /* 1879 */
-    XML_XPTR_UNKNOWN_SCHEME = 1900, 
+    XML_XPTR_UNKNOWN_SCHEME = 1900,
     XML_XPTR_CHILDSEQ_START, /* 1901 */
     XML_XPTR_EVAL_FAILED, /* 1902 */
     XML_XPTR_EXTRA_OBJECTS, /* 1903 */
@@ -685,15 +691,15 @@
     XML_SCHEMAP_SRC_SIMPLE_TYPE_2, /* 3001 */
     XML_SCHEMAP_SRC_SIMPLE_TYPE_3, /* 3002 */
     XML_SCHEMAP_SRC_SIMPLE_TYPE_4, /* 3003 */
-    XML_SCHEMAP_SRC_RESOLVE, /* 3004 */ 
+    XML_SCHEMAP_SRC_RESOLVE, /* 3004 */
     XML_SCHEMAP_SRC_RESTRICTION_BASE_OR_SIMPLETYPE, /* 3005 */
     XML_SCHEMAP_SRC_LIST_ITEMTYPE_OR_SIMPLETYPE, /* 3006 */
     XML_SCHEMAP_SRC_UNION_MEMBERTYPES_OR_SIMPLETYPES, /* 3007 */
     XML_SCHEMAP_ST_PROPS_CORRECT_1, /* 3008 */
     XML_SCHEMAP_ST_PROPS_CORRECT_2, /* 3009 */
-    XML_SCHEMAP_ST_PROPS_CORRECT_3, /* 3010 */     
+    XML_SCHEMAP_ST_PROPS_CORRECT_3, /* 3010 */
     XML_SCHEMAP_COS_ST_RESTRICTS_1_1, /* 3011 */
-    XML_SCHEMAP_COS_ST_RESTRICTS_1_2, /* 3012 */    
+    XML_SCHEMAP_COS_ST_RESTRICTS_1_2, /* 3012 */
     XML_SCHEMAP_COS_ST_RESTRICTS_1_3_1, /* 3013 */
     XML_SCHEMAP_COS_ST_RESTRICTS_1_3_2, /* 3014 */
     XML_SCHEMAP_COS_ST_RESTRICTS_2_1, /* 3015 */
@@ -712,7 +718,7 @@
     XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_3, /* 3028 */
     XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_4, /* 3029 */
     XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_5, /* 3030 */
-    XML_SCHEMAP_COS_ST_DERIVED_OK_2_1, /* 3031 */ 
+    XML_SCHEMAP_COS_ST_DERIVED_OK_2_1, /* 3031 */
     XML_SCHEMAP_COS_ST_DERIVED_OK_2_2, /* 3032 */
     XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, /* 3033 */
     XML_SCHEMAP_S4S_ELEM_MISSING, /* 3034 */
@@ -731,14 +737,14 @@
     XML_SCHEMAP_E_PROPS_CORRECT_4, /* 3047 */
     XML_SCHEMAP_E_PROPS_CORRECT_5, /* 3048 */
     XML_SCHEMAP_E_PROPS_CORRECT_6, /* 3049 */
-    XML_SCHEMAP_SRC_INCLUDE, /* 3050 */    
+    XML_SCHEMAP_SRC_INCLUDE, /* 3050 */
     XML_SCHEMAP_SRC_ATTRIBUTE_1, /* 3051 */
     XML_SCHEMAP_SRC_ATTRIBUTE_2, /* 3052 */
     XML_SCHEMAP_SRC_ATTRIBUTE_3_1, /* 3053 */
     XML_SCHEMAP_SRC_ATTRIBUTE_3_2, /* 3054 */
     XML_SCHEMAP_SRC_ATTRIBUTE_4, /* 3055 */
     XML_SCHEMAP_NO_XMLNS, /* 3056 */
-    XML_SCHEMAP_NO_XSI, /* 3057 */      
+    XML_SCHEMAP_NO_XSI, /* 3057 */
     XML_SCHEMAP_COS_VALID_DEFAULT_1, /* 3058 */
     XML_SCHEMAP_COS_VALID_DEFAULT_2_1, /* 3059 */
     XML_SCHEMAP_COS_VALID_DEFAULT_2_2_1, /* 3060 */
@@ -773,6 +779,8 @@
     XML_SCHEMAP_AU_PROPS_CORRECT, /* 3088 */
     XML_SCHEMAP_A_PROPS_CORRECT_3, /* 3089 */
     XML_SCHEMAP_COS_ALL_LIMITED, /* 3090 */
+    XML_SCHEMATRONV_ASSERT = 4000, /* 4000 */
+    XML_SCHEMATRONV_REPORT,
     XML_MODULE_OPEN = 4900, /* 4900 */
     XML_MODULE_CLOSE, /* 4901 */
     XML_CHECK_FOUND_ELEMENT = 5000,
@@ -835,7 +843,7 @@
  */
 typedef void (XMLCDECL *xmlGenericErrorFunc) (void *ctx,
 				 const char *msg,
-	 			 ...);
+				 ...) ATTRIBUTE_PRINTF(2,3);
 /**
  * xmlStructuredErrorFunc:
  * @userData:  user provided data for the error callback
@@ -850,38 +858,38 @@
  * Use the following function to reset the two global variables
  * xmlGenericError and xmlGenericErrorContext.
  */
-XMLPUBFUN void XMLCALL	
+XMLPUBFUN void XMLCALL
     xmlSetGenericErrorFunc	(void *ctx,
 				 xmlGenericErrorFunc handler);
-XMLPUBFUN void XMLCALL	
+XMLPUBFUN void XMLCALL
     initGenericErrorDefaultFunc	(xmlGenericErrorFunc *handler);
 
-XMLPUBFUN void XMLCALL	
+XMLPUBFUN void XMLCALL
     xmlSetStructuredErrorFunc	(void *ctx,
 				 xmlStructuredErrorFunc handler);
 /*
  * Default message routines used by SAX and Valid context for error
  * and warning reporting.
  */
-XMLPUBFUN void XMLCDECL	
+XMLPUBFUN void XMLCDECL
     xmlParserError		(void *ctx,
 				 const char *msg,
-				 ...);
-XMLPUBFUN void XMLCDECL	
+				 ...) ATTRIBUTE_PRINTF(2,3);
+XMLPUBFUN void XMLCDECL
     xmlParserWarning		(void *ctx,
 				 const char *msg,
-				 ...);
-XMLPUBFUN void XMLCDECL	
+				 ...) ATTRIBUTE_PRINTF(2,3);
+XMLPUBFUN void XMLCDECL
     xmlParserValidityError	(void *ctx,
 				 const char *msg,
-				 ...);
-XMLPUBFUN void XMLCDECL	
+				 ...) ATTRIBUTE_PRINTF(2,3);
+XMLPUBFUN void XMLCDECL
     xmlParserValidityWarning	(void *ctx,
 				 const char *msg,
-				 ...);
-XMLPUBFUN void XMLCALL	
+				 ...) ATTRIBUTE_PRINTF(2,3);
+XMLPUBFUN void XMLCALL
     xmlParserPrintFileInfo	(xmlParserInputPtr input);
-XMLPUBFUN void XMLCALL	
+XMLPUBFUN void XMLCALL
     xmlParserPrintFileContext	(xmlParserInputPtr input);
 
 /*
@@ -899,19 +907,19 @@
     xmlResetError		(xmlErrorPtr err);
 XMLPUBFUN int XMLCALL
     xmlCopyError		(xmlErrorPtr from,
-    				 xmlErrorPtr to);
+				 xmlErrorPtr to);
 
 #ifdef IN_LIBXML
 /*
  * Internal callback reporting routine
  */
-XMLPUBFUN void XMLCALL 
+XMLPUBFUN void XMLCALL
     __xmlRaiseError		(xmlStructuredErrorFunc schannel,
-    				 xmlGenericErrorFunc channel,
-    				 void *data,
+				 xmlGenericErrorFunc channel,
+				 void *data,
                                  void *ctx,
-    				 void *node,
-    				 int domain,
+				 void *node,
+				 int domain,
 				 int code,
 				 xmlErrorLevel level,
 				 const char *file,
@@ -922,10 +930,10 @@
 				 int int1,
 				 int col,
 				 const char *msg,
-				 ...);
-XMLPUBFUN void XMLCALL 
+				 ...) ATTRIBUTE_PRINTF(16,17);
+XMLPUBFUN void XMLCALL
     __xmlSimpleError		(int domain,
-    				 int code,
+				 int code,
 				 xmlNodePtr node,
 				 const char *msg,
 				 const char *extra);
diff --git a/include/libxml/xmlmemory.h b/include/libxml/xmlmemory.h
index 235721c..8f3b109 100644
--- a/include/libxml/xmlmemory.h
+++ b/include/libxml/xmlmemory.h
@@ -20,7 +20,7 @@
  *
  * DEBUG_MEMORY replaces the allocator with a collect and debug
  * shell to the libc allocator.
- * DEBUG_MEMORY should only be activated when debugging 
+ * DEBUG_MEMORY should only be activated when debugging
  * libxml i.e. if libxml has been configured with --with-debug-mem too.
  */
 /* #define DEBUG_MEMORY_FREED */
@@ -35,7 +35,7 @@
 /**
  * DEBUG_MEMORY_LOCATION:
  *
- * DEBUG_MEMORY_LOCATION should be activated only when debugging 
+ * DEBUG_MEMORY_LOCATION should be activated only when debugging
  * libxml i.e. if libxml has been configured with --with-debug-mem too.
  */
 #ifdef DEBUG_MEMORY_LOCATION
@@ -63,7 +63,7 @@
  *
  * Returns a pointer to the newly allocated block or NULL in case of error.
  */
-typedef void *(XMLCALL *xmlMallocFunc)(size_t size);
+typedef void *(ATTRIBUTE_ALLOC_SIZE(1) XMLCALL *xmlMallocFunc)(size_t size);
 
 /**
  * xmlReallocFunc:
@@ -105,18 +105,18 @@
 			 xmlMallocFunc mallocFunc,
 			 xmlReallocFunc reallocFunc,
 			 xmlStrdupFunc strdupFunc);
-XMLPUBFUN int XMLCALL     
+XMLPUBFUN int XMLCALL
 	xmlMemGet	(xmlFreeFunc *freeFunc,
 			 xmlMallocFunc *mallocFunc,
 			 xmlReallocFunc *reallocFunc,
 			 xmlStrdupFunc *strdupFunc);
-XMLPUBFUN int XMLCALL     
+XMLPUBFUN int XMLCALL
 	xmlGcMemSetup	(xmlFreeFunc freeFunc,
 			 xmlMallocFunc mallocFunc,
 			 xmlMallocFunc mallocAtomicFunc,
 			 xmlReallocFunc reallocFunc,
 			 xmlStrdupFunc strdupFunc);
-XMLPUBFUN int XMLCALL     
+XMLPUBFUN int XMLCALL
 	xmlGcMemGet	(xmlFreeFunc *freeFunc,
 			 xmlMallocFunc *mallocFunc,
 			 xmlMallocFunc *mallocAtomicFunc,
@@ -126,42 +126,44 @@
 /*
  * Initialization of the memory layer.
  */
-XMLPUBFUN int XMLCALL	
+XMLPUBFUN int XMLCALL
 	xmlInitMemory	(void);
 
-/* 
+/*
  * Cleanup of the memory layer.
  */
-XMLPUBFUN void XMLCALL                
+XMLPUBFUN void XMLCALL
                 xmlCleanupMemory        (void);
 /*
  * These are specific to the XML debug memory wrapper.
  */
-XMLPUBFUN int XMLCALL	
+XMLPUBFUN int XMLCALL
 	xmlMemUsed	(void);
-XMLPUBFUN int XMLCALL	
+XMLPUBFUN int XMLCALL
 	xmlMemBlocks	(void);
-XMLPUBFUN void XMLCALL	
+XMLPUBFUN void XMLCALL
 	xmlMemDisplay	(FILE *fp);
-XMLPUBFUN void XMLCALL	
+XMLPUBFUN void XMLCALL
+	xmlMemDisplayLast(FILE *fp, long nbBytes);
+XMLPUBFUN void XMLCALL
 	xmlMemShow	(FILE *fp, int nr);
-XMLPUBFUN void XMLCALL	
+XMLPUBFUN void XMLCALL
 	xmlMemoryDump	(void);
-XMLPUBFUN void * XMLCALL	
-	xmlMemMalloc	(size_t size);
-XMLPUBFUN void * XMLCALL	
+XMLPUBFUN void * XMLCALL
+	xmlMemMalloc	(size_t size) ATTRIBUTE_ALLOC_SIZE(1);
+XMLPUBFUN void * XMLCALL
 	xmlMemRealloc	(void *ptr,size_t size);
-XMLPUBFUN void XMLCALL	
+XMLPUBFUN void XMLCALL
 	xmlMemFree	(void *ptr);
-XMLPUBFUN char * XMLCALL	
+XMLPUBFUN char * XMLCALL
 	xmlMemoryStrdup	(const char *str);
-XMLPUBFUN void * XMLCALL  
-	xmlMallocLoc	(size_t size, const char *file, int line);
-XMLPUBFUN void * XMLCALL	
+XMLPUBFUN void * XMLCALL
+	xmlMallocLoc	(size_t size, const char *file, int line) ATTRIBUTE_ALLOC_SIZE(1);
+XMLPUBFUN void * XMLCALL
 	xmlReallocLoc	(void *ptr, size_t size, const char *file, int line);
-XMLPUBFUN void * XMLCALL	
-	xmlMallocAtomicLoc (size_t size, const char *file, int line);
-XMLPUBFUN char * XMLCALL	
+XMLPUBFUN void * XMLCALL
+	xmlMallocAtomicLoc (size_t size, const char *file, int line) ATTRIBUTE_ALLOC_SIZE(1);
+XMLPUBFUN char * XMLCALL
 	xmlMemStrdupLoc	(const char *str, const char *file, int line);
 
 
diff --git a/include/libxml/xmlreader.h b/include/libxml/xmlreader.h
index dfe51a3..6964482 100644
--- a/include/libxml/xmlreader.h
+++ b/include/libxml/xmlreader.h
@@ -18,13 +18,26 @@
 #include <libxml/xmlschemas.h>
 #endif
 
-#ifdef LIBXML_READER_ENABLED
-
 #ifdef __cplusplus
 extern "C" {
 #endif
 
 /**
+ * xmlParserSeverities:
+ *
+ * How severe an error callback is when the per-reader error callback API
+ * is used.
+ */
+typedef enum {
+    XML_PARSER_SEVERITY_VALIDITY_WARNING = 1,
+    XML_PARSER_SEVERITY_VALIDITY_ERROR = 2,
+    XML_PARSER_SEVERITY_WARNING = 3,
+    XML_PARSER_SEVERITY_ERROR = 4
+} xmlParserSeverities;
+
+#ifdef LIBXML_READER_ENABLED
+
+/**
  * xmlTextReaderMode:
  *
  * Internal state values for the reader.
@@ -42,7 +55,7 @@
  * xmlParserProperties:
  *
  * Some common options to use with xmlTextReaderSetParserProp, but it
- * is better to use xmlParserOption and the xmlReaderNewxxx and 
+ * is better to use xmlParserOption and the xmlReaderNewxxx and
  * xmlReaderForxxx APIs now.
  */
 typedef enum {
@@ -53,19 +66,6 @@
 } xmlParserProperties;
 
 /**
- * xmlParserSeverities:
- *
- * How severe an error callback is when the per-reader error callback API
- * is used.
- */
-typedef enum {
-    XML_PARSER_SEVERITY_VALIDITY_WARNING = 1,
-    XML_PARSER_SEVERITY_VALIDITY_ERROR = 2,
-    XML_PARSER_SEVERITY_WARNING = 3,
-    XML_PARSER_SEVERITY_ERROR = 4
-} xmlParserSeverities;
-
-/**
  * xmlReaderTypes:
  *
  * Predefined constants for the different types of nodes.
@@ -111,13 +111,13 @@
 XMLPUBFUN xmlTextReaderPtr XMLCALL
 			xmlNewTextReader	(xmlParserInputBufferPtr input,
 	                                         const char *URI);
-XMLPUBFUN xmlTextReaderPtr XMLCALL	
+XMLPUBFUN xmlTextReaderPtr XMLCALL
 			xmlNewTextReaderFilename(const char *URI);
 
-XMLPUBFUN void XMLCALL			
+XMLPUBFUN void XMLCALL
 			xmlFreeTextReader	(xmlTextReaderPtr reader);
 
-XMLPUBFUN int XMLCALL			
+XMLPUBFUN int XMLCALL
             xmlTextReaderSetup(xmlTextReaderPtr reader,
                    xmlParserInputBufferPtr input, const char *URL,
                    const char *encoding, int options);
@@ -125,120 +125,120 @@
 /*
  * Iterators
  */
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 			xmlTextReaderRead	(xmlTextReaderPtr reader);
 
 #ifdef LIBXML_WRITER_ENABLED
-XMLPUBFUN xmlChar * XMLCALL	
+XMLPUBFUN xmlChar * XMLCALL
 			xmlTextReaderReadInnerXml	(xmlTextReaderPtr reader);
-			
-XMLPUBFUN xmlChar * XMLCALL	
+
+XMLPUBFUN xmlChar * XMLCALL
 			xmlTextReaderReadOuterXml	(xmlTextReaderPtr reader);
 #endif
 
-XMLPUBFUN xmlChar * XMLCALL	
+XMLPUBFUN xmlChar * XMLCALL
 			xmlTextReaderReadString		(xmlTextReaderPtr reader);
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 			xmlTextReaderReadAttributeValue	(xmlTextReaderPtr reader);
 
 /*
  * Attributes of the node
  */
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 			xmlTextReaderAttributeCount(xmlTextReaderPtr reader);
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 			xmlTextReaderDepth	(xmlTextReaderPtr reader);
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 			xmlTextReaderHasAttributes(xmlTextReaderPtr reader);
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 			xmlTextReaderHasValue(xmlTextReaderPtr reader);
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 			xmlTextReaderIsDefault	(xmlTextReaderPtr reader);
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 			xmlTextReaderIsEmptyElement(xmlTextReaderPtr reader);
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 			xmlTextReaderNodeType	(xmlTextReaderPtr reader);
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 			xmlTextReaderQuoteChar	(xmlTextReaderPtr reader);
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 			xmlTextReaderReadState	(xmlTextReaderPtr reader);
 XMLPUBFUN int XMLCALL
                         xmlTextReaderIsNamespaceDecl(xmlTextReaderPtr reader);
 
-XMLPUBFUN const xmlChar * XMLCALL	
+XMLPUBFUN const xmlChar * XMLCALL
 		    xmlTextReaderConstBaseUri	(xmlTextReaderPtr reader);
-XMLPUBFUN const xmlChar * XMLCALL	
+XMLPUBFUN const xmlChar * XMLCALL
 		    xmlTextReaderConstLocalName	(xmlTextReaderPtr reader);
-XMLPUBFUN const xmlChar * XMLCALL	
+XMLPUBFUN const xmlChar * XMLCALL
 		    xmlTextReaderConstName	(xmlTextReaderPtr reader);
-XMLPUBFUN const xmlChar * XMLCALL	
+XMLPUBFUN const xmlChar * XMLCALL
 		    xmlTextReaderConstNamespaceUri(xmlTextReaderPtr reader);
-XMLPUBFUN const xmlChar * XMLCALL	
+XMLPUBFUN const xmlChar * XMLCALL
 		    xmlTextReaderConstPrefix	(xmlTextReaderPtr reader);
-XMLPUBFUN const xmlChar * XMLCALL	
+XMLPUBFUN const xmlChar * XMLCALL
 		    xmlTextReaderConstXmlLang	(xmlTextReaderPtr reader);
-XMLPUBFUN const xmlChar * XMLCALL	
+XMLPUBFUN const xmlChar * XMLCALL
 		    xmlTextReaderConstString	(xmlTextReaderPtr reader,
-		    				 const xmlChar *str);
-XMLPUBFUN const xmlChar * XMLCALL	
+						 const xmlChar *str);
+XMLPUBFUN const xmlChar * XMLCALL
 		    xmlTextReaderConstValue	(xmlTextReaderPtr reader);
 
 /*
  * use the Const version of the routine for
  * better performance and simpler code
  */
-XMLPUBFUN xmlChar * XMLCALL	
+XMLPUBFUN xmlChar * XMLCALL
 			xmlTextReaderBaseUri	(xmlTextReaderPtr reader);
-XMLPUBFUN xmlChar * XMLCALL	
+XMLPUBFUN xmlChar * XMLCALL
 			xmlTextReaderLocalName	(xmlTextReaderPtr reader);
-XMLPUBFUN xmlChar * XMLCALL	
+XMLPUBFUN xmlChar * XMLCALL
 			xmlTextReaderName	(xmlTextReaderPtr reader);
-XMLPUBFUN xmlChar * XMLCALL	
+XMLPUBFUN xmlChar * XMLCALL
 			xmlTextReaderNamespaceUri(xmlTextReaderPtr reader);
-XMLPUBFUN xmlChar * XMLCALL	
+XMLPUBFUN xmlChar * XMLCALL
 			xmlTextReaderPrefix	(xmlTextReaderPtr reader);
-XMLPUBFUN xmlChar * XMLCALL	
+XMLPUBFUN xmlChar * XMLCALL
 			xmlTextReaderXmlLang	(xmlTextReaderPtr reader);
-XMLPUBFUN xmlChar * XMLCALL	
+XMLPUBFUN xmlChar * XMLCALL
 			xmlTextReaderValue	(xmlTextReaderPtr reader);
 
 /*
  * Methods of the XmlTextReader
  */
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 		    xmlTextReaderClose		(xmlTextReaderPtr reader);
-XMLPUBFUN xmlChar * XMLCALL	
+XMLPUBFUN xmlChar * XMLCALL
 		    xmlTextReaderGetAttributeNo	(xmlTextReaderPtr reader,
 						 int no);
-XMLPUBFUN xmlChar * XMLCALL	
+XMLPUBFUN xmlChar * XMLCALL
 		    xmlTextReaderGetAttribute	(xmlTextReaderPtr reader,
 						 const xmlChar *name);
-XMLPUBFUN xmlChar * XMLCALL	
+XMLPUBFUN xmlChar * XMLCALL
 		    xmlTextReaderGetAttributeNs	(xmlTextReaderPtr reader,
 						 const xmlChar *localName,
 						 const xmlChar *namespaceURI);
-XMLPUBFUN xmlParserInputBufferPtr XMLCALL 
+XMLPUBFUN xmlParserInputBufferPtr XMLCALL
 		    xmlTextReaderGetRemainder	(xmlTextReaderPtr reader);
-XMLPUBFUN xmlChar * XMLCALL	
+XMLPUBFUN xmlChar * XMLCALL
 		    xmlTextReaderLookupNamespace(xmlTextReaderPtr reader,
 						 const xmlChar *prefix);
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 		    xmlTextReaderMoveToAttributeNo(xmlTextReaderPtr reader,
 						 int no);
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 		    xmlTextReaderMoveToAttribute(xmlTextReaderPtr reader,
 						 const xmlChar *name);
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 		    xmlTextReaderMoveToAttributeNs(xmlTextReaderPtr reader,
 						 const xmlChar *localName,
 						 const xmlChar *namespaceURI);
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 		    xmlTextReaderMoveToFirstAttribute(xmlTextReaderPtr reader);
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 		    xmlTextReaderMoveToNextAttribute(xmlTextReaderPtr reader);
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 		    xmlTextReaderMoveToElement	(xmlTextReaderPtr reader);
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 		    xmlTextReaderNormalization	(xmlTextReaderPtr reader);
 XMLPUBFUN const xmlChar * XMLCALL
 		    xmlTextReaderConstEncoding  (xmlTextReaderPtr reader);
@@ -246,14 +246,14 @@
 /*
  * Extensions
  */
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 		    xmlTextReaderSetParserProp	(xmlTextReaderPtr reader,
 						 int prop,
 						 int value);
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 		    xmlTextReaderGetParserProp	(xmlTextReaderPtr reader,
 						 int prop);
-XMLPUBFUN xmlNodePtr XMLCALL	
+XMLPUBFUN xmlNodePtr XMLCALL
 		    xmlTextReaderCurrentNode	(xmlTextReaderPtr reader);
 
 XMLPUBFUN int XMLCALL
@@ -262,41 +262,41 @@
 XMLPUBFUN int XMLCALL
             xmlTextReaderGetParserColumnNumber(xmlTextReaderPtr reader);
 
-XMLPUBFUN xmlNodePtr XMLCALL	
+XMLPUBFUN xmlNodePtr XMLCALL
 		    xmlTextReaderPreserve	(xmlTextReaderPtr reader);
 #ifdef LIBXML_PATTERN_ENABLED
-XMLPUBFUN int XMLCALL	
+XMLPUBFUN int XMLCALL
 		    xmlTextReaderPreservePattern(xmlTextReaderPtr reader,
-		    				 const xmlChar *pattern,
+						 const xmlChar *pattern,
 						 const xmlChar **namespaces);
 #endif /* LIBXML_PATTERN_ENABLED */
-XMLPUBFUN xmlDocPtr XMLCALL	
+XMLPUBFUN xmlDocPtr XMLCALL
 		    xmlTextReaderCurrentDoc	(xmlTextReaderPtr reader);
-XMLPUBFUN xmlNodePtr XMLCALL	
+XMLPUBFUN xmlNodePtr XMLCALL
 		    xmlTextReaderExpand		(xmlTextReaderPtr reader);
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 		    xmlTextReaderNext		(xmlTextReaderPtr reader);
 XMLPUBFUN int XMLCALL
 		    xmlTextReaderNextSibling	(xmlTextReaderPtr reader);
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 		    xmlTextReaderIsValid	(xmlTextReaderPtr reader);
 #ifdef LIBXML_SCHEMAS_ENABLED
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 		    xmlTextReaderRelaxNGValidate(xmlTextReaderPtr reader,
 						 const char *rng);
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 		    xmlTextReaderRelaxNGSetSchema(xmlTextReaderPtr reader,
 						 xmlRelaxNGPtr schema);
 XMLPUBFUN int XMLCALL
 		    xmlTextReaderSchemaValidate	(xmlTextReaderPtr reader,
-		    				 const char *xsd);
+						 const char *xsd);
 XMLPUBFUN int XMLCALL
 		    xmlTextReaderSchemaValidateCtxt(xmlTextReaderPtr reader,
 						 xmlSchemaValidCtxtPtr ctxt,
 						 int options);
-XMLPUBFUN int XMLCALL		
+XMLPUBFUN int XMLCALL
 		    xmlTextReaderSetSchema	(xmlTextReaderPtr reader,
-		    				 xmlSchemaPtr schema);
+						 xmlSchemaPtr schema);
 #endif
 XMLPUBFUN const xmlChar * XMLCALL
 		    xmlTextReaderConstXmlVersion(xmlTextReaderPtr reader);
@@ -382,33 +382,43 @@
  * Error handling extensions
  */
 typedef void *  xmlTextReaderLocatorPtr;
-typedef void   (XMLCALL *xmlTextReaderErrorFunc)        (void *arg, 
+
+/**
+ * xmlTextReaderErrorFunc:
+ * @arg: the user argument
+ * @msg: the message
+ * @severity: the severity of the error
+ * @locator: a locator indicating where the error occured
+ *
+ * Signature of an error callback from a reader parser
+ */
+typedef void   (XMLCALL *xmlTextReaderErrorFunc)(void *arg,
 						 const char *msg,
 						 xmlParserSeverities severity,
 						 xmlTextReaderLocatorPtr locator);
-XMLPUBFUN int XMLCALL             
+XMLPUBFUN int XMLCALL
 		    xmlTextReaderLocatorLineNumber(xmlTextReaderLocatorPtr locator);
 /*int             xmlTextReaderLocatorLinePosition(xmlTextReaderLocatorPtr locator);*/
-XMLPUBFUN xmlChar * XMLCALL       
+XMLPUBFUN xmlChar * XMLCALL
 		    xmlTextReaderLocatorBaseURI (xmlTextReaderLocatorPtr locator);
-XMLPUBFUN void XMLCALL            
-		    xmlTextReaderSetErrorHandler(xmlTextReaderPtr reader, 
-						 xmlTextReaderErrorFunc f, 
+XMLPUBFUN void XMLCALL
+		    xmlTextReaderSetErrorHandler(xmlTextReaderPtr reader,
+						 xmlTextReaderErrorFunc f,
 						 void *arg);
 XMLPUBFUN void XMLCALL
 		    xmlTextReaderSetStructuredErrorHandler(xmlTextReaderPtr reader,
 							   xmlStructuredErrorFunc f,
 							   void *arg);
-XMLPUBFUN void XMLCALL            
-		    xmlTextReaderGetErrorHandler(xmlTextReaderPtr reader, 
-						 xmlTextReaderErrorFunc *f, 
+XMLPUBFUN void XMLCALL
+		    xmlTextReaderGetErrorHandler(xmlTextReaderPtr reader,
+						 xmlTextReaderErrorFunc *f,
 						 void **arg);
 
+#endif /* LIBXML_READER_ENABLED */
+
 #ifdef __cplusplus
 }
 #endif
 
-#endif /* LIBXML_READER_ENABLED */
-
 #endif /* __XML_XMLREADER_H__ */
 
diff --git a/include/libxml/xmlregexp.h b/include/libxml/xmlregexp.h
index 022cd6a..7009645 100644
--- a/include/libxml/xmlregexp.h
+++ b/include/libxml/xmlregexp.h
@@ -38,7 +38,7 @@
 
 #ifdef __cplusplus
 }
-#endif 
+#endif
 #include <libxml/tree.h>
 #include <libxml/dict.h>
 #ifdef __cplusplus
@@ -51,16 +51,22 @@
 XMLPUBFUN xmlRegexpPtr XMLCALL
 		    xmlRegexpCompile	(const xmlChar *regexp);
 XMLPUBFUN void XMLCALL			 xmlRegFreeRegexp(xmlRegexpPtr regexp);
-XMLPUBFUN int XMLCALL			
+XMLPUBFUN int XMLCALL
 		    xmlRegexpExec	(xmlRegexpPtr comp,
 					 const xmlChar *value);
-XMLPUBFUN void XMLCALL			
-    		    xmlRegexpPrint	(FILE *output,
+XMLPUBFUN void XMLCALL
+		    xmlRegexpPrint	(FILE *output,
 					 xmlRegexpPtr regexp);
-XMLPUBFUN int XMLCALL			
+XMLPUBFUN int XMLCALL
 		    xmlRegexpIsDeterminist(xmlRegexpPtr comp);
 
-/*
+/**
+ * xmlRegExecCallbacks:
+ * @exec: the regular expression context
+ * @token: the current token string
+ * @transdata: transition data
+ * @inputdata: input data
+ *
  * Callback function when doing a transition in the automata
  */
 typedef void (*xmlRegExecCallbacks) (xmlRegExecCtxtPtr exec,
@@ -71,17 +77,17 @@
 /*
  * The progressive API
  */
-XMLPUBFUN xmlRegExecCtxtPtr XMLCALL	
-    		    xmlRegNewExecCtxt	(xmlRegexpPtr comp,
+XMLPUBFUN xmlRegExecCtxtPtr XMLCALL
+		    xmlRegNewExecCtxt	(xmlRegexpPtr comp,
 					 xmlRegExecCallbacks callback,
 					 void *data);
-XMLPUBFUN void XMLCALL			
+XMLPUBFUN void XMLCALL
 		    xmlRegFreeExecCtxt	(xmlRegExecCtxtPtr exec);
-XMLPUBFUN int XMLCALL			
-    		    xmlRegExecPushString(xmlRegExecCtxtPtr exec,
+XMLPUBFUN int XMLCALL
+		    xmlRegExecPushString(xmlRegExecCtxtPtr exec,
 					 const xmlChar *value,
 					 void *data);
-XMLPUBFUN int XMLCALL			
+XMLPUBFUN int XMLCALL
 		    xmlRegExecPushString2(xmlRegExecCtxtPtr exec,
 					 const xmlChar *value,
 					 const xmlChar *value2,
@@ -89,15 +95,15 @@
 
 XMLPUBFUN int XMLCALL
 		    xmlRegExecNextValues(xmlRegExecCtxtPtr exec,
-		    			 int *nbval,
-		    			 int *nbneg,
+					 int *nbval,
+					 int *nbneg,
 					 xmlChar **values,
 					 int *terminal);
 XMLPUBFUN int XMLCALL
 		    xmlRegExecErrInfo	(xmlRegExecCtxtPtr exec,
-		    			 const xmlChar **string,
+					 const xmlChar **string,
 					 int *nbval,
-		    			 int *nbneg,
+					 int *nbneg,
 					 xmlChar **values,
 					 int *terminal);
 #ifdef LIBXML_EXPR_ENABLED
@@ -135,7 +141,7 @@
 } xmlExpNodeType;
 
 /*
- * 2 core expressions shared by all for the empty language set 
+ * 2 core expressions shared by all for the empty language set
  * and for the set with just the empty token
  */
 XMLPUBVAR xmlExpNodePtr forbiddenExp;
@@ -209,7 +215,7 @@
 #endif /* LIBXML_EXPR_ENABLED */
 #ifdef __cplusplus
 }
-#endif 
+#endif
 
 #endif /* LIBXML_REGEXP_ENABLED */
 
diff --git a/include/libxml/xmlsave.h b/include/libxml/xmlsave.h
index c71c71a..4201b4d 100644
--- a/include/libxml/xmlsave.h
+++ b/include/libxml/xmlsave.h
@@ -30,7 +30,10 @@
     XML_SAVE_FORMAT     = 1<<0,	/* format save output */
     XML_SAVE_NO_DECL    = 1<<1,	/* drop the xml declaration */
     XML_SAVE_NO_EMPTY	= 1<<2, /* no empty tags */
-    XML_SAVE_NO_XHTML	= 1<<3  /* disable XHTML1 specific rules */
+    XML_SAVE_NO_XHTML	= 1<<3, /* disable XHTML1 specific rules */
+    XML_SAVE_XHTML	= 1<<4, /* force XHTML1 specific rules */
+    XML_SAVE_AS_XML     = 1<<5, /* force XML serialization on HTML doc */
+    XML_SAVE_AS_HTML    = 1<<6  /* force HTML serialization on XML doc */
 } xmlSaveOption;
 
 
diff --git a/include/libxml/xmlschemas.h b/include/libxml/xmlschemas.h
index 15faef5..ebef3a7 100644
--- a/include/libxml/xmlschemas.h
+++ b/include/libxml/xmlschemas.h
@@ -56,7 +56,7 @@
 
 /*
 * ATTENTION: Change xmlSchemaSetValidOptions's check
-* for invalid values, if adding to the validation 
+* for invalid values, if adding to the validation
 * options below.
 */
 /**
@@ -85,11 +85,28 @@
 typedef xmlSchema *xmlSchemaPtr;
 
 /**
+ * xmlSchemaValidityErrorFunc:
+ * @ctx: the validation context
+ * @msg: the message
+ * @...: extra arguments
+ *
+ * Signature of an error callback from an XSD validation
+ */
+typedef void (XMLCDECL *xmlSchemaValidityErrorFunc) (void *ctx, const char *msg, ...) ATTRIBUTE_PRINTF(2,3);
+
+/**
+ * xmlSchemaValidityWarningFunc:
+ * @ctx: the validation context
+ * @msg: the message
+ * @...: extra arguments
+ *
+ * Signature of a warning callback from an XSD validation
+ */
+typedef void (XMLCDECL *xmlSchemaValidityWarningFunc) (void *ctx, const char *msg, ...) ATTRIBUTE_PRINTF(2,3);
+
+/**
  * A schemas validation context
  */
-typedef void (XMLCDECL *xmlSchemaValidityErrorFunc) (void *ctx, const char *msg, ...);
-typedef void (XMLCDECL *xmlSchemaValidityWarningFunc) (void *ctx, const char *msg, ...);
-
 typedef struct _xmlSchemaParserCtxt xmlSchemaParserCtxt;
 typedef xmlSchemaParserCtxt *xmlSchemaParserCtxtPtr;
 
@@ -99,16 +116,16 @@
 /*
  * Interfaces for parsing.
  */
-XMLPUBFUN xmlSchemaParserCtxtPtr XMLCALL 
+XMLPUBFUN xmlSchemaParserCtxtPtr XMLCALL
 	    xmlSchemaNewParserCtxt	(const char *URL);
-XMLPUBFUN xmlSchemaParserCtxtPtr XMLCALL 
+XMLPUBFUN xmlSchemaParserCtxtPtr XMLCALL
 	    xmlSchemaNewMemParserCtxt	(const char *buffer,
 					 int size);
 XMLPUBFUN xmlSchemaParserCtxtPtr XMLCALL
 	    xmlSchemaNewDocParserCtxt	(xmlDocPtr doc);
-XMLPUBFUN void XMLCALL		
+XMLPUBFUN void XMLCALL
 	    xmlSchemaFreeParserCtxt	(xmlSchemaParserCtxtPtr ctxt);
-XMLPUBFUN void XMLCALL		
+XMLPUBFUN void XMLCALL
 	    xmlSchemaSetParserErrors	(xmlSchemaParserCtxtPtr ctxt,
 					 xmlSchemaValidityErrorFunc err,
 					 xmlSchemaValidityWarningFunc warn,
@@ -125,19 +142,19 @@
 XMLPUBFUN int XMLCALL
 		xmlSchemaIsValid	(xmlSchemaValidCtxtPtr ctxt);
 
-XMLPUBFUN xmlSchemaPtr XMLCALL	
+XMLPUBFUN xmlSchemaPtr XMLCALL
 	    xmlSchemaParse		(xmlSchemaParserCtxtPtr ctxt);
-XMLPUBFUN void XMLCALL		
+XMLPUBFUN void XMLCALL
 	    xmlSchemaFree		(xmlSchemaPtr schema);
 #ifdef LIBXML_OUTPUT_ENABLED
-XMLPUBFUN void XMLCALL		
+XMLPUBFUN void XMLCALL
 	    xmlSchemaDump		(FILE *output,
 					 xmlSchemaPtr schema);
 #endif /* LIBXML_OUTPUT_ENABLED */
 /*
  * Interfaces for validating
  */
-XMLPUBFUN void XMLCALL		
+XMLPUBFUN void XMLCALL
 	    xmlSchemaSetValidErrors	(xmlSchemaValidCtxtPtr ctxt,
 					 xmlSchemaValidityErrorFunc err,
 					 xmlSchemaValidityWarningFunc warn,
@@ -157,11 +174,11 @@
 XMLPUBFUN int XMLCALL
 	    xmlSchemaValidCtxtGetOptions(xmlSchemaValidCtxtPtr ctxt);
 
-XMLPUBFUN xmlSchemaValidCtxtPtr XMLCALL	
+XMLPUBFUN xmlSchemaValidCtxtPtr XMLCALL
 	    xmlSchemaNewValidCtxt	(xmlSchemaPtr schema);
-XMLPUBFUN void XMLCALL			
+XMLPUBFUN void XMLCALL
 	    xmlSchemaFreeValidCtxt	(xmlSchemaValidCtxtPtr ctxt);
-XMLPUBFUN int XMLCALL			
+XMLPUBFUN int XMLCALL
 	    xmlSchemaValidateDoc	(xmlSchemaValidCtxtPtr ctxt,
 					 xmlDocPtr instance);
 XMLPUBFUN int XMLCALL
@@ -178,8 +195,11 @@
 					 const char * filename,
 					 int options);
 
+XMLPUBFUN xmlParserCtxtPtr XMLCALL
+	    xmlSchemaValidCtxtGetParserCtxt(xmlSchemaValidCtxtPtr ctxt);
+
 /*
- * Interface to insert Schemas SAX velidation in a SAX stream
+ * Interface to insert Schemas SAX validation in a SAX stream
  */
 typedef struct _xmlSchemaSAXPlug xmlSchemaSAXPlugStruct;
 typedef xmlSchemaSAXPlugStruct *xmlSchemaSAXPlugPtr;
diff --git a/include/libxml/xmlversion.h b/include/libxml/xmlversion.h
index ee529c4..a98e00c 100644
--- a/include/libxml/xmlversion.h
+++ b/include/libxml/xmlversion.h
@@ -29,28 +29,28 @@
  *
  * the version string like "1.2.3"
  */
-#define LIBXML_DOTTED_VERSION "2.6.31"
+#define LIBXML_DOTTED_VERSION "2.7.3"
 
 /**
  * LIBXML_VERSION:
  *
  * the version number: 1.2.3 value is 10203
  */
-#define LIBXML_VERSION 20631
+#define LIBXML_VERSION 20703
 
 /**
  * LIBXML_VERSION_STRING:
  *
  * the version number string, 1.2.3 value is "10203"
  */
-#define LIBXML_VERSION_STRING "20631"
+#define LIBXML_VERSION_STRING "20703"
 
 /**
  * LIBXML_VERSION_EXTRA:
  *
  * extra version information, used to show a CVS compilation
  */
-#define LIBXML_VERSION_EXTRA "-CVS2831"
+#define LIBXML_VERSION_EXTRA ""
 
 /**
  * LIBXML_TEST_VERSION:
@@ -58,7 +58,7 @@
  * Macro to check that the libxml version in use is compatible with
  * the version the software has been compiled against
  */
-#define LIBXML_TEST_VERSION xmlCheckVersion(20631);
+#define LIBXML_TEST_VERSION xmlCheckVersion(20703);
 
 #ifndef VMS
 #if 0
@@ -370,7 +370,7 @@
  *
  * the string suffix used by dynamic modules (usually shared libraries)
  */
-#define LIBXML_MODULE_EXTENSION ".so" 
+#define LIBXML_MODULE_EXTENSION "" 
 #endif
 
 /**
@@ -382,22 +382,74 @@
 #define LIBXML_ZLIB_ENABLED
 #endif
 
+#ifdef __GNUC__
+#ifdef HAVE_ANSIDECL_H
+#include <ansidecl.h>
+#endif
+
 /**
  * ATTRIBUTE_UNUSED:
  *
  * Macro used to signal to GCC unused function parameters
  */
-#ifdef __GNUC__
-#ifdef HAVE_ANSIDECL_H
-#include <ansidecl.h>
-#endif
+
 #ifndef ATTRIBUTE_UNUSED
 #define ATTRIBUTE_UNUSED __attribute__((unused))
 #endif
+
+/**
+ * ATTRIBUTE_ALLOC_SIZE:
+ *
+ * Macro used to indicate to GCC this is an allocator function
+ */
+
+#ifndef ATTRIBUTE_ALLOC_SIZE
+# if ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)))
+#  define ATTRIBUTE_ALLOC_SIZE(x) __attribute__((alloc_size(x)))
+# else
+#  define ATTRIBUTE_ALLOC_SIZE(x)
+# endif
 #else
-#define ATTRIBUTE_UNUSED
+# define ATTRIBUTE_ALLOC_SIZE(x)
 #endif
 
+/**
+ * ATTRIBUTE_PRINTF:
+ *
+ * Macro used to indicate to GCC the parameter are printf like
+ */
+
+#ifndef ATTRIBUTE_PRINTF
+# if ((__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)))
+#  define ATTRIBUTE_PRINTF(fmt,args) __attribute__((__format__(__printf__,fmt,args)))
+# else
+#  define ATTRIBUTE_PRINTF(fmt,args)
+# endif
+#else
+# define ATTRIBUTE_PRINTF(fmt,args)
+#endif
+
+#else /* ! __GNUC__ */
+/**
+ * ATTRIBUTE_UNUSED:
+ *
+ * Macro used to signal to GCC unused function parameters
+ */
+#define ATTRIBUTE_UNUSED
+/**
+ * ATTRIBUTE_ALLOC_SIZE:
+ *
+ * Macro used to indicate to GCC this is an allocator function
+ */
+#define ATTRIBUTE_ALLOC_SIZE(x)
+/**
+ * ATTRIBUTE_PRINTF:
+ *
+ * Macro used to indicate to GCC the parameter are printf like
+ */
+#define ATTRIBUTE_PRINTF(fmt,args)
+#endif /* __GNUC__ */
+
 #ifdef __cplusplus
 }
 #endif /* __cplusplus */
diff --git a/include/libxml/xmlwriter.h b/include/libxml/xmlwriter.h
index 31ceb5f..df4509d 100644
--- a/include/libxml/xmlwriter.h
+++ b/include/libxml/xmlwriter.h
@@ -69,11 +69,13 @@
     XMLPUBFUN int XMLCALL xmlTextWriterEndComment(xmlTextWriterPtr writer);
     XMLPUBFUN int XMLCALL
         xmlTextWriterWriteFormatComment(xmlTextWriterPtr writer,
-                                        const char *format, ...);
+                                        const char *format, ...)
+					ATTRIBUTE_PRINTF(2,3);
     XMLPUBFUN int XMLCALL
         xmlTextWriterWriteVFormatComment(xmlTextWriterPtr writer,
                                          const char *format,
-                                         va_list argptr);
+                                         va_list argptr)
+					 ATTRIBUTE_PRINTF(2,0);
     XMLPUBFUN int XMLCALL xmlTextWriterWriteComment(xmlTextWriterPtr
                                                     writer,
                                                     const xmlChar *
@@ -102,12 +104,14 @@
     XMLPUBFUN int XMLCALL
         xmlTextWriterWriteFormatElement(xmlTextWriterPtr writer,
                                         const xmlChar * name,
-                                        const char *format, ...);
+                                        const char *format, ...)
+					ATTRIBUTE_PRINTF(3,4);
     XMLPUBFUN int XMLCALL
         xmlTextWriterWriteVFormatElement(xmlTextWriterPtr writer,
                                          const xmlChar * name,
                                          const char *format,
-                                         va_list argptr);
+                                         va_list argptr)
+					 ATTRIBUTE_PRINTF(3,0);
     XMLPUBFUN int XMLCALL xmlTextWriterWriteElement(xmlTextWriterPtr
                                                     writer,
                                                     const xmlChar * name,
@@ -118,14 +122,16 @@
                                           const xmlChar * prefix,
                                           const xmlChar * name,
                                           const xmlChar * namespaceURI,
-                                          const char *format, ...);
+                                          const char *format, ...)
+					  ATTRIBUTE_PRINTF(5,6);
     XMLPUBFUN int XMLCALL
         xmlTextWriterWriteVFormatElementNS(xmlTextWriterPtr writer,
                                            const xmlChar * prefix,
                                            const xmlChar * name,
                                            const xmlChar * namespaceURI,
                                            const char *format,
-                                           va_list argptr);
+                                           va_list argptr)
+					   ATTRIBUTE_PRINTF(5,0);
     XMLPUBFUN int XMLCALL xmlTextWriterWriteElementNS(xmlTextWriterPtr
                                                       writer,
                                                       const xmlChar *
@@ -141,10 +147,12 @@
  */
     XMLPUBFUN int XMLCALL
         xmlTextWriterWriteFormatRaw(xmlTextWriterPtr writer,
-                                    const char *format, ...);
+                                    const char *format, ...)
+				    ATTRIBUTE_PRINTF(2,3);
     XMLPUBFUN int XMLCALL
         xmlTextWriterWriteVFormatRaw(xmlTextWriterPtr writer,
-                                     const char *format, va_list argptr);
+                                     const char *format, va_list argptr)
+				     ATTRIBUTE_PRINTF(2,0);
     XMLPUBFUN int XMLCALL
         xmlTextWriterWriteRawLen(xmlTextWriterPtr writer,
                                  const xmlChar * content, int len);
@@ -154,12 +162,14 @@
     XMLPUBFUN int XMLCALL xmlTextWriterWriteFormatString(xmlTextWriterPtr
                                                          writer,
                                                          const char
-                                                         *format, ...);
+                                                         *format, ...)
+							 ATTRIBUTE_PRINTF(2,3);
     XMLPUBFUN int XMLCALL xmlTextWriterWriteVFormatString(xmlTextWriterPtr
                                                           writer,
                                                           const char
                                                           *format,
-                                                          va_list argptr);
+                                                          va_list argptr)
+							  ATTRIBUTE_PRINTF(2,0);
     XMLPUBFUN int XMLCALL xmlTextWriterWriteString(xmlTextWriterPtr writer,
                                                    const xmlChar *
                                                    content);
@@ -193,12 +203,14 @@
     XMLPUBFUN int XMLCALL
         xmlTextWriterWriteFormatAttribute(xmlTextWriterPtr writer,
                                           const xmlChar * name,
-                                          const char *format, ...);
+                                          const char *format, ...)
+					  ATTRIBUTE_PRINTF(3,4);
     XMLPUBFUN int XMLCALL
         xmlTextWriterWriteVFormatAttribute(xmlTextWriterPtr writer,
                                            const xmlChar * name,
                                            const char *format,
-                                           va_list argptr);
+                                           va_list argptr)
+					   ATTRIBUTE_PRINTF(3,0);
     XMLPUBFUN int XMLCALL xmlTextWriterWriteAttribute(xmlTextWriterPtr
                                                       writer,
                                                       const xmlChar * name,
@@ -209,14 +221,16 @@
                                             const xmlChar * prefix,
                                             const xmlChar * name,
                                             const xmlChar * namespaceURI,
-                                            const char *format, ...);
+                                            const char *format, ...)
+					    ATTRIBUTE_PRINTF(5,6);
     XMLPUBFUN int XMLCALL
         xmlTextWriterWriteVFormatAttributeNS(xmlTextWriterPtr writer,
                                              const xmlChar * prefix,
                                              const xmlChar * name,
                                              const xmlChar * namespaceURI,
                                              const char *format,
-                                             va_list argptr);
+                                             va_list argptr)
+					     ATTRIBUTE_PRINTF(5,0);
     XMLPUBFUN int XMLCALL xmlTextWriterWriteAttributeNS(xmlTextWriterPtr
                                                         writer,
                                                         const xmlChar *
@@ -242,11 +256,13 @@
     XMLPUBFUN int XMLCALL
         xmlTextWriterWriteFormatPI(xmlTextWriterPtr writer,
                                    const xmlChar * target,
-                                   const char *format, ...);
+                                   const char *format, ...)
+				   ATTRIBUTE_PRINTF(3,4);
     XMLPUBFUN int XMLCALL
         xmlTextWriterWriteVFormatPI(xmlTextWriterPtr writer,
                                     const xmlChar * target,
-                                    const char *format, va_list argptr);
+                                    const char *format, va_list argptr)
+				    ATTRIBUTE_PRINTF(3,0);
     XMLPUBFUN int XMLCALL
         xmlTextWriterWritePI(xmlTextWriterPtr writer,
                              const xmlChar * target,
@@ -270,10 +286,12 @@
  */
     XMLPUBFUN int XMLCALL
         xmlTextWriterWriteFormatCDATA(xmlTextWriterPtr writer,
-                                      const char *format, ...);
+                                      const char *format, ...)
+				      ATTRIBUTE_PRINTF(2,3);
     XMLPUBFUN int XMLCALL
         xmlTextWriterWriteVFormatCDATA(xmlTextWriterPtr writer,
-                                       const char *format, va_list argptr);
+                                       const char *format, va_list argptr)
+				       ATTRIBUTE_PRINTF(2,0);
     XMLPUBFUN int XMLCALL
         xmlTextWriterWriteCDATA(xmlTextWriterPtr writer,
                                 const xmlChar * content);
@@ -296,13 +314,15 @@
                                     const xmlChar * name,
                                     const xmlChar * pubid,
                                     const xmlChar * sysid,
-                                    const char *format, ...);
+                                    const char *format, ...)
+				    ATTRIBUTE_PRINTF(5,6);
     XMLPUBFUN int XMLCALL
         xmlTextWriterWriteVFormatDTD(xmlTextWriterPtr writer,
                                      const xmlChar * name,
                                      const xmlChar * pubid,
                                      const xmlChar * sysid,
-                                     const char *format, va_list argptr);
+                                     const char *format, va_list argptr)
+				     ATTRIBUTE_PRINTF(5,0);
     XMLPUBFUN int XMLCALL
         xmlTextWriterWriteDTD(xmlTextWriterPtr writer,
                               const xmlChar * name,
@@ -332,12 +352,14 @@
     XMLPUBFUN int XMLCALL
         xmlTextWriterWriteFormatDTDElement(xmlTextWriterPtr writer,
                                            const xmlChar * name,
-                                           const char *format, ...);
+                                           const char *format, ...)
+					   ATTRIBUTE_PRINTF(3,4);
     XMLPUBFUN int XMLCALL
         xmlTextWriterWriteVFormatDTDElement(xmlTextWriterPtr writer,
                                             const xmlChar * name,
                                             const char *format,
-                                            va_list argptr);
+                                            va_list argptr)
+					    ATTRIBUTE_PRINTF(3,0);
     XMLPUBFUN int XMLCALL xmlTextWriterWriteDTDElement(xmlTextWriterPtr
                                                        writer,
                                                        const xmlChar *
@@ -360,12 +382,14 @@
     XMLPUBFUN int XMLCALL
         xmlTextWriterWriteFormatDTDAttlist(xmlTextWriterPtr writer,
                                            const xmlChar * name,
-                                           const char *format, ...);
+                                           const char *format, ...)
+					   ATTRIBUTE_PRINTF(3,4);
     XMLPUBFUN int XMLCALL
         xmlTextWriterWriteVFormatDTDAttlist(xmlTextWriterPtr writer,
                                             const xmlChar * name,
                                             const char *format,
-                                            va_list argptr);
+                                            va_list argptr)
+					    ATTRIBUTE_PRINTF(3,0);
     XMLPUBFUN int XMLCALL xmlTextWriterWriteDTDAttlist(xmlTextWriterPtr
                                                        writer,
                                                        const xmlChar *
@@ -389,13 +413,15 @@
         xmlTextWriterWriteFormatDTDInternalEntity(xmlTextWriterPtr writer,
                                                   int pe,
                                                   const xmlChar * name,
-                                                  const char *format, ...);
+                                                  const char *format, ...)
+						  ATTRIBUTE_PRINTF(4,5);
     XMLPUBFUN int XMLCALL
         xmlTextWriterWriteVFormatDTDInternalEntity(xmlTextWriterPtr writer,
                                                    int pe,
                                                    const xmlChar * name,
                                                    const char *format,
-                                                   va_list argptr);
+                                                   va_list argptr)
+						   ATTRIBUTE_PRINTF(4,0);
     XMLPUBFUN int XMLCALL
         xmlTextWriterWriteDTDInternalEntity(xmlTextWriterPtr writer,
                                             int pe,
diff --git a/include/libxml/xpath.h b/include/libxml/xpath.h
index 725cebe..1a9e30e 100644
--- a/include/libxml/xpath.h
+++ b/include/libxml/xpath.h
@@ -278,6 +278,9 @@
  *    - the set of namespace declarations in scope for the expression 
  * Following the switch to hash tables, this need to be trimmed up at
  * the next binary incompatible release.
+ * The node may be modified when the context is passed to libxml2
+ * for an XPath evaluation so you may need to initialize it again
+ * before the next call.
  */
 
 struct _xmlXPathContext {
diff --git a/libxml.h b/libxml.h
index f5c6394..3c44c83 100644
--- a/libxml.h
+++ b/libxml.h
@@ -77,6 +77,7 @@
  */
 void __xmlGlobalInitMutexLock(void);
 void __xmlGlobalInitMutexUnlock(void);
+void __xmlGlobalInitMutexDestroy(void);
 
 #ifdef IN_LIBXML
 #ifdef __GNUC__
diff --git a/nanoftp.c b/nanoftp.c
index 8c4ea88..a54b85b 100644
--- a/nanoftp.c
+++ b/nanoftp.c
@@ -89,7 +89,7 @@
  * A couple portability macros
  */
 #ifndef _WINSOCKAPI_
-#ifndef __BEOS__
+#if !defined(__BEOS__) || defined(__HAIKU__)
 #define closesocket(s) close(s)
 #endif
 #define SOCKET int
diff --git a/nanohttp.c b/nanohttp.c
index 91c7e87..9001ae5 100644
--- a/nanohttp.c
+++ b/nanohttp.c
@@ -95,7 +95,7 @@
  * A couple portability macros
  */
 #ifndef _WINSOCKAPI_
-#ifndef __BEOS__
+#if !defined(__BEOS__) || defined(__HAIKU__)
 #define closesocket(s) close(s)
 #endif
 #define SOCKET int
@@ -844,7 +844,7 @@
 	status = ioctl(s, FIONBIO, &enable);
     }
 #else /* VMS */
-#if defined(__BEOS__)
+#if defined(__BEOS__) && !defined(__HAIKU__)
 	{
 		bool noblock = true;
 		status = setsockopt(s, SOL_SOCKET, SO_NONBLOCK, &noblock, sizeof(noblock));
@@ -1332,13 +1332,23 @@
     if (headers != NULL)
 	blen += strlen(headers) + 2;
     if (contentType && *contentType)
+	/* reserve for string plus 'Content-Type: \r\n" */
 	blen += strlen(*contentType) + 16;
     if (ctxt->query != NULL)
+	/* 1 for '?' */
 	blen += strlen(ctxt->query) + 1;
     blen += strlen(method) + strlen(ctxt->path) + 24;
 #ifdef HAVE_ZLIB_H
+    /* reserve for possible 'Accept-Encoding: gzip' string */
     blen += 23;
 #endif
+    if (ctxt->port != 80) {
+	/* reserve space for ':xxxxx', incl. potential proxy */
+	if (proxy)
+	    blen += 12;
+	else
+	    blen += 6;
+    }
     bp = (char*)xmlMallocAtomic(blen);
     if ( bp == NULL ) {
         xmlNanoHTTPFreeCtxt( ctxt );
diff --git a/parser.c b/parser.c
index 529e061..9db664f 100644
--- a/parser.c
+++ b/parser.c
@@ -80,20 +80,111 @@
 #include <zlib.h>
 #endif
 
+static void
+xmlFatalErr(xmlParserCtxtPtr ctxt, xmlParserErrors error, const char *info);
+
+/************************************************************************
+ *									*
+ *	Arbitrary limits set in the parser. See XML_PARSE_HUGE		*
+ *									*
+ ************************************************************************/
+
+#define XML_PARSER_BIG_ENTITY 1000
+#define XML_PARSER_LOT_ENTITY 5000
+
+/*
+ * XML_PARSER_NON_LINEAR is the threshold where the ratio of parsed entity
+ *    replacement over the size in byte of the input indicates that you have
+ *    and eponential behaviour. A value of 10 correspond to at least 3 entity
+ *    replacement per byte of input.
+ */
+#define XML_PARSER_NON_LINEAR 10
+
+/*
+ * xmlParserEntityCheck
+ *
+ * Function to check non-linear entity expansion behaviour
+ * This is here to detect and stop exponential linear entity expansion
+ * This is not a limitation of the parser but a safety
+ * boundary feature. It can be disabled with the XML_PARSE_HUGE
+ * parser option.
+ */
+static int
+xmlParserEntityCheck(xmlParserCtxtPtr ctxt, unsigned long size,
+                     xmlEntityPtr ent)
+{
+    unsigned long consumed = 0;
+
+    if ((ctxt == NULL) || (ctxt->options & XML_PARSE_HUGE))
+        return (0);
+    if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP)
+        return (1);
+    if (size != 0) {
+        /*
+         * Do the check based on the replacement size of the entity
+         */
+        if (size < XML_PARSER_BIG_ENTITY)
+	    return(0);
+
+        /*
+         * A limit on the amount of text data reasonably used
+         */
+        if (ctxt->input != NULL) {
+            consumed = ctxt->input->consumed +
+                (ctxt->input->cur - ctxt->input->base);
+        }
+        consumed += ctxt->sizeentities;
+
+        if ((size < XML_PARSER_NON_LINEAR * consumed) &&
+	    (ctxt->nbentities * 3 < XML_PARSER_NON_LINEAR * consumed))
+            return (0);
+    } else if (ent != NULL) {
+        /*
+         * use the number of parsed entities in the replacement
+         */
+        size = ent->checked;
+
+        /*
+         * The amount of data parsed counting entities size only once
+         */
+        if (ctxt->input != NULL) {
+            consumed = ctxt->input->consumed +
+                (ctxt->input->cur - ctxt->input->base);
+        }
+        consumed += ctxt->sizeentities;
+
+        /*
+         * Check the density of entities for the amount of data
+	 * knowing an entity reference will take at least 3 bytes
+         */
+        if (size * 3 < consumed * XML_PARSER_NON_LINEAR)
+            return (0);
+    } else {
+        /*
+         * strange we got no data for checking just return
+         */
+        return (0);
+    }
+
+    xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
+    return (1);
+}
+
 /**
  * xmlParserMaxDepth:
  *
- * arbitrary depth limit for the XML documents that we allow to 
- * process. This is not a limitation of the parser but a safety 
- * boundary feature.
+ * arbitrary depth limit for the XML documents that we allow to
+ * process. This is not a limitation of the parser but a safety
+ * boundary feature. It can be disabled with the XML_PARSE_HUGE
+ * parser option.
  */
-unsigned int xmlParserMaxDepth = 1024;
+unsigned int xmlParserMaxDepth = 256;
+
+
 
 #define SAX2 1
-
 #define XML_PARSER_BIG_BUFFER_SIZE 300
 #define XML_PARSER_BUFFER_SIZE 100
-
 #define SAX_COMPAT_MODE BAD_CAST "SAX compatibility mode document"
 
 /*
@@ -116,6 +207,9 @@
 		      void *user_data, int depth, const xmlChar *URL,
 		      const xmlChar *ID, xmlNodePtr *list);
 
+static int
+xmlCtxtUseOptionsInternal(xmlParserCtxtPtr ctxt, int options,
+                          const char *encoding);
 #ifdef LIBXML_LEGACY_ENABLED
 static void
 xmlAddEntityReference(xmlEntityPtr ent, xmlNodePtr firstNode,
@@ -126,6 +220,9 @@
 xmlParseBalancedChunkMemoryInternal(xmlParserCtxtPtr oldctxt,
 		      const xmlChar *string, void *user_data, xmlNodePtr *lst);
 
+static int
+xmlLoadEntityContent(xmlParserCtxtPtr ctxt, xmlEntityPtr entity);
+
 /************************************************************************
  *									*
  * 		Some factorized error routines				*
@@ -415,7 +512,7 @@
               const char *msg, const xmlChar *str1, const xmlChar *str2)
 {
     xmlStructuredErrorFunc schannel = NULL;
-    
+
     if ((ctxt != NULL) && (ctxt->disableSAX != 0) &&
         (ctxt->instate == XML_PARSER_EOF))
 	return;
@@ -442,7 +539,7 @@
  */
 static void
 xmlValidityError(xmlParserCtxtPtr ctxt, xmlParserErrors error,
-              const char *msg, const xmlChar *str1)
+              const char *msg, const xmlChar *str1, const xmlChar *str2)
 {
     xmlStructuredErrorFunc schannel = NULL;
 
@@ -458,8 +555,8 @@
                     ctxt->vctxt.error, ctxt->vctxt.userData,
                     ctxt, NULL, XML_FROM_DTD, error,
                     XML_ERR_ERROR, NULL, 0, (const char *) str1,
-		    NULL, NULL, 0, 0,
-		    msg, (const char *) str1);
+		    (const char *) str2, NULL, 0, 0,
+		    msg, (const char *) str1, (const char *) str2);
     if (ctxt != NULL) {
 	ctxt->valid = 0;
     }
@@ -607,6 +704,33 @@
 	ctxt->nsWellFormed = 0;
 }
 
+/**
+ * xmlNsWarn
+ * @ctxt:  an XML parser context
+ * @error:  the error number
+ * @msg:  the message
+ * @info1:  extra information string
+ * @info2:  extra information string
+ *
+ * Handle a fatal parser error, i.e. violating Well-Formedness constraints
+ */
+static void
+xmlNsWarn(xmlParserCtxtPtr ctxt, xmlParserErrors error,
+         const char *msg,
+         const xmlChar * info1, const xmlChar * info2,
+         const xmlChar * info3)
+{
+    if ((ctxt != NULL) && (ctxt->disableSAX != 0) &&
+        (ctxt->instate == XML_PARSER_EOF))
+	return;
+    if (ctxt != NULL)
+	ctxt->errNo = error;
+    __xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_NAMESPACE, error,
+                    XML_ERR_WARNING, NULL, 0, (const char *) info1,
+                    (const char *) info2, (const char *) info3, 0, 0, msg,
+                    info1, info2, info3);
+}
+
 /************************************************************************
  *									*
  * 		Library wide options					*
@@ -806,7 +930,7 @@
             return(1);
 #else
             return(0);
-#endif 
+#endif
         case XML_WITH_ZLIB:
 #ifdef LIBXML_ZLIB_ENABLED
             return(1);
@@ -856,10 +980,108 @@
 struct _xmlDefAttrs {
     int nbAttrs;	/* number of defaulted attributes on that element */
     int maxAttrs;       /* the size of the array */
-    const xmlChar *values[4]; /* array of localname/prefix/values */
+    const xmlChar *values[5]; /* array of localname/prefix/values/external */
 };
 
 /**
+ * xmlAttrNormalizeSpace:
+ * @src: the source string
+ * @dst: the target string
+ *
+ * Normalize the space in non CDATA attribute values:
+ * If the attribute type is not CDATA, then the XML processor MUST further
+ * process the normalized attribute value by discarding any leading and
+ * trailing space (#x20) characters, and by replacing sequences of space
+ * (#x20) characters by a single space (#x20) character.
+ * Note that the size of dst need to be at least src, and if one doesn't need
+ * to preserve dst (and it doesn't come from a dictionary or read-only) then
+ * passing src as dst is just fine.
+ *
+ * Returns a pointer to the normalized value (dst) or NULL if no conversion
+ *         is needed.
+ */
+static xmlChar *
+xmlAttrNormalizeSpace(const xmlChar *src, xmlChar *dst)
+{
+    if ((src == NULL) || (dst == NULL))
+        return(NULL);
+
+    while (*src == 0x20) src++;
+    while (*src != 0) {
+	if (*src == 0x20) {
+	    while (*src == 0x20) src++;
+	    if (*src != 0)
+		*dst++ = 0x20;
+	} else {
+	    *dst++ = *src++;
+	}
+    }
+    *dst = 0;
+    if (dst == src)
+       return(NULL);
+    return(dst);
+}
+
+/**
+ * xmlAttrNormalizeSpace2:
+ * @src: the source string
+ *
+ * Normalize the space in non CDATA attribute values, a slightly more complex
+ * front end to avoid allocation problems when running on attribute values
+ * coming from the input.
+ *
+ * Returns a pointer to the normalized value (dst) or NULL if no conversion
+ *         is needed.
+ */
+static const xmlChar *
+xmlAttrNormalizeSpace2(xmlParserCtxtPtr ctxt, xmlChar *src, int *len)
+{
+    int i;
+    int remove_head = 0;
+    int need_realloc = 0;
+    const xmlChar *cur;
+
+    if ((ctxt == NULL) || (src == NULL) || (len == NULL))
+        return(NULL);
+    i = *len;
+    if (i <= 0)
+        return(NULL);
+
+    cur = src;
+    while (*cur == 0x20) {
+        cur++;
+	remove_head++;
+    }
+    while (*cur != 0) {
+	if (*cur == 0x20) {
+	    cur++;
+	    if ((*cur == 0x20) || (*cur == 0)) {
+	        need_realloc = 1;
+		break;
+	    }
+	} else
+	    cur++;
+    }
+    if (need_realloc) {
+        xmlChar *ret;
+
+	ret = xmlStrndup(src + remove_head, i - remove_head + 1);
+	if (ret == NULL) {
+	    xmlErrMemory(ctxt, NULL);
+	    return(NULL);
+	}
+	xmlAttrNormalizeSpace(ret, ret);
+	*len = (int) strlen((const char *)ret);
+        return(ret);
+    } else if (remove_head) {
+        *len -= remove_head;
+        memmove(src, src + remove_head, 1 + *len);
+	return(src);
+    }
+    return(NULL);
+}
+
+/**
  * xmlAddDefAttrs:
  * @ctxt:  an XML parser context
  * @fullname:  the element fullname
@@ -878,6 +1100,14 @@
     const xmlChar *name;
     const xmlChar *prefix;
 
+    /*
+     * Allows to detect attribute redefinitions
+     */
+    if (ctxt->attsSpecial != NULL) {
+        if (xmlHashLookup2(ctxt->attsSpecial, fullname, fullattr) != NULL)
+	    return;
+    }
+
     if (ctxt->attsDefault == NULL) {
         ctxt->attsDefault = xmlHashCreateDict(10, ctxt->dict);
 	if (ctxt->attsDefault == NULL)
@@ -903,22 +1133,30 @@
     defaults = xmlHashLookup2(ctxt->attsDefault, name, prefix);
     if (defaults == NULL) {
         defaults = (xmlDefAttrsPtr) xmlMalloc(sizeof(xmlDefAttrs) +
-	                   (4 * 4) * sizeof(const xmlChar *));
+	                   (4 * 5) * sizeof(const xmlChar *));
 	if (defaults == NULL)
 	    goto mem_error;
 	defaults->nbAttrs = 0;
 	defaults->maxAttrs = 4;
-	xmlHashUpdateEntry2(ctxt->attsDefault, name, prefix, defaults, NULL);
+	if (xmlHashUpdateEntry2(ctxt->attsDefault, name, prefix,
+	                        defaults, NULL) < 0) {
+	    xmlFree(defaults);
+	    goto mem_error;
+	}
     } else if (defaults->nbAttrs >= defaults->maxAttrs) {
         xmlDefAttrsPtr temp;
 
         temp = (xmlDefAttrsPtr) xmlRealloc(defaults, sizeof(xmlDefAttrs) +
-		       (2 * defaults->maxAttrs * 4) * sizeof(const xmlChar *));
+		       (2 * defaults->maxAttrs * 5) * sizeof(const xmlChar *));
 	if (temp == NULL)
 	    goto mem_error;
 	defaults = temp;
 	defaults->maxAttrs *= 2;
-	xmlHashUpdateEntry2(ctxt->attsDefault, name, prefix, defaults, NULL);
+	if (xmlHashUpdateEntry2(ctxt->attsDefault, name, prefix,
+	                        defaults, NULL) < 0) {
+	    xmlFree(defaults);
+	    goto mem_error;
+	}
     }
 
     /*
@@ -934,13 +1172,17 @@
 	prefix = xmlDictLookup(ctxt->dict, fullattr, len);
     }
 
-    defaults->values[4 * defaults->nbAttrs] = name;
-    defaults->values[4 * defaults->nbAttrs + 1] = prefix;
+    defaults->values[5 * defaults->nbAttrs] = name;
+    defaults->values[5 * defaults->nbAttrs + 1] = prefix;
     /* intern the string and precompute the end */
     len = xmlStrlen(value);
     value = xmlDictLookup(ctxt->dict, value, len);
-    defaults->values[4 * defaults->nbAttrs + 2] = value;
-    defaults->values[4 * defaults->nbAttrs + 3] = value + len;
+    defaults->values[5 * defaults->nbAttrs + 2] = value;
+    defaults->values[5 * defaults->nbAttrs + 3] = value + len;
+    if (ctxt->external)
+        defaults->values[5 * defaults->nbAttrs + 4] = BAD_CAST "external";
+    else
+        defaults->values[5 * defaults->nbAttrs + 4] = NULL;
     defaults->nbAttrs++;
 
     return;
@@ -1096,7 +1338,7 @@
 
 /************************************************************************
  *									*
- * 		Parser stacks related functions and macros		*
+ *		Parser stacks related functions and macros		*
  *									*
  ************************************************************************/
 
@@ -1141,15 +1383,16 @@
             return (-1);
 	}
     } else if (ctxt->nsNr >= ctxt->nsMax) {
+        const xmlChar ** tmp;
         ctxt->nsMax *= 2;
-        ctxt->nsTab = (const xmlChar **)
-	              xmlRealloc((char *) ctxt->nsTab,
-				 ctxt->nsMax * sizeof(ctxt->nsTab[0]));
-        if (ctxt->nsTab == NULL) {
+        tmp = (const xmlChar **) xmlRealloc((char *) ctxt->nsTab,
+				    ctxt->nsMax * sizeof(ctxt->nsTab[0]));
+        if (tmp == NULL) {
             xmlErrMemory(ctxt, NULL);
 	    ctxt->nsMax /= 2;
             return (-1);
         }
+	ctxt->nsTab = tmp;
     }
     ctxt->nsTab[ctxt->nsNr++] = prefix;
     ctxt->nsTab[ctxt->nsNr++] = URL;
@@ -1176,7 +1419,7 @@
     }
     if (ctxt->nsNr <= 0)
         return (0);
-    
+
     for (i = 0;i < nr;i++) {
          ctxt->nsNr--;
 	 ctxt->nsTab[ctxt->nsNr] = NULL;
@@ -1226,13 +1469,13 @@
  *
  * Pushes a new parser input on top of the input stack
  *
- * Returns 0 in case of error, the index in the stack otherwise
+ * Returns -1 in case of error, the index in the stack otherwise
  */
 int
 inputPush(xmlParserCtxtPtr ctxt, xmlParserInputPtr value)
 {
     if ((ctxt == NULL) || (value == NULL))
-        return(0);
+        return(-1);
     if (ctxt->inputNr >= ctxt->inputMax) {
         ctxt->inputMax *= 2;
         ctxt->inputTab =
@@ -1241,7 +1484,10 @@
                                              sizeof(ctxt->inputTab[0]));
         if (ctxt->inputTab == NULL) {
             xmlErrMemory(ctxt, NULL);
-            return (0);
+	    xmlFreeInputStream(value);
+	    ctxt->inputMax /= 2;
+	    value = NULL;
+            return (-1);
         }
     }
     ctxt->inputTab[ctxt->inputNr] = value;
@@ -1281,7 +1527,7 @@
  *
  * Pushes a new element node on top of the node stack
  *
- * Returns 0 in case of error, the index in the stack otherwise
+ * Returns -1 in case of error, the index in the stack otherwise
  */
 int
 nodePush(xmlParserCtxtPtr ctxt, xmlNodePtr value)
@@ -1295,22 +1541,24 @@
                                       sizeof(ctxt->nodeTab[0]));
         if (tmp == NULL) {
             xmlErrMemory(ctxt, NULL);
-            return (0);
+            return (-1);
         }
         ctxt->nodeTab = tmp;
 	ctxt->nodeMax *= 2;
     }
-    if (((unsigned int) ctxt->nodeNr) > xmlParserMaxDepth) {
+    if ((((unsigned int) ctxt->nodeNr) > xmlParserMaxDepth) &&
+        ((ctxt->options & XML_PARSE_HUGE) == 0)) {
 	xmlFatalErrMsgInt(ctxt, XML_ERR_INTERNAL_ERROR,
-		 "Excessive depth in document: change xmlParserMaxDepth = %d\n",
+		 "Excessive depth in document: %d use XML_PARSE_HUGE option\n",
 			  xmlParserMaxDepth);
 	ctxt->instate = XML_PARSER_EOF;
-	return(0);
+	return(-1);
     }
     ctxt->nodeTab[ctxt->nodeNr] = value;
     ctxt->node = value;
     return (ctxt->nodeNr++);
 }
+
 /**
  * nodePop:
  * @ctxt: an XML parser context
@@ -1470,13 +1718,17 @@
 
 static int spacePush(xmlParserCtxtPtr ctxt, int val) {
     if (ctxt->spaceNr >= ctxt->spaceMax) {
+        int *tmp;
+
 	ctxt->spaceMax *= 2;
-        ctxt->spaceTab = (int *) xmlRealloc(ctxt->spaceTab,
-	             ctxt->spaceMax * sizeof(ctxt->spaceTab[0]));
-        if (ctxt->spaceTab == NULL) {
+        tmp = (int *) xmlRealloc(ctxt->spaceTab,
+	                         ctxt->spaceMax * sizeof(ctxt->spaceTab[0]));
+        if (tmp == NULL) {
 	    xmlErrMemory(ctxt, NULL);
-	    return(0);
+	    ctxt->spaceMax /=2;
+	    return(-1);
 	}
+	ctxt->spaceTab = tmp;
     }
     ctxt->spaceTab[ctxt->spaceNr] = val;
     ctxt->space = &ctxt->spaceTab[ctxt->spaceNr];
@@ -1722,10 +1974,12 @@
  *
  * xmlPushInput: switch to a new input stream which is stacked on top
  *               of the previous one(s).
+ * Returns -1 in case of error or the index in the input stack
  */
-void
+int
 xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) {
-    if (input == NULL) return;
+    int ret;
+    if (input == NULL) return(-1);
 
     if (xmlParserDebugEntities) {
 	if ((ctxt->input != NULL) && (ctxt->input->filename))
@@ -1735,8 +1989,9 @@
 	xmlGenericError(xmlGenericErrorContext,
 		"Pushing input %d : %.30s\n", ctxt->inputNr+1, input->cur);
     }
-    inputPush(ctxt, input);
+    ret = inputPush(ctxt, input);
     GROW;
+    return(ret);
 }
 
 /**
@@ -1966,6 +2221,7 @@
     buffer = xmlMallocAtomic(length);
     if (buffer == NULL) {
 	xmlErrMemory(ctxt, NULL);
+        xmlFree(input);
     	return(NULL);
     }
     buffer [0] = ' ';
@@ -2113,7 +2369,7 @@
 		    if ((ctxt->validate) && (ctxt->vctxt.error != NULL)) {
 		        xmlValidityError(ctxt, XML_WAR_UNDECLARED_ENTITY,
 			                 "PEReference: %%%s; not found\n",
-				         name);
+				         name, NULL);
 		    } else 
 		        xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
 			              "PEReference: %%%s; not found\n",
@@ -2122,7 +2378,8 @@
 		}
 	    } else if (ctxt->input->free != deallocblankswrapper) {
 		    input = xmlNewBlanksWrapperInputStream(ctxt, entity);
-		    xmlPushInput(ctxt, input);
+		    if (xmlPushInput(ctxt, input) < 0)
+		        return;
 	    } else {
 	        if ((entity->etype == XML_INTERNAL_PARAMETER_ENTITY) ||
 		    (entity->etype == XML_EXTERNAL_PARAMETER_ENTITY)) {
@@ -2135,7 +2392,8 @@
 		     * this is done independently.
 		     */
 		    input = xmlNewEntityInputStream(ctxt, entity);
-		    xmlPushInput(ctxt, input);
+		    if (xmlPushInput(ctxt, input) < 0)
+		        return;
 
 		    /* 
 		     * Get the 4 first bytes and decode the charset
@@ -2178,11 +2436,12 @@
 /*
  * Macro used to grow the current buffer.
  */
-#define growBuffer(buffer) {						\
+#define growBuffer(buffer, n) {						\
     xmlChar *tmp;							\
     buffer##_size *= 2;							\
+    buffer##_size += n;							\
     tmp = (xmlChar *)							\
-    		xmlRealloc(buffer, buffer##_size * sizeof(xmlChar));	\
+		xmlRealloc(buffer, buffer##_size * sizeof(xmlChar));	\
     if (tmp == NULL) goto mem_error;					\
     buffer = tmp;							\
 }
@@ -2213,6 +2472,7 @@
     int buffer_size = 0;
 
     xmlChar *current = NULL;
+    xmlChar *rep = NULL;
     const xmlChar *last;
     xmlEntityPtr ent;
     int c,l;
@@ -2222,7 +2482,9 @@
 	return(NULL);
     last = str + len;
 
-    if (ctxt->depth > 40) {
+    if (((ctxt->depth > 40) &&
+         ((ctxt->options & XML_PARSE_HUGE) == 0)) ||
+	(ctxt->depth > 1024)) {
 	xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
 	return(NULL);
     }
@@ -2252,7 +2514,7 @@
 		COPY_BUF(0,buffer,nbchars,val);
 	    }
 	    if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) {
-	        growBuffer(buffer);
+	        growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
 	    }
 	} else if ((c == '&') && (what & XML_SUBSTITUTE_REF)) {
 	    if (xmlParserDebugEntities)
@@ -2260,34 +2522,41 @@
 			"String decoding Entity Reference: %.30s\n",
 			str);
 	    ent = xmlParseStringEntityRef(ctxt, &str);
+	    if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) ||
+	        (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR))
+	        goto int_error;
+	    if (ent != NULL)
+	        ctxt->nbentities += ent->checked;
 	    if ((ent != NULL) &&
 		(ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) {
 		if (ent->content != NULL) {
 		    COPY_BUF(0,buffer,nbchars,ent->content[0]);
 		    if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) {
-			growBuffer(buffer);
+			growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
 		    }
 		} else {
 		    xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR,
 			    "predefined entity has no content\n");
 		}
 	    } else if ((ent != NULL) && (ent->content != NULL)) {
-		xmlChar *rep;
-
 		ctxt->depth++;
 		rep = xmlStringDecodeEntities(ctxt, ent->content, what,
 			                      0, 0, 0);
 		ctxt->depth--;
+
 		if (rep != NULL) {
 		    current = rep;
 		    while (*current != 0) { /* non input consuming loop */
 			buffer[nbchars++] = *current++;
 			if (nbchars >
 		            buffer_size - XML_PARSER_BUFFER_SIZE) {
-			    growBuffer(buffer);
+			    if (xmlParserEntityCheck(ctxt, nbchars, ent))
+				goto int_error;
+			    growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
 			}
 		    }
 		    xmlFree(rep);
+		    rep = NULL;
 		}
 	    } else if (ent != NULL) {
 		int i = xmlStrlen(ent->name);
@@ -2295,7 +2564,7 @@
 
 		buffer[nbchars++] = '&';
 		if (nbchars > buffer_size - i - XML_PARSER_BUFFER_SIZE) {
-		    growBuffer(buffer);
+		    growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
 		}
 		for (;i > 0;i--)
 		    buffer[nbchars++] = *cur++;
@@ -2306,9 +2575,14 @@
 		xmlGenericError(xmlGenericErrorContext,
 			"String decoding PE Reference: %.30s\n", str);
 	    ent = xmlParseStringPEReference(ctxt, &str);
+	    if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP)
+	        goto int_error;
+	    if (ent != NULL)
+	        ctxt->nbentities += ent->checked;
 	    if (ent != NULL) {
-		xmlChar *rep;
-
+                if (ent->content == NULL) {
+		    xmlLoadEntityContent(ctxt, ent);
+		}
 		ctxt->depth++;
 		rep = xmlStringDecodeEntities(ctxt, ent->content, what,
 			                      0, 0, 0);
@@ -2319,17 +2593,20 @@
 			buffer[nbchars++] = *current++;
 			if (nbchars >
 		            buffer_size - XML_PARSER_BUFFER_SIZE) {
-			    growBuffer(buffer);
+			    if (xmlParserEntityCheck(ctxt, nbchars, ent))
+			        goto int_error;
+			    growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
 			}
 		    }
 		    xmlFree(rep);
+		    rep = NULL;
 		}
 	    }
 	} else {
 	    COPY_BUF(l,buffer,nbchars,c);
 	    str += l;
 	    if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) {
-	      growBuffer(buffer);
+	      growBuffer(buffer, XML_PARSER_BUFFER_SIZE);
 	    }
 	}
 	if (str < last)
@@ -2342,6 +2619,11 @@
 
 mem_error:
     xmlErrMemory(ctxt, NULL);
+int_error:
+    if (rep != NULL)
+        xmlFree(rep);
+    if (buffer != NULL)
+        xmlFree(buffer);
     return(NULL);
 }
 
@@ -2456,7 +2738,7 @@
  * xmlSplitQName:
  * @ctxt:  an XML parser context
  * @name:  an XML parser context
- * @prefix:  a xmlChar ** 
+ * @prefix:  a xmlChar **
  *
  * parse an UTF8 encoded XML qualified name string
  *
@@ -2507,7 +2789,7 @@
 	 * for the processing speed.
 	 */
 	max = len * 2;
-	
+
 	buffer = (xmlChar *) xmlMallocAtomic(max * sizeof(xmlChar));
 	if (buffer == NULL) {
 	    xmlErrMemory(ctxt, NULL);
@@ -2522,7 +2804,7 @@
 		tmp = (xmlChar *) xmlRealloc(buffer,
 						max * sizeof(xmlChar));
 		if (tmp == NULL) {
-		    xmlFree(tmp);
+		    xmlFree(buffer);
 		    xmlErrMemory(ctxt, NULL);
 		    return(NULL);
 		}
@@ -2533,7 +2815,7 @@
 	}
 	buffer[len] = 0;
     }
-    
+
     if ((c == ':') && (*cur == 0)) {
         if (buffer != NULL)
 	    xmlFree(buffer);
@@ -2586,7 +2868,7 @@
 	     * for the processing speed.
 	     */
 	    max = len * 2;
-	    
+
 	    buffer = (xmlChar *) xmlMallocAtomic(max * sizeof(xmlChar));
 	    if (buffer == NULL) {
 	        xmlErrMemory(ctxt, NULL);
@@ -2612,7 +2894,7 @@
 	    }
 	    buffer[len] = 0;
 	}
-	
+
 	if (buffer == NULL)
 	    ret = xmlStrndup(buf, len);
 	else {
@@ -2630,10 +2912,198 @@
  *									*
  ************************************************************************/
 
-static const xmlChar * xmlParseNameComplex(xmlParserCtxtPtr ctxt);
+/************************************************************************
+ *									*
+ *	Routines to parse Name, NCName and NmToken			*
+ *									*
+ ************************************************************************/
+unsigned long nbParseName = 0;
+unsigned long nbParseNmToken = 0;
+unsigned long nbParseNCName = 0;
+unsigned long nbParseNCNameComplex = 0;
+unsigned long nbParseNameComplex = 0;
+unsigned long nbParseStringName = 0;
+/*
+ * The two following functions are related to the change of accepted
+ * characters for Name and NmToken in the Revision 5 of XML-1.0
+ * They correspond to the modified production [4] and the new production [4a]
+ * changes in that revision. Also note that the macros used for the
+ * productions Letter, Digit, CombiningChar and Extender are not needed
+ * anymore.
+ * We still keep compatibility to pre-revision5 parsing semantic if the
+ * new XML_PARSE_OLD10 option is given to the parser.
+ */
+static int
+xmlIsNameStartChar(xmlParserCtxtPtr ctxt, int c) {
+    if ((ctxt->options & XML_PARSE_OLD10) == 0) {
+        /*
+	 * Use the new checks of production [4] [4a] amd [5] of the
+	 * Update 5 of XML-1.0
+	 */
+	if ((c != ' ') && (c != '>') && (c != '/') && /* accelerators */
+	    (((c >= 'a') && (c <= 'z')) ||
+	     ((c >= 'A') && (c <= 'Z')) ||
+	     (c == '_') || (c == ':') ||
+	     ((c >= 0xC0) && (c <= 0xD6)) ||
+	     ((c >= 0xD8) && (c <= 0xF6)) ||
+	     ((c >= 0xF8) && (c <= 0x2FF)) ||
+	     ((c >= 0x370) && (c <= 0x37D)) ||
+	     ((c >= 0x37F) && (c <= 0x1FFF)) ||
+	     ((c >= 0x200C) && (c <= 0x200D)) ||
+	     ((c >= 0x2070) && (c <= 0x218F)) ||
+	     ((c >= 0x2C00) && (c <= 0x2FEF)) ||
+	     ((c >= 0x3001) && (c <= 0xD7FF)) ||
+	     ((c >= 0xF900) && (c <= 0xFDCF)) ||
+	     ((c >= 0xFDF0) && (c <= 0xFFFD)) ||
+	     ((c >= 0x10000) && (c <= 0xEFFFF))))
+	    return(1);
+    } else {
+        if (IS_LETTER(c) || (c == '_') || (c == ':'))
+	    return(1);
+    }
+    return(0);
+}
+
+static int
+xmlIsNameChar(xmlParserCtxtPtr ctxt, int c) {
+    if ((ctxt->options & XML_PARSE_OLD10) == 0) {
+        /*
+	 * Use the new checks of production [4] [4a] amd [5] of the
+	 * Update 5 of XML-1.0
+	 */
+	if ((c != ' ') && (c != '>') && (c != '/') && /* accelerators */
+	    (((c >= 'a') && (c <= 'z')) ||
+	     ((c >= 'A') && (c <= 'Z')) ||
+	     ((c >= '0') && (c <= '9')) || /* !start */
+	     (c == '_') || (c == ':') ||
+	     (c == '-') || (c == '.') || (c == 0xB7) || /* !start */
+	     ((c >= 0xC0) && (c <= 0xD6)) ||
+	     ((c >= 0xD8) && (c <= 0xF6)) ||
+	     ((c >= 0xF8) && (c <= 0x2FF)) ||
+	     ((c >= 0x300) && (c <= 0x36F)) || /* !start */
+	     ((c >= 0x370) && (c <= 0x37D)) ||
+	     ((c >= 0x37F) && (c <= 0x1FFF)) ||
+	     ((c >= 0x200C) && (c <= 0x200D)) ||
+	     ((c >= 0x203F) && (c <= 0x2040)) || /* !start */
+	     ((c >= 0x2070) && (c <= 0x218F)) ||
+	     ((c >= 0x2C00) && (c <= 0x2FEF)) ||
+	     ((c >= 0x3001) && (c <= 0xD7FF)) ||
+	     ((c >= 0xF900) && (c <= 0xFDCF)) ||
+	     ((c >= 0xFDF0) && (c <= 0xFFFD)) ||
+	     ((c >= 0x10000) && (c <= 0xEFFFF))))
+	     return(1);
+    } else {
+        if ((IS_LETTER(c)) || (IS_DIGIT(c)) ||
+            (c == '.') || (c == '-') ||
+	    (c == '_') || (c == ':') || 
+	    (IS_COMBINING(c)) ||
+	    (IS_EXTENDER(c)))
+	    return(1);
+    }
+    return(0);
+}
+
 static xmlChar * xmlParseAttValueInternal(xmlParserCtxtPtr ctxt,
                                           int *len, int *alloc, int normalize);
 
+static const xmlChar *
+xmlParseNameComplex(xmlParserCtxtPtr ctxt) {
+    int len = 0, l;
+    int c;
+    int count = 0;
+
+    nbParseNameComplex++;
+
+    /*
+     * Handler for more complex cases
+     */
+    GROW;
+    c = CUR_CHAR(l);
+    if ((ctxt->options & XML_PARSE_OLD10) == 0) {
+        /*
+	 * Use the new checks of production [4] [4a] amd [5] of the
+	 * Update 5 of XML-1.0
+	 */
+	if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
+	    (!(((c >= 'a') && (c <= 'z')) ||
+	       ((c >= 'A') && (c <= 'Z')) ||
+	       (c == '_') || (c == ':') ||
+	       ((c >= 0xC0) && (c <= 0xD6)) ||
+	       ((c >= 0xD8) && (c <= 0xF6)) ||
+	       ((c >= 0xF8) && (c <= 0x2FF)) ||
+	       ((c >= 0x370) && (c <= 0x37D)) ||
+	       ((c >= 0x37F) && (c <= 0x1FFF)) ||
+	       ((c >= 0x200C) && (c <= 0x200D)) ||
+	       ((c >= 0x2070) && (c <= 0x218F)) ||
+	       ((c >= 0x2C00) && (c <= 0x2FEF)) ||
+	       ((c >= 0x3001) && (c <= 0xD7FF)) ||
+	       ((c >= 0xF900) && (c <= 0xFDCF)) ||
+	       ((c >= 0xFDF0) && (c <= 0xFFFD)) ||
+	       ((c >= 0x10000) && (c <= 0xEFFFF))))) {
+	    return(NULL);
+	}
+	len += l;
+	NEXTL(l);
+	c = CUR_CHAR(l);
+	while ((c != ' ') && (c != '>') && (c != '/') && /* accelerators */
+	       (((c >= 'a') && (c <= 'z')) ||
+	        ((c >= 'A') && (c <= 'Z')) ||
+	        ((c >= '0') && (c <= '9')) || /* !start */
+	        (c == '_') || (c == ':') ||
+	        (c == '-') || (c == '.') || (c == 0xB7) || /* !start */
+	        ((c >= 0xC0) && (c <= 0xD6)) ||
+	        ((c >= 0xD8) && (c <= 0xF6)) ||
+	        ((c >= 0xF8) && (c <= 0x2FF)) ||
+	        ((c >= 0x300) && (c <= 0x36F)) || /* !start */
+	        ((c >= 0x370) && (c <= 0x37D)) ||
+	        ((c >= 0x37F) && (c <= 0x1FFF)) ||
+	        ((c >= 0x200C) && (c <= 0x200D)) ||
+	        ((c >= 0x203F) && (c <= 0x2040)) || /* !start */
+	        ((c >= 0x2070) && (c <= 0x218F)) ||
+	        ((c >= 0x2C00) && (c <= 0x2FEF)) ||
+	        ((c >= 0x3001) && (c <= 0xD7FF)) ||
+	        ((c >= 0xF900) && (c <= 0xFDCF)) ||
+	        ((c >= 0xFDF0) && (c <= 0xFFFD)) ||
+	        ((c >= 0x10000) && (c <= 0xEFFFF))
+		)) {
+	    if (count++ > 100) {
+		count = 0;
+		GROW;
+	    }
+	    len += l;
+	    NEXTL(l);
+	    c = CUR_CHAR(l);
+	}
+    } else {
+	if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
+	    (!IS_LETTER(c) && (c != '_') &&
+	     (c != ':'))) {
+	    return(NULL);
+	}
+	len += l;
+	NEXTL(l);
+	c = CUR_CHAR(l);
+
+	while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
+	       ((IS_LETTER(c)) || (IS_DIGIT(c)) ||
+		(c == '.') || (c == '-') ||
+		(c == '_') || (c == ':') || 
+		(IS_COMBINING(c)) ||
+		(IS_EXTENDER(c)))) {
+	    if (count++ > 100) {
+		count = 0;
+		GROW;
+	    }
+	    len += l;
+	    NEXTL(l);
+	    c = CUR_CHAR(l);
+	}
+    }
+    if ((*ctxt->input->cur == '\n') && (ctxt->input->cur[-1] == '\r'))
+        return(xmlDictLookup(ctxt->dict, ctxt->input->cur - (len + 1), len));
+    return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len));
+}
+
 /**
  * xmlParseName:
  * @ctxt:  an XML parser context
@@ -2658,6 +3128,8 @@
 
     GROW;
 
+    nbParseName++;
+
     /*
      * Accelerator for simple ASCII names
      */
@@ -2683,9 +3155,93 @@
 	    return(ret);
 	}
     }
+    /* accelerator for special cases */
     return(xmlParseNameComplex(ctxt));
 }
 
+static const xmlChar *
+xmlParseNCNameComplex(xmlParserCtxtPtr ctxt) {
+    int len = 0, l;
+    int c;
+    int count = 0;
+
+    nbParseNCNameComplex++;
+
+    /*
+     * Handler for more complex cases
+     */
+    GROW;
+    c = CUR_CHAR(l);
+    if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
+	(!xmlIsNameStartChar(ctxt, c) || (c == ':'))) {
+	return(NULL);
+    }
+
+    while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
+	   (xmlIsNameChar(ctxt, c) && (c != ':'))) {
+	if (count++ > 100) {
+	    count = 0;
+	    GROW;
+	}
+	len += l;
+	NEXTL(l);
+	c = CUR_CHAR(l);
+    }
+    return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len));
+}
+
+/**
+ * xmlParseNCName:
+ * @ctxt:  an XML parser context
+ * @len:  lenght of the string parsed
+ *
+ * parse an XML name.
+ *
+ * [4NS] NCNameChar ::= Letter | Digit | '.' | '-' | '_' |
+ *                      CombiningChar | Extender
+ *
+ * [5NS] NCName ::= (Letter | '_') (NCNameChar)*
+ *
+ * Returns the Name parsed or NULL
+ */
+
+static const xmlChar *
+xmlParseNCName(xmlParserCtxtPtr ctxt) {
+    const xmlChar *in;
+    const xmlChar *ret;
+    int count = 0;
+
+    nbParseNCName++;
+
+    /*
+     * Accelerator for simple ASCII names
+     */
+    in = ctxt->input->cur;
+    if (((*in >= 0x61) && (*in <= 0x7A)) ||
+	((*in >= 0x41) && (*in <= 0x5A)) ||
+	(*in == '_')) {
+	in++;
+	while (((*in >= 0x61) && (*in <= 0x7A)) ||
+	       ((*in >= 0x41) && (*in <= 0x5A)) ||
+	       ((*in >= 0x30) && (*in <= 0x39)) ||
+	       (*in == '_') || (*in == '-') ||
+	       (*in == '.'))
+	    in++;
+	if ((*in > 0) && (*in < 0x80)) {
+	    count = in - ctxt->input->cur;
+	    ret = xmlDictLookup(ctxt->dict, ctxt->input->cur, count);
+	    ctxt->input->cur = in;
+	    ctxt->nbChars += count;
+	    ctxt->input->col += count;
+	    if (ret == NULL) {
+	        xmlErrMemory(ctxt, NULL);
+	    }
+	    return(ret);
+	}
+    }
+    return(xmlParseNCNameComplex(ctxt));
+}
+
 /**
  * xmlParseNameAndCompare:
  * @ctxt:  an XML parser context
@@ -2704,15 +3260,15 @@
     const xmlChar *ret;
 
     GROW;
-    
+
     in = ctxt->input->cur;
     while (*in != 0 && *in == *cmp) {
-    	++in;
+	++in;
 	++cmp;
 	ctxt->input->col++;
     }
     if (*cmp == 0 && (*in == '>' || IS_BLANK_CH (*in))) {
-    	/* success */
+	/* success */
 	ctxt->input->cur = in;
 	return (const xmlChar*) 1;
     }
@@ -2725,42 +3281,6 @@
     return ret;
 }
 
-static const xmlChar *
-xmlParseNameComplex(xmlParserCtxtPtr ctxt) {
-    int len = 0, l;
-    int c;
-    int count = 0;
-
-    /*
-     * Handler for more complex cases
-     */
-    GROW;
-    c = CUR_CHAR(l);
-    if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
-	(!IS_LETTER(c) && (c != '_') &&
-         (c != ':'))) {
-	return(NULL);
-    }
-
-    while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
-	   ((IS_LETTER(c)) || (IS_DIGIT(c)) ||
-            (c == '.') || (c == '-') ||
-	    (c == '_') || (c == ':') || 
-	    (IS_COMBINING(c)) ||
-	    (IS_EXTENDER(c)))) {
-	if (count++ > 100) {
-	    count = 0;
-	    GROW;
-	}
-	len += l;
-	NEXTL(l);
-	c = CUR_CHAR(l);
-    }
-    if ((*ctxt->input->cur == '\n') && (ctxt->input->cur[-1] == '\r'))
-        return(xmlDictLookup(ctxt->dict, ctxt->input->cur - (len + 1), len));
-    return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len));
-}
-
 /**
  * xmlParseStringName:
  * @ctxt:  an XML parser context
@@ -2786,17 +3306,17 @@
     int len = 0, l;
     int c;
 
+    nbParseStringName++;
+
     c = CUR_SCHAR(cur, l);
-    if (!IS_LETTER(c) && (c != '_') &&
-        (c != ':')) {
+    if (!xmlIsNameStartChar(ctxt, c)) {
 	return(NULL);
     }
 
-    while ((IS_LETTER(c)) || (IS_DIGIT(c)) || /* test bigentname.xml */
-           (c == '.') || (c == '-') ||
-	   (c == '_') || (c == ':') || 
-	   (IS_COMBINING(c)) ||
-	   (IS_EXTENDER(c))) {
+    COPY_BUF(l,buf,len,c);
+    cur += l;
+    c = CUR_SCHAR(cur, l);
+    while (xmlIsNameChar(ctxt, c)) {
 	COPY_BUF(l,buf,len,c);
 	cur += l;
 	c = CUR_SCHAR(cur, l);
@@ -2807,19 +3327,14 @@
 	     */
 	    xmlChar *buffer;
 	    int max = len * 2;
-	    
+
 	    buffer = (xmlChar *) xmlMallocAtomic(max * sizeof(xmlChar));
 	    if (buffer == NULL) {
 	        xmlErrMemory(ctxt, NULL);
 		return(NULL);
 	    }
 	    memcpy(buffer, buf, len);
-	    while ((IS_LETTER(c)) || (IS_DIGIT(c)) ||
-	             /* test bigentname.xml */
-		   (c == '.') || (c == '-') ||
-		   (c == '_') || (c == ':') || 
-		   (IS_COMBINING(c)) ||
-		   (IS_EXTENDER(c))) {
+	    while (xmlIsNameChar(ctxt, c)) {
 		if (len + 10 > max) {
 		    xmlChar *tmp;
 		    max *= 2;
@@ -2848,7 +3363,7 @@
 /**
  * xmlParseNmtoken:
  * @ctxt:  an XML parser context
- * 
+ *
  * parse an XML Nmtoken.
  *
  * [7] Nmtoken ::= (NameChar)+
@@ -2865,14 +3380,12 @@
     int c;
     int count = 0;
 
+    nbParseNmToken++;
+
     GROW;
     c = CUR_CHAR(l);
 
-    while ((IS_LETTER(c)) || (IS_DIGIT(c)) || /* test bigtoken.xml */
-           (c == '.') || (c == '-') ||
-	   (c == '_') || (c == ':') || 
-	   (IS_COMBINING(c)) ||
-	   (IS_EXTENDER(c))) {
+    while (xmlIsNameChar(ctxt, c)) {
 	if (count++ > 100) {
 	    count = 0;
 	    GROW;
@@ -2887,18 +3400,14 @@
 	     */
 	    xmlChar *buffer;
 	    int max = len * 2;
-	    
+
 	    buffer = (xmlChar *) xmlMallocAtomic(max * sizeof(xmlChar));
 	    if (buffer == NULL) {
 	        xmlErrMemory(ctxt, NULL);
 		return(NULL);
 	    }
 	    memcpy(buffer, buf, len);
-	    while ((IS_LETTER(c)) || (IS_DIGIT(c)) || /* test bigtoken.xml */
-		   (c == '.') || (c == '-') ||
-		   (c == '_') || (c == ':') || 
-		   (IS_COMBINING(c)) ||
-		   (IS_EXTENDER(c))) {
+	    while (xmlIsNameChar(ctxt, c)) {
 		if (count++ > 100) {
 		    count = 0;
 		    GROW;
@@ -3085,6 +3594,7 @@
 xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) {
     xmlChar limit = 0;
     xmlChar *buf = NULL;
+    xmlChar *rep = NULL;
     int len = 0;
     int buf_size = 0;
     int c, l, in_space = 0;
@@ -3103,7 +3613,7 @@
 	xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL);
 	return(NULL);
     }
-    
+
     /*
      * allocate a translation buffer.
      */
@@ -3126,7 +3636,7 @@
 		if (val == '&') {
 		    if (ctxt->replaceEntities) {
 			if (len > buf_size - 10) {
-			    growBuffer(buf);
+			    growBuffer(buf, 10);
 			}
 			buf[len++] = '&';
 		    } else {
@@ -3135,7 +3645,7 @@
 			 * called by the attribute() function in SAX.c
 			 */
 			if (len > buf_size - 10) {
-			    growBuffer(buf);
+			    growBuffer(buf, 10);
 			}
 			buf[len++] = '&';
 			buf[len++] = '#';
@@ -3143,18 +3653,21 @@
 			buf[len++] = '8';
 			buf[len++] = ';';
 		    }
-		} else {
+		} else if (val != 0) {
 		    if (len > buf_size - 10) {
-			growBuffer(buf);
+			growBuffer(buf, 10);
 		    }
 		    len += xmlCopyChar(0, &buf[len], val);
 		}
 	    } else {
 		ent = xmlParseEntityRef(ctxt);
+		ctxt->nbentities++;
+		if (ent != NULL)
+		    ctxt->nbentities += ent->owner;
 		if ((ent != NULL) &&
 		    (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) {
 		    if (len > buf_size - 10) {
-			growBuffer(buf);
+			growBuffer(buf, 10);
 		    }
 		    if ((ctxt->replaceEntities == 0) &&
 		        (ent->content[0] == '&')) {
@@ -3168,8 +3681,6 @@
 		    }
 		} else if ((ent != NULL) && 
 		           (ctxt->replaceEntities != 0)) {
-		    xmlChar *rep;
-
 		    if (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) {
 			rep = xmlStringDecodeEntities(ctxt, ent->content,
 						      XML_SUBSTITUTE_REF,
@@ -3179,14 +3690,15 @@
 			    while (*current != 0) { /* non input consuming */
 				buf[len++] = *current++;
 				if (len > buf_size - 10) {
-				    growBuffer(buf);
+				    growBuffer(buf, 10);
 				}
 			    }
 			    xmlFree(rep);
+			    rep = NULL;
 			}
 		    } else {
 			if (len > buf_size - 10) {
-			    growBuffer(buf);
+			    growBuffer(buf, 10);
 			}
 			if (ent->content != NULL)
 			    buf[len++] = ent->content[0];
@@ -3201,19 +3713,20 @@
 		     */
 		    if ((ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) &&
 			(ent->content != NULL)) {
-			xmlChar *rep;
 			rep = xmlStringDecodeEntities(ctxt, ent->content,
-						      XML_SUBSTITUTE_REF, 0, 0, 0);
-			if (rep != NULL)
+						  XML_SUBSTITUTE_REF, 0, 0, 0);
+			if (rep != NULL) {
 			    xmlFree(rep);
+			    rep = NULL;
+			}
 		    }
 
 		    /*
 		     * Just output the reference
 		     */
 		    buf[len++] = '&';
-		    if (len > buf_size - i - 10) {
-			growBuffer(buf);
+		    while (len > buf_size - i - 10) {
+			growBuffer(buf, i + 10);
 		    }
 		    for (;i > 0;i--)
 			buf[len++] = *cur++;
@@ -3225,8 +3738,8 @@
 	        if ((len != 0) || (!normalize)) {
 		    if ((!normalize) || (!in_space)) {
 			COPY_BUF(l,buf,len,0x20);
-			if (len > buf_size - 10) {
-			    growBuffer(buf);
+			while (len > buf_size - 10) {
+			    growBuffer(buf, 10);
 			}
 		    }
 		    in_space = 1;
@@ -3235,7 +3748,7 @@
 	        in_space = 0;
 		COPY_BUF(l,buf,len,c);
 		if (len > buf_size - 10) {
-		    growBuffer(buf);
+		    growBuffer(buf, 10);
 		}
 	    }
 	    NEXTL(l);
@@ -3264,6 +3777,10 @@
 
 mem_error:
     xmlErrMemory(ctxt, NULL);
+    if (buf != NULL)
+        xmlFree(buf);
+    if (rep != NULL)
+        xmlFree(rep);
     return(NULL);
 }
 
@@ -3625,6 +4142,9 @@
                     line = ctxt->input->line;
                     col = ctxt->input->col;
 		}
+                /* something really bad happened in the SAX callback */
+                if (ctxt->instate != XML_PARSER_CONTENT)
+                    return;
 	    }
 	    ctxt->input->cur = in;
 	    if (*in == 0xD) {
@@ -3705,6 +4225,9 @@
 		}
 	    }
 	    nbchar = 0;
+            /* something really bad happened in the SAX callback */
+            if (ctxt->instate != XML_PARSER_CONTENT)
+                return;
 	}
 	count++;
 	if (count > 50) {
@@ -3843,8 +4366,10 @@
     int q, ql;
     int r, rl;
     int cur, l;
-    xmlParserInputPtr input = ctxt->input;
     int count = 0;
+    int inputid;
+
+    inputid = ctxt->input->id;
 
     if (buf == NULL) {
         len = 0;
@@ -3926,7 +4451,7 @@
                           "xmlParseComment: invalid xmlChar value %d\n",
 	                  cur);
     } else {
-	if (input != ctxt->input) {
+	if (inputid != ctxt->input->id) {
 	    xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
 		"Comment doesn't start and stop in the same entity\n");
 	}
@@ -3962,15 +4487,16 @@
     xmlParserInputState state;
     const xmlChar *in;
     int nbchar = 0, ccol;
+    int inputid;
 
     /*
      * Check that there is a comment right here.
      */
     if ((RAW != '<') || (NXT(1) != '!') ||
         (NXT(2) != '-') || (NXT(3) != '-')) return;
-
     state = ctxt->instate;
     ctxt->instate = XML_PARSER_COMMENT;
+    inputid = ctxt->input->id;
     SKIP(4);
     SHRINK;
     GROW;
@@ -4061,6 +4587,10 @@
 	if (*in == '-') {
 	    if (in[1] == '-') {
 	        if (in[2] == '>') {
+		    if (ctxt->input->id != inputid) {
+			xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
+			"comment doesn't start and stop in the same entity\n");
+		    }
 		    SKIP(3);
 		    if ((ctxt->sax != NULL) && (ctxt->sax->comment != NULL) &&
 		        (!ctxt->disableSAX)) {
@@ -4134,6 +4664,10 @@
 		      "xmlParsePITarget: invalid name prefix 'xml'\n",
 		      NULL, NULL);
     }
+    if ((name != NULL) && (xmlStrchr(name, ':') != NULL)) {
+	xmlNsErr(ctxt, XML_NS_ERR_COLON, 
+		 "colon are forbidden from PI names '%s'\n", name, NULL, NULL);
+    }
     return(name);
 }
 
@@ -4377,6 +4911,11 @@
 		     "Space required after the NOTATION name'\n");
 	    return;
 	}
+	if (xmlStrchr(name, ':') != NULL) {
+	    xmlNsErr(ctxt, XML_NS_ERR_COLON, 
+		     "colon are forbidden from notation names '%s'\n",
+		     name, NULL, NULL);
+	}
 	SKIP_BLANKS;
 
 	/*
@@ -4461,6 +5000,11 @@
 	                   "xmlParseEntityDecl: no name\n");
             return;
 	}
+	if (xmlStrchr(name, ':') != NULL) {
+	    xmlNsErr(ctxt, XML_NS_ERR_COLON, 
+		     "colon are forbidden from entities names '%s'\n",
+		     name, NULL, NULL);
+	}
         skipped = SKIP_BLANKS;
 	if (skipped == 0) {
 	    xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
@@ -4532,6 +5076,11 @@
 		    (xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE))) {
 		    if (ctxt->myDoc == NULL) {
 			ctxt->myDoc = xmlNewDoc(SAX_COMPAT_MODE);
+			if (ctxt->myDoc == NULL) {
+			    xmlErrMemory(ctxt, "New Doc failed");
+			    return;
+			}
+			ctxt->myDoc->properties = XML_DOC_INTERNAL;
 		    }
 		    if (ctxt->myDoc->intSubset == NULL)
 			ctxt->myDoc->intSubset = xmlNewDtd(ctxt->myDoc,
@@ -4600,6 +5149,11 @@
 			(xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE)))) {
 			if (ctxt->myDoc == NULL) {
 			    ctxt->myDoc = xmlNewDoc(SAX_COMPAT_MODE);
+			    if (ctxt->myDoc == NULL) {
+			        xmlErrMemory(ctxt, "New Doc failed");
+				return;
+			    }
+			    ctxt->myDoc->properties = XML_DOC_INTERNAL;
 			}
 
 			if (ctxt->myDoc->intSubset == NULL)
@@ -4738,7 +5292,7 @@
 xmlEnumerationPtr
 xmlParseNotationType(xmlParserCtxtPtr ctxt) {
     const xmlChar *name;
-    xmlEnumerationPtr ret = NULL, last = NULL, cur;
+    xmlEnumerationPtr ret = NULL, last = NULL, cur, tmp;
 
     if (RAW != '(') {
 	xmlFatalErr(ctxt, XML_ERR_NOTATION_NOT_STARTED, NULL);
@@ -4754,12 +5308,26 @@
 			   "Name expected in NOTATION declaration\n");
 	    return(ret);
 	}
-	cur = xmlCreateEnumeration(name);
-	if (cur == NULL) return(ret);
-	if (last == NULL) ret = last = cur;
-	else {
-	    last->next = cur;
-	    last = cur;
+	tmp = ret;
+	while (tmp != NULL) {
+	    if (xmlStrEqual(name, tmp->name)) {
+		xmlValidityError(ctxt, XML_DTD_DUP_TOKEN,
+	  "standalone: attribute notation value token %s duplicated\n",
+				 name, NULL);
+		if (!xmlDictOwns(ctxt->dict, name))
+		    xmlFree((xmlChar *) name);
+		break;
+	    }
+	    tmp = tmp->next;
+	}
+	if (tmp == NULL) {
+	    cur = xmlCreateEnumeration(name);
+	    if (cur == NULL) return(ret);
+	    if (last == NULL) ret = last = cur;
+	    else {
+		last->next = cur;
+		last = cur;
+	    }
 	}
 	SKIP_BLANKS;
     } while (RAW == '|');
@@ -4791,7 +5359,7 @@
 xmlEnumerationPtr
 xmlParseEnumerationType(xmlParserCtxtPtr ctxt) {
     xmlChar *name;
-    xmlEnumerationPtr ret = NULL, last = NULL, cur;
+    xmlEnumerationPtr ret = NULL, last = NULL, cur, tmp;
 
     if (RAW != '(') {
 	xmlFatalErr(ctxt, XML_ERR_ATTLIST_NOT_STARTED, NULL);
@@ -4806,13 +5374,28 @@
 	    xmlFatalErr(ctxt, XML_ERR_NMTOKEN_REQUIRED, NULL);
 	    return(ret);
 	}
-	cur = xmlCreateEnumeration(name);
-	xmlFree(name);
-	if (cur == NULL) return(ret);
-	if (last == NULL) ret = last = cur;
-	else {
-	    last->next = cur;
-	    last = cur;
+	tmp = ret;
+	while (tmp != NULL) {
+	    if (xmlStrEqual(name, tmp->name)) {
+		xmlValidityError(ctxt, XML_DTD_DUP_TOKEN,
+	  "standalone: attribute enumeration value token %s duplicated\n",
+				 name, NULL);
+		if (!xmlDictOwns(ctxt->dict, name))
+		    xmlFree(name);
+		break;
+	    }
+	    tmp = tmp->next;
+	}
+	if (tmp == NULL) {
+	    cur = xmlCreateEnumeration(name);
+	    if (!xmlDictOwns(ctxt->dict, name))
+		xmlFree(name);
+	    if (cur == NULL) return(ret);
+	    if (last == NULL) ret = last = cur;
+	    else {
+		last->next = cur;
+		last = cur;
+	    }
 	}
 	SKIP_BLANKS;
     } while (RAW == '|');
@@ -5013,6 +5596,8 @@
 		    xmlFreeEnumeration(tree);
 	        break;
 	    }
+	    if ((type != XML_ATTRIBUTE_CDATA) && (defaultValue != NULL))
+	        xmlAttrNormalizeSpace(defaultValue, defaultValue);
 
 	    GROW;
             if (RAW != '>') {
@@ -5057,8 +5642,9 @@
 	}
 	if (RAW == '>') {
 	    if (input != ctxt->input) {
-		xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
-    "Attribute list declaration doesn't start and stop in the same entity\n");
+		xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
+    "Attribute list declaration doesn't start and stop in the same entity\n",
+                                 NULL, NULL);
 	    }
 	    NEXT;
 	}
@@ -5098,10 +5684,12 @@
 	    if ((ctxt->validate) && (ctxt->input->id != inputchk)) {
 		xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
 "Element content declaration doesn't start and stop in the same entity\n",
-                                 NULL);
+                                 NULL, NULL);
 	    }
 	    NEXT;
 	    ret = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_PCDATA);
+	    if (ret == NULL)
+	        return(NULL);
 	    if (RAW == '*') {
 		ret->ocur = XML_ELEMENT_CONTENT_MULT;
 		NEXT;
@@ -5154,7 +5742,7 @@
 	    if ((ctxt->validate) && (ctxt->input->id != inputchk)) {
 		xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
 "Element content declaration doesn't start and stop in the same entity\n",
-				 NULL);
+				 NULL, NULL);
 	    }
 	    SKIP(2);
 	} else {
@@ -5332,6 +5920,8 @@
 	    }
 	} else {
 	    xmlFatalErr(ctxt, XML_ERR_ELEMCONTENT_NOT_FINISHED, NULL);
+	    if ((last != NULL) && (last != ret))
+	        xmlFreeDocElementContent(ctxt->myDoc, last);
 	    if (ret != NULL)
 		xmlFreeDocElementContent(ctxt->myDoc, ret);
 	    return(NULL);
@@ -5355,6 +5945,11 @@
 		return(NULL);
 	    }
 	    last = xmlNewDocElementContent(ctxt->myDoc, elem, XML_ELEMENT_CONTENT_ELEMENT);
+	    if (last == NULL) {
+		if (ret != NULL)
+		    xmlFreeDocElementContent(ctxt->myDoc, ret);
+		return(NULL);
+	    }
 	    if (RAW == '?') {
 		last->ocur = XML_ELEMENT_CONTENT_OPT;
 		NEXT;
@@ -5379,7 +5974,7 @@
     if ((ctxt->validate) && (ctxt->input->id != inputchk)) {
 	xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
 "Element content declaration doesn't start and stop in the same entity\n",
-			 NULL);
+			 NULL, NULL);
     }
     NEXT;
     if (RAW == '?') {
@@ -5621,6 +6216,8 @@
 
 static void
 xmlParseConditionalSections(xmlParserCtxtPtr ctxt) {
+    int id = ctxt->input->id;
+
     SKIP(3);
     SKIP_BLANKS;
     if (CMP7(CUR_PTR, 'I', 'N', 'C', 'L', 'U', 'D', 'E')) {
@@ -5629,6 +6226,11 @@
 	if (RAW != '[') {
 	    xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL);
 	} else {
+	    if (ctxt->input->id != id) {
+		xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
+	    "All markup of the conditional section is not in the same entity\n",
+				     NULL, NULL);
+	    }
 	    NEXT;
 	}
 	if (xmlParserDebugEntities) {
@@ -5684,6 +6286,11 @@
 	if (RAW != '[') {
 	    xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL);
 	} else {
+	    if (ctxt->input->id != id) {
+		xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
+	    "All markup of the conditional section is not in the same entity\n",
+				     NULL, NULL);
+	    }
 	    NEXT;
 	}
 	if (xmlParserDebugEntities) {
@@ -5740,6 +6347,11 @@
     if (RAW == 0) {
 	xmlFatalErr(ctxt, XML_ERR_CONDSEC_NOT_FINISHED, NULL);
     } else {
+	if (ctxt->input->id != id) {
+	    xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY,
+	"All markup of the conditional section is not in the same entity\n",
+				 NULL, NULL);
+	}
         SKIP(3);
     }
 }
@@ -5818,12 +6430,10 @@
 /**
  * xmlParseTextDecl:
  * @ctxt:  an XML parser context
- * 
+ *
  * parse an XML declaration header for external entities
  *
  * [77] TextDecl ::= '<?xml' VersionInfo? EncodingDecl S? '?>'
- *
- * Question: Seems that EncodingDecl is mandatory ? Is that a typo ?
  */
 
 void
@@ -5907,6 +6517,21 @@
                        const xmlChar *SystemID) {
     xmlDetectSAX2(ctxt);
     GROW;
+
+    if ((ctxt->encoding == (const xmlChar *)XML_CHAR_ENCODING_NONE) &&
+        (ctxt->input->end - ctxt->input->cur >= 4)) {
+        xmlChar start[4];
+	xmlCharEncoding enc;
+
+	start[0] = RAW;
+	start[1] = NXT(1);
+	start[2] = NXT(2);
+	start[3] = NXT(3);
+	enc = xmlDetectCharEncoding(start, 4);
+	if (enc != XML_CHAR_ENCODING_NONE)
+	    xmlSwitchEncoding(ctxt, enc);
+    }
+
     if (CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) {
 	xmlParseTextDecl(ctxt);
 	if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) {
@@ -5919,6 +6544,11 @@
     }
     if (ctxt->myDoc == NULL) {
         ctxt->myDoc = xmlNewDoc(BAD_CAST "1.0");
+	if (ctxt->myDoc == NULL) {
+	    xmlErrMemory(ctxt, "New Doc failed");
+	    return;
+	}
+	ctxt->myDoc->properties = XML_DOC_INTERNAL;
     }
     if ((ctxt->myDoc != NULL) && (ctxt->myDoc->intSubset == NULL))
         xmlCreateIntSubset(ctxt->myDoc, NULL, ExternalID, SystemID);
@@ -5962,7 +6592,7 @@
 /**
  * xmlParseReference:
  * @ctxt:  an XML parser context
- * 
+ *
  * parse and handle entity references in content, depending on the SAX
  * interface, this may end-up in a call to character() if this is a
  * CharRef, a predefined entity, if there is no reference() callback.
@@ -5974,14 +6604,25 @@
 xmlParseReference(xmlParserCtxtPtr ctxt) {
     xmlEntityPtr ent;
     xmlChar *val;
-    if (RAW != '&') return;
+    int was_checked;
+    xmlNodePtr list = NULL;
+    xmlParserErrors ret = XML_ERR_OK;
 
+
+    if (RAW != '&')
+        return;
+
+    /*
+     * Simple case of a CharRef
+     */
     if (NXT(1) == '#') {
 	int i = 0;
 	xmlChar out[10];
 	int hex = NXT(2);
 	int value = xmlParseCharRef(ctxt);
-	
+
+	if (value == 0)
+	    return;
 	if (ctxt->charset != XML_CHAR_ENCODING_UTF8) {
 	    /*
 	     * So we are using non-UTF-8 buffers
@@ -6013,360 +6654,342 @@
 		(!ctxt->disableSAX))
 		ctxt->sax->characters(ctxt->userData, out, i);
 	}
-    } else {
-        int was_checked;
+	return;
+    }
 
-	ent = xmlParseEntityRef(ctxt);
-	if (ent == NULL) return;
-	if (!ctxt->wellFormed)
+    /*
+     * We are seeing an entity reference
+     */
+    ent = xmlParseEntityRef(ctxt);
+    if (ent == NULL) return;
+    if (!ctxt->wellFormed)
+	return;
+    was_checked = ent->checked;
+
+    /* special case of predefined entities */
+    if ((ent->name == NULL) ||
+        (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) {
+	val = ent->content;
+	if (val == NULL) return;
+	/*
+	 * inline the entity.
+	 */
+	if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL) &&
+	    (!ctxt->disableSAX))
+	    ctxt->sax->characters(ctxt->userData, val, xmlStrlen(val));
+	return;
+    }
+
+    /*
+     * The first reference to the entity trigger a parsing phase
+     * where the ent->children is filled with the result from
+     * the parsing.
+     */
+    if (ent->checked == 0) {
+	unsigned long oldnbent = ctxt->nbentities;
+
+	/*
+	 * This is a bit hackish but this seems the best
+	 * way to make sure both SAX and DOM entity support
+	 * behaves okay.
+	 */
+	void *user_data;
+	if (ctxt->userData == ctxt)
+	    user_data = NULL;
+	else
+	    user_data = ctxt->userData;
+
+	/*
+	 * Check that this entity is well formed
+	 * 4.3.2: An internal general parsed entity is well-formed
+	 * if its replacement text matches the production labeled
+	 * content.
+	 */
+	if (ent->etype == XML_INTERNAL_GENERAL_ENTITY) {
+	    ctxt->depth++;
+	    ret = xmlParseBalancedChunkMemoryInternal(ctxt, ent->content,
+	                                              user_data, &list);
+	    ctxt->depth--;
+
+	} else if (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY) {
+	    ctxt->depth++;
+	    ret = xmlParseExternalEntityPrivate(ctxt->myDoc, ctxt, ctxt->sax,
+	                                   user_data, ctxt->depth, ent->URI,
+					   ent->ExternalID, &list);
+	    ctxt->depth--;
+	} else {
+	    ret = XML_ERR_ENTITY_PE_INTERNAL;
+	    xmlErrMsgStr(ctxt, XML_ERR_INTERNAL_ERROR,
+			 "invalid entity type found\n", NULL);
+	}
+
+	/*
+	 * Store the number of entities needing parsing for this entity
+	 * content and do checkings
+	 */
+	ent->checked = ctxt->nbentities - oldnbent;
+	if (ret == XML_ERR_ENTITY_LOOP) {
+	    xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
+	    xmlFreeNodeList(list);
 	    return;
-	was_checked = ent->checked;
-	if ((ent->name != NULL) && 
-	    (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY)) {
-	    xmlNodePtr list = NULL;
-	    xmlParserErrors ret = XML_ERR_OK;
+	}
+	if (xmlParserEntityCheck(ctxt, 0, ent)) {
+	    xmlFreeNodeList(list);
+	    return;
+	}
 
-
-	    /*
-	     * The first reference to the entity trigger a parsing phase
-	     * where the ent->children is filled with the result from
-	     * the parsing.
-	     */
-	    if (ent->checked == 0) {
-		xmlChar *value;
-
-		value = ent->content;
-
-		/*
-		 * Check that this entity is well formed
-		 */
-		if ((value != NULL) && (value[0] != 0) &&
-		    (value[1] == 0) && (value[0] == '<') &&
-		    (xmlStrEqual(ent->name, BAD_CAST "lt"))) {
+	if ((ret == XML_ERR_OK) && (list != NULL)) {
+	    if (((ent->etype == XML_INTERNAL_GENERAL_ENTITY) ||
+	     (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY))&&
+		(ent->children == NULL)) {
+		ent->children = list;
+		if (ctxt->replaceEntities) {
 		    /*
-		     * DONE: get definite answer on this !!!
-		     * Lots of entity decls are used to declare a single
-		     * char 
-		     *    <!ENTITY lt     "<">
-		     * Which seems to be valid since
-		     * 2.4: The ampersand character (&) and the left angle
-		     * bracket (<) may appear in their literal form only
-		     * when used ... They are also legal within the literal
-		     * entity value of an internal entity declaration;i
-		     * see "4.3.2 Well-Formed Parsed Entities". 
-		     * IMHO 2.4 and 4.3.2 are directly in contradiction.
-		     * Looking at the OASIS test suite and James Clark 
-		     * tests, this is broken. However the XML REC uses
-		     * it. Is the XML REC not well-formed ????
-		     * This is a hack to avoid this problem
-		     *
-		     * ANSWER: since lt gt amp .. are already defined,
-		     *   this is a redefinition and hence the fact that the
-		     *   content is not well balanced is not a Wf error, this
-		     *   is lousy but acceptable.
+		     * Prune it directly in the generated document
+		     * except for single text nodes.
 		     */
-		    list = xmlNewDocText(ctxt->myDoc, value);
-		    if (list != NULL) {
-			if ((ent->etype == XML_INTERNAL_GENERAL_ENTITY) &&
-			    (ent->children == NULL)) {
-			    ent->children = list;
-			    ent->last = list;
-			    ent->owner = 1;
-			    list->parent = (xmlNodePtr) ent;
-			} else {
-			    xmlFreeNodeList(list);
+		    if (((list->type == XML_TEXT_NODE) &&
+			 (list->next == NULL)) ||
+			(ctxt->parseMode == XML_PARSE_READER)) {
+			list->parent = (xmlNodePtr) ent;
+			list = NULL;
+			ent->owner = 1;
+		    } else {
+			ent->owner = 0;
+			while (list != NULL) {
+			    list->parent = (xmlNodePtr) ctxt->node;
+			    list->doc = ctxt->myDoc;
+			    if (list->next == NULL)
+				ent->last = list;
+			    list = list->next;
 			}
-		    } else if (list != NULL) {
-			xmlFreeNodeList(list);
+			list = ent->children;
+#ifdef LIBXML_LEGACY_ENABLED
+			if (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)
+			  xmlAddEntityReference(ent, list, NULL);
+#endif /* LIBXML_LEGACY_ENABLED */
 		    }
 		} else {
-		    /*
-		     * 4.3.2: An internal general parsed entity is well-formed
-		     * if its replacement text matches the production labeled
-		     * content.
-		     */
-
-		    void *user_data;
-		    /*
-		     * This is a bit hackish but this seems the best
-		     * way to make sure both SAX and DOM entity support
-		     * behaves okay.
-		     */
-		    if (ctxt->userData == ctxt)
-			user_data = NULL;
-		    else
-			user_data = ctxt->userData;
-
-		    if (ent->etype == XML_INTERNAL_GENERAL_ENTITY) {
-			ctxt->depth++;
-			ret = xmlParseBalancedChunkMemoryInternal(ctxt,
-					   value, user_data, &list);
-			ctxt->depth--;
-		    } else if (ent->etype ==
-			       XML_EXTERNAL_GENERAL_PARSED_ENTITY) {
-			ctxt->depth++;
-			ret = xmlParseExternalEntityPrivate(ctxt->myDoc, ctxt,
-				   ctxt->sax, user_data, ctxt->depth,
-				   ent->URI, ent->ExternalID, &list);
-			ctxt->depth--;
-		    } else {
-			ret = XML_ERR_ENTITY_PE_INTERNAL;
-			xmlErrMsgStr(ctxt, XML_ERR_INTERNAL_ERROR,
-				     "invalid entity type found\n", NULL);
-		    }
-		    if (ret == XML_ERR_ENTITY_LOOP) {
-			xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
-			return;
-		    } else if ((ret == XML_ERR_OK) && (list != NULL)) {
-			if (((ent->etype == XML_INTERNAL_GENERAL_ENTITY) ||
-			 (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY))&&
-			    (ent->children == NULL)) {
-			    ent->children = list;
-			    if (ctxt->replaceEntities) {
-				/*
-				 * Prune it directly in the generated document
-				 * except for single text nodes.
-				 */
-				if (((list->type == XML_TEXT_NODE) &&
-				     (list->next == NULL)) ||
-				    (ctxt->parseMode == XML_PARSE_READER)) {
-				    list->parent = (xmlNodePtr) ent;
-				    list = NULL;
-				    ent->owner = 1;
-				} else {
-				    ent->owner = 0;
-				    while (list != NULL) {
-					list->parent = (xmlNodePtr) ctxt->node;
-					list->doc = ctxt->myDoc;
-					if (list->next == NULL)
-					    ent->last = list;
-					list = list->next;
-			 	    }
-				    list = ent->children;
-#ifdef LIBXML_LEGACY_ENABLED
-				    if (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)
-				      xmlAddEntityReference(ent, list, NULL);
-#endif /* LIBXML_LEGACY_ENABLED */
-				}
-			    } else {
-				ent->owner = 1;
-				while (list != NULL) {
-				    list->parent = (xmlNodePtr) ent;
-				    if (list->next == NULL)
-					ent->last = list;
-				    list = list->next;
-				}
-			    }
-			} else {
-			    xmlFreeNodeList(list);
-			    list = NULL;
-			}
-		    } else if ((ret != XML_ERR_OK) &&
-		               (ret != XML_WAR_UNDECLARED_ENTITY)) {
-			xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
-				 "Entity '%s' failed to parse\n", ent->name);
-		    } else if (list != NULL) {
-			xmlFreeNodeList(list);
-			list = NULL;
+		    ent->owner = 1;
+		    while (list != NULL) {
+			list->parent = (xmlNodePtr) ent;
+			if (list->next == NULL)
+			    ent->last = list;
+			list = list->next;
 		    }
 		}
-		ent->checked = 1;
+	    } else {
+		xmlFreeNodeList(list);
+		list = NULL;
 	    }
+	} else if ((ret != XML_ERR_OK) &&
+		   (ret != XML_WAR_UNDECLARED_ENTITY)) {
+	    xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
+		     "Entity '%s' failed to parse\n", ent->name);
+	} else if (list != NULL) {
+	    xmlFreeNodeList(list);
+	    list = NULL;
+	}
+	if (ent->checked == 0)
+	    ent->checked = 1;
+    } else if (ent->checked != 1) {
+	ctxt->nbentities += ent->checked;
+    }
 
-            if (ent->children == NULL) {
-		/*
-		 * Probably running in SAX mode and the callbacks don't
-		 * build the entity content. So unless we already went
-		 * though parsing for first checking go though the entity
-		 * content to generate callbacks associated to the entity
-		 */
-		if (was_checked == 1) {
-		    void *user_data;
-		    /*
-		     * This is a bit hackish but this seems the best
-		     * way to make sure both SAX and DOM entity support
-		     * behaves okay.
-		     */
-		    if (ctxt->userData == ctxt)
-			user_data = NULL;
-		    else
-			user_data = ctxt->userData;
-
-		    if (ent->etype == XML_INTERNAL_GENERAL_ENTITY) {
-			ctxt->depth++;
-			ret = xmlParseBalancedChunkMemoryInternal(ctxt,
-					   ent->content, user_data, NULL);
-			ctxt->depth--;
-		    } else if (ent->etype ==
-			       XML_EXTERNAL_GENERAL_PARSED_ENTITY) {
-			ctxt->depth++;
-			ret = xmlParseExternalEntityPrivate(ctxt->myDoc, ctxt,
-				   ctxt->sax, user_data, ctxt->depth,
-				   ent->URI, ent->ExternalID, NULL);
-			ctxt->depth--;
-		    } else {
-			ret = XML_ERR_ENTITY_PE_INTERNAL;
-			xmlErrMsgStr(ctxt, XML_ERR_INTERNAL_ERROR,
-				     "invalid entity type found\n", NULL);
-		    }
-		    if (ret == XML_ERR_ENTITY_LOOP) {
-			xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
-			return;
-		    }
-		}
-		if ((ctxt->sax != NULL) && (ctxt->sax->reference != NULL) &&
-		    (ctxt->replaceEntities == 0) && (!ctxt->disableSAX)) {
-		    /*
-		     * Entity reference callback comes second, it's somewhat
-		     * superfluous but a compatibility to historical behaviour
-		     */
-		    ctxt->sax->reference(ctxt->userData, ent->name);
-		}
-		return;
-	    }
-	    if ((ctxt->sax != NULL) && (ctxt->sax->reference != NULL) &&
-	        (ctxt->replaceEntities == 0) && (!ctxt->disableSAX)) {
-		/*
-		 * Create a node.
-		 */
-		ctxt->sax->reference(ctxt->userData, ent->name);
-		return;
-	    }
-	    if ((ctxt->replaceEntities) || (ent->children == NULL))  {
-		/*
-		 * There is a problem on the handling of _private for entities
-		 * (bug 155816): Should we copy the content of the field from
-		 * the entity (possibly overwriting some value set by the user
-		 * when a copy is created), should we leave it alone, or should
-		 * we try to take care of different situations?  The problem
-		 * is exacerbated by the usage of this field by the xmlReader.
-		 * To fix this bug, we look at _private on the created node
-		 * and, if it's NULL, we copy in whatever was in the entity.
-		 * If it's not NULL we leave it alone.  This is somewhat of a
-		 * hack - maybe we should have further tests to determine
-		 * what to do.
-		 */
-		if ((ctxt->node != NULL) && (ent->children != NULL)) {
-		    /*
-		     * Seems we are generating the DOM content, do
-		     * a simple tree copy for all references except the first
-		     * In the first occurrence list contains the replacement.
-		     * progressive == 2 means we are operating on the Reader
-		     * and since nodes are discarded we must copy all the time.
-		     */
-		    if (((list == NULL) && (ent->owner == 0)) ||
-		        (ctxt->parseMode == XML_PARSE_READER)) {
-			xmlNodePtr nw = NULL, cur, firstChild = NULL;
-
-			/*
-			 * when operating on a reader, the entities definitions
-			 * are always owning the entities subtree.
-			if (ctxt->parseMode == XML_PARSE_READER)
-			    ent->owner = 1;
-			 */
-
-			cur = ent->children;
-			while (cur != NULL) {
-			    nw = xmlDocCopyNode(cur, ctxt->myDoc, 1);
-			    if (nw != NULL) {
-				if (nw->_private == NULL)
-				    nw->_private = cur->_private;
-				if (firstChild == NULL){
-				    firstChild = nw;
-				}
-				nw = xmlAddChild(ctxt->node, nw);
-			    }
-			    if (cur == ent->last) {
-			        /*
-				 * needed to detect some strange empty
-				 * node cases in the reader tests
-				 */
-			        if ((ctxt->parseMode == XML_PARSE_READER) &&
-				    (nw != NULL) &&
-				    (nw->type == XML_ELEMENT_NODE) &&
-				    (nw->children == NULL))
-				    nw->extra = 1;
-
-				break;
-			    }
-			    cur = cur->next;
-			}
-#ifdef LIBXML_LEGACY_ENABLED
-			if (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)			      
-			  xmlAddEntityReference(ent, firstChild, nw);
-#endif /* LIBXML_LEGACY_ENABLED */
-		    } else if (list == NULL) {
-			xmlNodePtr nw = NULL, cur, next, last,
-			           firstChild = NULL;
-			/*
-			 * Copy the entity child list and make it the new
-			 * entity child list. The goal is to make sure any
-			 * ID or REF referenced will be the one from the
-			 * document content and not the entity copy.
-			 */
-			cur = ent->children;
-			ent->children = NULL;
-			last = ent->last;
-			ent->last = NULL;
-			while (cur != NULL) {
-			    next = cur->next;
-			    cur->next = NULL;
-			    cur->parent = NULL;
-			    nw = xmlDocCopyNode(cur, ctxt->myDoc, 1);
-			    if (nw != NULL) {
-				if (nw->_private == NULL)
-				    nw->_private = cur->_private;
-				if (firstChild == NULL){
-				    firstChild = cur;
-				}
-				xmlAddChild((xmlNodePtr) ent, nw);
-				xmlAddChild(ctxt->node, cur);
-			    }
-			    if (cur == last)
-				break;
-			    cur = next;
-			}
-			ent->owner = 1;
-#ifdef LIBXML_LEGACY_ENABLED
-			if (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)			      
-			  xmlAddEntityReference(ent, firstChild, nw);
-#endif /* LIBXML_LEGACY_ENABLED */
-		    } else {
-		        const xmlChar *nbktext;
-
-			/*
-			 * the name change is to avoid coalescing of the
-			 * node with a possible previous text one which
-			 * would make ent->children a dangling pointer
-			 */
-			nbktext = xmlDictLookup(ctxt->dict, BAD_CAST "nbktext",
-			                        -1);
-			if (ent->children->type == XML_TEXT_NODE)
-			    ent->children->name = nbktext;
-			if ((ent->last != ent->children) &&
-			    (ent->last->type == XML_TEXT_NODE))
-			    ent->last->name = nbktext;
-			xmlAddChildList(ctxt->node, ent->children);
-		    }
-
-		    /*
-		     * This is to avoid a nasty side effect, see
-		     * characters() in SAX.c
-		     */
-		    ctxt->nodemem = 0;
-		    ctxt->nodelen = 0;
-		    return;
-		}
-	    }
-	} else {
-	    val = ent->content;
-	    if (val == NULL) return;
+    /*
+     * Now that the entity content has been gathered
+     * provide it to the application, this can take different forms based
+     * on the parsing modes.
+     */
+    if (ent->children == NULL) {
+	/*
+	 * Probably running in SAX mode and the callbacks don't
+	 * build the entity content. So unless we already went
+	 * though parsing for first checking go though the entity
+	 * content to generate callbacks associated to the entity
+	 */
+	if (was_checked != 0) {
+	    void *user_data;
 	    /*
-	     * inline the entity.
+	     * This is a bit hackish but this seems the best
+	     * way to make sure both SAX and DOM entity support
+	     * behaves okay.
 	     */
-	    if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL) &&
-		(!ctxt->disableSAX))
-		ctxt->sax->characters(ctxt->userData, val, xmlStrlen(val));
+	    if (ctxt->userData == ctxt)
+		user_data = NULL;
+	    else
+		user_data = ctxt->userData;
+
+	    if (ent->etype == XML_INTERNAL_GENERAL_ENTITY) {
+		ctxt->depth++;
+		ret = xmlParseBalancedChunkMemoryInternal(ctxt,
+				   ent->content, user_data, NULL);
+		ctxt->depth--;
+	    } else if (ent->etype ==
+		       XML_EXTERNAL_GENERAL_PARSED_ENTITY) {
+		ctxt->depth++;
+		ret = xmlParseExternalEntityPrivate(ctxt->myDoc, ctxt,
+			   ctxt->sax, user_data, ctxt->depth,
+			   ent->URI, ent->ExternalID, NULL);
+		ctxt->depth--;
+	    } else {
+		ret = XML_ERR_ENTITY_PE_INTERNAL;
+		xmlErrMsgStr(ctxt, XML_ERR_INTERNAL_ERROR,
+			     "invalid entity type found\n", NULL);
+	    }
+	    if (ret == XML_ERR_ENTITY_LOOP) {
+		xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL);
+		return;
+	    }
+	}
+	if ((ctxt->sax != NULL) && (ctxt->sax->reference != NULL) &&
+	    (ctxt->replaceEntities == 0) && (!ctxt->disableSAX)) {
+	    /*
+	     * Entity reference callback comes second, it's somewhat
+	     * superfluous but a compatibility to historical behaviour
+	     */
+	    ctxt->sax->reference(ctxt->userData, ent->name);
+	}
+	return;
+    }
+
+    /*
+     * If we didn't get any children for the entity being built
+     */
+    if ((ctxt->sax != NULL) && (ctxt->sax->reference != NULL) &&
+	(ctxt->replaceEntities == 0) && (!ctxt->disableSAX)) {
+	/*
+	 * Create a node.
+	 */
+	ctxt->sax->reference(ctxt->userData, ent->name);
+	return;
+    }
+
+    if ((ctxt->replaceEntities) || (ent->children == NULL))  {
+	/*
+	 * There is a problem on the handling of _private for entities
+	 * (bug 155816): Should we copy the content of the field from
+	 * the entity (possibly overwriting some value set by the user
+	 * when a copy is created), should we leave it alone, or should
+	 * we try to take care of different situations?  The problem
+	 * is exacerbated by the usage of this field by the xmlReader.
+	 * To fix this bug, we look at _private on the created node
+	 * and, if it's NULL, we copy in whatever was in the entity.
+	 * If it's not NULL we leave it alone.  This is somewhat of a
+	 * hack - maybe we should have further tests to determine
+	 * what to do.
+	 */
+	if ((ctxt->node != NULL) && (ent->children != NULL)) {
+	    /*
+	     * Seems we are generating the DOM content, do
+	     * a simple tree copy for all references except the first
+	     * In the first occurrence list contains the replacement.
+	     * progressive == 2 means we are operating on the Reader
+	     * and since nodes are discarded we must copy all the time.
+	     */
+	    if (((list == NULL) && (ent->owner == 0)) ||
+		(ctxt->parseMode == XML_PARSE_READER)) {
+		xmlNodePtr nw = NULL, cur, firstChild = NULL;
+
+		/*
+		 * when operating on a reader, the entities definitions
+		 * are always owning the entities subtree.
+		if (ctxt->parseMode == XML_PARSE_READER)
+		    ent->owner = 1;
+		 */
+
+		cur = ent->children;
+		while (cur != NULL) {
+		    nw = xmlDocCopyNode(cur, ctxt->myDoc, 1);
+		    if (nw != NULL) {
+			if (nw->_private == NULL)
+			    nw->_private = cur->_private;
+			if (firstChild == NULL){
+			    firstChild = nw;
+			}
+			nw = xmlAddChild(ctxt->node, nw);
+		    }
+		    if (cur == ent->last) {
+			/*
+			 * needed to detect some strange empty
+			 * node cases in the reader tests
+			 */
+			if ((ctxt->parseMode == XML_PARSE_READER) &&
+			    (nw != NULL) &&
+			    (nw->type == XML_ELEMENT_NODE) &&
+			    (nw->children == NULL))
+			    nw->extra = 1;
+
+			break;
+		    }
+		    cur = cur->next;
+		}
+#ifdef LIBXML_LEGACY_ENABLED
+		if (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)
+		  xmlAddEntityReference(ent, firstChild, nw);
+#endif /* LIBXML_LEGACY_ENABLED */
+	    } else if (list == NULL) {
+		xmlNodePtr nw = NULL, cur, next, last,
+			   firstChild = NULL;
+		/*
+		 * Copy the entity child list and make it the new
+		 * entity child list. The goal is to make sure any
+		 * ID or REF referenced will be the one from the
+		 * document content and not the entity copy.
+		 */
+		cur = ent->children;
+		ent->children = NULL;
+		last = ent->last;
+		ent->last = NULL;
+		while (cur != NULL) {
+		    next = cur->next;
+		    cur->next = NULL;
+		    cur->parent = NULL;
+		    nw = xmlDocCopyNode(cur, ctxt->myDoc, 1);
+		    if (nw != NULL) {
+			if (nw->_private == NULL)
+			    nw->_private = cur->_private;
+			if (firstChild == NULL){
+			    firstChild = cur;
+			}
+			xmlAddChild((xmlNodePtr) ent, nw);
+			xmlAddChild(ctxt->node, cur);
+		    }
+		    if (cur == last)
+			break;
+		    cur = next;
+		}
+		if (ent->owner == 0)
+		    ent->owner = 1;
+#ifdef LIBXML_LEGACY_ENABLED
+		if (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)
+		  xmlAddEntityReference(ent, firstChild, nw);
+#endif /* LIBXML_LEGACY_ENABLED */
+	    } else {
+		const xmlChar *nbktext;
+
+		/*
+		 * the name change is to avoid coalescing of the
+		 * node with a possible previous text one which
+		 * would make ent->children a dangling pointer
+		 */
+		nbktext = xmlDictLookup(ctxt->dict, BAD_CAST "nbktext",
+					-1);
+		if (ent->children->type == XML_TEXT_NODE)
+		    ent->children->name = nbktext;
+		if ((ent->last != ent->children) &&
+		    (ent->last->type == XML_TEXT_NODE))
+		    ent->last->name = nbktext;
+		xmlAddChildList(ctxt->node, ent->children);
+	    }
+
+	    /*
+	     * This is to avoid a nasty side effect, see
+	     * characters() in SAX.c
+	     */
+	    ctxt->nodemem = 0;
+	    ctxt->nodelen = 0;
+	    return;
 	}
     }
 }
@@ -6405,132 +7028,146 @@
     xmlEntityPtr ent = NULL;
 
     GROW;
-    
-    if (RAW == '&') {
-        NEXT;
-        name = xmlParseName(ctxt);
-	if (name == NULL) {
-	    xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
-			   "xmlParseEntityRef: no name\n");
-	} else {
-	    if (RAW == ';') {
-	        NEXT;
-		/*
-		 * Ask first SAX for entity resolution, otherwise try the
-		 * predefined set.
-		 */
-		if (ctxt->sax != NULL) {
-		    if (ctxt->sax->getEntity != NULL)
-			ent = ctxt->sax->getEntity(ctxt->userData, name);
-		    if ((ctxt->wellFormed == 1 ) && (ent == NULL))
-		        ent = xmlGetPredefinedEntity(name);
-		    if ((ctxt->wellFormed == 1 ) && (ent == NULL) &&
-			(ctxt->userData==ctxt)) {
-			ent = xmlSAX2GetEntity(ctxt, name);
-		    }
-		}
-		/*
-		 * [ WFC: Entity Declared ]
-		 * In a document without any DTD, a document with only an
-		 * internal DTD subset which contains no parameter entity
-		 * references, or a document with "standalone='yes'", the
-		 * Name given in the entity reference must match that in an
-		 * entity declaration, except that well-formed documents
-		 * need not declare any of the following entities: amp, lt,
-		 * gt, apos, quot.
-		 * The declaration of a parameter entity must precede any
-		 * reference to it.
-		 * Similarly, the declaration of a general entity must
-		 * precede any reference to it which appears in a default
-		 * value in an attribute-list declaration. Note that if
-		 * entities are declared in the external subset or in
-		 * external parameter entities, a non-validating processor
-		 * is not obligated to read and process their declarations;
-		 * for such documents, the rule that an entity must be
-		 * declared is a well-formedness constraint only if
-		 * standalone='yes'. 
-		 */
-		if (ent == NULL) {
-		    if ((ctxt->standalone == 1) ||
-		        ((ctxt->hasExternalSubset == 0) &&
-			 (ctxt->hasPErefs == 0))) {
-			xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
-				 "Entity '%s' not defined\n", name);
-		    } else {
-		        xmlErrMsgStr(ctxt, XML_WAR_UNDECLARED_ENTITY,
-				 "Entity '%s' not defined\n", name);
-			if ((ctxt->inSubset == 0) &&
-		            (ctxt->sax != NULL) &&
-		            (ctxt->sax->reference != NULL)) {
-			    ctxt->sax->reference(ctxt->userData, name);
-			}
-		    }
-		    ctxt->valid = 0;
-		}
 
-		/*
-		 * [ WFC: Parsed Entity ]
-		 * An entity reference must not contain the name of an
-		 * unparsed entity
-		 */
-		else if (ent->etype == XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) {
-		    xmlFatalErrMsgStr(ctxt, XML_ERR_UNPARSED_ENTITY,
-			     "Entity reference to unparsed entity %s\n", name);
-		}
+    if (RAW != '&')
+        return(NULL);
+    NEXT;
+    name = xmlParseName(ctxt);
+    if (name == NULL) {
+	xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
+		       "xmlParseEntityRef: no name\n");
+        return(NULL);
+    }
+    if (RAW != ';') {
+	xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
+	return(NULL);
+    }
+    NEXT;
 
-		/*
-		 * [ WFC: No External Entity References ]
-		 * Attribute values cannot contain direct or indirect
-		 * entity references to external entities.
-		 */
-		else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&
-		         (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)) {
-		    xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_EXTERNAL,
-			 "Attribute references external entity '%s'\n", name);
-		}
-		/*
-		 * [ WFC: No < in Attribute Values ]
-		 * The replacement text of any entity referred to directly or
-		 * indirectly in an attribute value (other than "&lt;") must
-		 * not contain a <. 
-		 */
-		else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&
-		         (ent != NULL) &&
-			 (!xmlStrEqual(ent->name, BAD_CAST "lt")) &&
-		         (ent->content != NULL) &&
-			 (xmlStrchr(ent->content, '<'))) {
-		    xmlFatalErrMsgStr(ctxt, XML_ERR_LT_IN_ATTRIBUTE,
-	 "'<' in entity '%s' is not allowed in attributes values\n", name);
-		}
+    /*
+     * Predefined entites override any extra definition
+     */
+    if ((ctxt->options & XML_PARSE_OLDSAX) == 0) {
+        ent = xmlGetPredefinedEntity(name);
+        if (ent != NULL)
+            return(ent);
+    }
 
-		/*
-		 * Internal check, no parameter entities here ...
-		 */
-		else {
-		    switch (ent->etype) {
-			case XML_INTERNAL_PARAMETER_ENTITY:
-			case XML_EXTERNAL_PARAMETER_ENTITY:
-			xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER,
-			 "Attempt to reference the parameter entity '%s'\n",
-		                          name);
-			break;
-			default:
-			break;
-		    }
-		}
+    /*
+     * Increate the number of entity references parsed
+     */
+    ctxt->nbentities++;
 
-		/*
-		 * [ WFC: No Recursion ]
-		 * A parsed entity must not contain a recursive reference
-		 * to itself, either directly or indirectly. 
-		 * Done somewhere else
-		 */
-
-	    } else {
-		xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
-	    }
+    /*
+     * Ask first SAX for entity resolution, otherwise try the
+     * entities which may have stored in the parser context.
+     */
+    if (ctxt->sax != NULL) {
+	if (ctxt->sax->getEntity != NULL)
+	    ent = ctxt->sax->getEntity(ctxt->userData, name);
+	if ((ctxt->wellFormed == 1 ) && (ent == NULL) && 
+	    (ctxt->options & XML_PARSE_OLDSAX))
+	    ent = xmlGetPredefinedEntity(name);
+	if ((ctxt->wellFormed == 1 ) && (ent == NULL) &&
+	    (ctxt->userData==ctxt)) {
+	    ent = xmlSAX2GetEntity(ctxt, name);
 	}
     }
+    /*
+     * [ WFC: Entity Declared ]
+     * In a document without any DTD, a document with only an
+     * internal DTD subset which contains no parameter entity
+     * references, or a document with "standalone='yes'", the
+     * Name given in the entity reference must match that in an
+     * entity declaration, except that well-formed documents
+     * need not declare any of the following entities: amp, lt,
+     * gt, apos, quot.
+     * The declaration of a parameter entity must precede any
+     * reference to it.
+     * Similarly, the declaration of a general entity must
+     * precede any reference to it which appears in a default
+     * value in an attribute-list declaration. Note that if
+     * entities are declared in the external subset or in
+     * external parameter entities, a non-validating processor
+     * is not obligated to read and process their declarations;
+     * for such documents, the rule that an entity must be
+     * declared is a well-formedness constraint only if
+     * standalone='yes'.
+     */
+    if (ent == NULL) {
+	if ((ctxt->standalone == 1) ||
+	    ((ctxt->hasExternalSubset == 0) &&
+	     (ctxt->hasPErefs == 0))) {
+	    xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
+		     "Entity '%s' not defined\n", name);
+	} else {
+	    xmlErrMsgStr(ctxt, XML_WAR_UNDECLARED_ENTITY,
+		     "Entity '%s' not defined\n", name);
+	    if ((ctxt->inSubset == 0) &&
+		(ctxt->sax != NULL) &&
+		(ctxt->sax->reference != NULL)) {
+		ctxt->sax->reference(ctxt->userData, name);
+	    }
+	}
+	ctxt->valid = 0;
+    }
+
+    /*
+     * [ WFC: Parsed Entity ]
+     * An entity reference must not contain the name of an
+     * unparsed entity
+     */
+    else if (ent->etype == XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) {
+	xmlFatalErrMsgStr(ctxt, XML_ERR_UNPARSED_ENTITY,
+		 "Entity reference to unparsed entity %s\n", name);
+    }
+
+    /*
+     * [ WFC: No External Entity References ]
+     * Attribute values cannot contain direct or indirect
+     * entity references to external entities.
+     */
+    else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&
+	     (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)) {
+	xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_EXTERNAL,
+	     "Attribute references external entity '%s'\n", name);
+    }
+    /*
+     * [ WFC: No < in Attribute Values ]
+     * The replacement text of any entity referred to directly or
+     * indirectly in an attribute value (other than "&lt;") must
+     * not contain a <. 
+     */
+    else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&
+	     (ent != NULL) && (ent->content != NULL) &&
+	     (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) &&
+	     (xmlStrchr(ent->content, '<'))) {
+	xmlFatalErrMsgStr(ctxt, XML_ERR_LT_IN_ATTRIBUTE,
+    "'<' in entity '%s' is not allowed in attributes values\n", name);
+    }
+
+    /*
+     * Internal check, no parameter entities here ...
+     */
+    else {
+	switch (ent->etype) {
+	    case XML_INTERNAL_PARAMETER_ENTITY:
+	    case XML_EXTERNAL_PARAMETER_ENTITY:
+	    xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER,
+	     "Attempt to reference the parameter entity '%s'\n",
+			      name);
+	    break;
+	    default:
+	    break;
+	}
+    }
+
+    /*
+     * [ WFC: No Recursion ]
+     * A parsed entity must not contain a recursive reference
+     * to itself, either directly or indirectly. 
+     * Done somewhere else
+     */
     return(ent);
 }
 
@@ -6576,129 +7213,152 @@
         return(NULL);
     ptr = *str;
     cur = *ptr;
-    if (cur == '&') {
-        ptr++;
-	cur = *ptr;
-        name = xmlParseStringName(ctxt, &ptr);
-	if (name == NULL) {
-	    xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
-			   "xmlParseStringEntityRef: no name\n");
-	} else {
-	    if (*ptr == ';') {
-	        ptr++;
-		/*
-		 * Ask first SAX for entity resolution, otherwise try the
-		 * predefined set.
-		 */
-		if (ctxt->sax != NULL) {
-		    if (ctxt->sax->getEntity != NULL)
-			ent = ctxt->sax->getEntity(ctxt->userData, name);
-		    if (ent == NULL)
-		        ent = xmlGetPredefinedEntity(name);
-		    if ((ent == NULL) && (ctxt->userData==ctxt)) {
-			ent = xmlSAX2GetEntity(ctxt, name);
-		    }
-		}
-		/*
-		 * [ WFC: Entity Declared ]
-		 * In a document without any DTD, a document with only an
-		 * internal DTD subset which contains no parameter entity
-		 * references, or a document with "standalone='yes'", the
-		 * Name given in the entity reference must match that in an
-		 * entity declaration, except that well-formed documents
-		 * need not declare any of the following entities: amp, lt,
-		 * gt, apos, quot.
-		 * The declaration of a parameter entity must precede any
-		 * reference to it.
-		 * Similarly, the declaration of a general entity must
-		 * precede any reference to it which appears in a default
-		 * value in an attribute-list declaration. Note that if
-		 * entities are declared in the external subset or in
-		 * external parameter entities, a non-validating processor
-		 * is not obligated to read and process their declarations;
-		 * for such documents, the rule that an entity must be
-		 * declared is a well-formedness constraint only if
-		 * standalone='yes'. 
-		 */
-		if (ent == NULL) {
-		    if ((ctxt->standalone == 1) ||
-		        ((ctxt->hasExternalSubset == 0) &&
-			 (ctxt->hasPErefs == 0))) {
-			xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
-				 "Entity '%s' not defined\n", name);
-		    } else {
-			xmlErrMsgStr(ctxt, XML_WAR_UNDECLARED_ENTITY,
-				      "Entity '%s' not defined\n",
-				      name);
-		    }
-		    /* TODO ? check regressions ctxt->valid = 0; */
-		}
+    if (cur != '&')
+	return(NULL);
 
-		/*
-		 * [ WFC: Parsed Entity ]
-		 * An entity reference must not contain the name of an
-		 * unparsed entity
-		 */
-		else if (ent->etype == XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) {
-		    xmlFatalErrMsgStr(ctxt, XML_ERR_UNPARSED_ENTITY,
-			     "Entity reference to unparsed entity %s\n", name);
-		}
+    ptr++;
+    cur = *ptr;
+    name = xmlParseStringName(ctxt, &ptr);
+    if (name == NULL) {
+	xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
+		       "xmlParseStringEntityRef: no name\n");
+	*str = ptr;
+	return(NULL);
+    }
+    if (*ptr != ';') {
+	xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
+        xmlFree(name);
+	*str = ptr;
+	return(NULL);
+    }
+    ptr++;
 
-		/*
-		 * [ WFC: No External Entity References ]
-		 * Attribute values cannot contain direct or indirect
-		 * entity references to external entities.
-		 */
-		else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&
-		         (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)) {
-		    xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_EXTERNAL,
-		     "Attribute references external entity '%s'\n", name);
-		}
-		/*
-		 * [ WFC: No < in Attribute Values ]
-		 * The replacement text of any entity referred to directly or
-		 * indirectly in an attribute value (other than "&lt;") must
-		 * not contain a <. 
-		 */
-		else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&
-		         (ent != NULL) &&
-			 (!xmlStrEqual(ent->name, BAD_CAST "lt")) &&
-		         (ent->content != NULL) &&
-			 (xmlStrchr(ent->content, '<'))) {
-		    xmlFatalErrMsgStr(ctxt, XML_ERR_LT_IN_ATTRIBUTE,
-		 "'<' in entity '%s' is not allowed in attributes values\n",
-	                              name);
-		}
 
-		/*
-		 * Internal check, no parameter entities here ...
-		 */
-		else {
-		    switch (ent->etype) {
-			case XML_INTERNAL_PARAMETER_ENTITY:
-			case XML_EXTERNAL_PARAMETER_ENTITY:
-			    xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER,
-			 "Attempt to reference the parameter entity '%s'\n",
-			                      name);
-			break;
-			default:
-			break;
-		    }
-		}
+    /*
+     * Predefined entites override any extra definition
+     */
+    if ((ctxt->options & XML_PARSE_OLDSAX) == 0) {
+        ent = xmlGetPredefinedEntity(name);
+        if (ent != NULL) {
+            xmlFree(name);
+            *str = ptr;
+            return(ent);
+        }
+    }
 
-		/*
-		 * [ WFC: No Recursion ]
-		 * A parsed entity must not contain a recursive reference
-		 * to itself, either directly or indirectly. 
-		 * Done somewhere else
-		 */
+    /*
+     * Increate the number of entity references parsed
+     */
+    ctxt->nbentities++;
 
-	    } else {
-		xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
-	    }
-	    xmlFree(name);
+    /*
+     * Ask first SAX for entity resolution, otherwise try the
+     * entities which may have stored in the parser context.
+     */
+    if (ctxt->sax != NULL) {
+	if (ctxt->sax->getEntity != NULL)
+	    ent = ctxt->sax->getEntity(ctxt->userData, name);
+	if ((ent == NULL) && (ctxt->options & XML_PARSE_OLDSAX))
+	    ent = xmlGetPredefinedEntity(name);
+	if ((ent == NULL) && (ctxt->userData==ctxt)) {
+	    ent = xmlSAX2GetEntity(ctxt, name);
 	}
     }
+
+    /*
+     * [ WFC: Entity Declared ]
+     * In a document without any DTD, a document with only an
+     * internal DTD subset which contains no parameter entity
+     * references, or a document with "standalone='yes'", the
+     * Name given in the entity reference must match that in an
+     * entity declaration, except that well-formed documents
+     * need not declare any of the following entities: amp, lt,
+     * gt, apos, quot.
+     * The declaration of a parameter entity must precede any
+     * reference to it.
+     * Similarly, the declaration of a general entity must
+     * precede any reference to it which appears in a default
+     * value in an attribute-list declaration. Note that if
+     * entities are declared in the external subset or in
+     * external parameter entities, a non-validating processor
+     * is not obligated to read and process their declarations;
+     * for such documents, the rule that an entity must be
+     * declared is a well-formedness constraint only if
+     * standalone='yes'. 
+     */
+    if (ent == NULL) {
+	if ((ctxt->standalone == 1) ||
+	    ((ctxt->hasExternalSubset == 0) &&
+	     (ctxt->hasPErefs == 0))) {
+	    xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
+		     "Entity '%s' not defined\n", name);
+	} else {
+	    xmlErrMsgStr(ctxt, XML_WAR_UNDECLARED_ENTITY,
+			  "Entity '%s' not defined\n",
+			  name);
+	}
+	/* TODO ? check regressions ctxt->valid = 0; */
+    }
+
+    /*
+     * [ WFC: Parsed Entity ]
+     * An entity reference must not contain the name of an
+     * unparsed entity
+     */
+    else if (ent->etype == XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) {
+	xmlFatalErrMsgStr(ctxt, XML_ERR_UNPARSED_ENTITY,
+		 "Entity reference to unparsed entity %s\n", name);
+    }
+
+    /*
+     * [ WFC: No External Entity References ]
+     * Attribute values cannot contain direct or indirect
+     * entity references to external entities.
+     */
+    else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&
+	     (ent->etype == XML_EXTERNAL_GENERAL_PARSED_ENTITY)) {
+	xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_EXTERNAL,
+	 "Attribute references external entity '%s'\n", name);
+    }
+    /*
+     * [ WFC: No < in Attribute Values ]
+     * The replacement text of any entity referred to directly or
+     * indirectly in an attribute value (other than "&lt;") must
+     * not contain a <.
+     */
+    else if ((ctxt->instate == XML_PARSER_ATTRIBUTE_VALUE) &&
+	     (ent != NULL) && (ent->content != NULL) &&
+	     (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) &&
+	     (xmlStrchr(ent->content, '<'))) {
+	xmlFatalErrMsgStr(ctxt, XML_ERR_LT_IN_ATTRIBUTE,
+     "'<' in entity '%s' is not allowed in attributes values\n",
+			  name);
+    }
+
+    /*
+     * Internal check, no parameter entities here ...
+     */
+    else {
+	switch (ent->etype) {
+	    case XML_INTERNAL_PARAMETER_ENTITY:
+	    case XML_EXTERNAL_PARAMETER_ENTITY:
+		xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER,
+	     "Attempt to reference the parameter entity '%s'\n",
+				  name);
+	    break;
+	    default:
+	    break;
+	}
+    }
+
+    /*
+     * [ WFC: No Recursion ]
+     * A parsed entity must not contain a recursive reference
+     * to itself, either directly or indirectly.
+     * Done somewhere else
+     */
+
+    xmlFree(name);
     *str = ptr;
     return(ent);
 }
@@ -6739,90 +7399,185 @@
     xmlEntityPtr entity = NULL;
     xmlParserInputPtr input;
 
-    if (RAW == '%') {
-        NEXT;
-        name = xmlParseName(ctxt);
-        if (name == NULL) {
-            xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
-                           "xmlParsePEReference: no name\n");
-        } else {
-            if (RAW == ';') {
-                NEXT;
-                if ((ctxt->sax != NULL) &&
-                    (ctxt->sax->getParameterEntity != NULL))
-                    entity = ctxt->sax->getParameterEntity(ctxt->userData,
-                                                           name);
-                if (entity == NULL) {
-                    /*
-                     * [ WFC: Entity Declared ]
-                     * In a document without any DTD, a document with only an
-                     * internal DTD subset which contains no parameter entity
-                     * references, or a document with "standalone='yes'", ...
-                     * ... The declaration of a parameter entity must precede
-                     * any reference to it...
-                     */
-                    if ((ctxt->standalone == 1) ||
-                        ((ctxt->hasExternalSubset == 0) &&
-                         (ctxt->hasPErefs == 0))) {
-                        xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
-                                          "PEReference: %%%s; not found\n",
-                                          name);
-                    } else {
-                        /*
-                         * [ VC: Entity Declared ]
-                         * In a document with an external subset or external
-                         * parameter entities with "standalone='no'", ...
-                         * ... The declaration of a parameter entity must
-			 * precede any reference to it...
-                         */
-                        xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
-                                      "PEReference: %%%s; not found\n",
-                                      name, NULL);
-                        ctxt->valid = 0;
-                    }
-                } else {
-                    /*
-                     * Internal checking in case the entity quest barfed
-                     */
-                    if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) &&
-                        (entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) {
-                        xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
-			      "Internal: %%%s; is not a parameter entity\n",
-                                      name, NULL);
-                    } else if (ctxt->input->free != deallocblankswrapper) {
-                        input =
-                            xmlNewBlanksWrapperInputStream(ctxt, entity);
-                        xmlPushInput(ctxt, input);
-                    } else {
-                        /*
-                         * TODO !!!
-                         * handle the extra spaces added before and after
-                         * c.f. http://www.w3.org/TR/REC-xml#as-PE
-                         */
-                        input = xmlNewEntityInputStream(ctxt, entity);
-                        xmlPushInput(ctxt, input);
-                        if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
-			    (CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) &&
-			    (IS_BLANK_CH(NXT(5)))) {
-                            xmlParseTextDecl(ctxt);
-                            if (ctxt->errNo ==
-                                XML_ERR_UNSUPPORTED_ENCODING) {
-                                /*
-                                 * The XML REC instructs us to stop parsing
-                                 * right here
-                                 */
-                                ctxt->instate = XML_PARSER_EOF;
-                                return;
-                            }
-                        }
-                    }
-                }
-                ctxt->hasPErefs = 1;
-            } else {
-                xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
-            }
-        }
+    if (RAW != '%')
+        return;
+    NEXT;
+    name = xmlParseName(ctxt);
+    if (name == NULL) {
+	xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
+		       "xmlParsePEReference: no name\n");
+	return;
     }
+    if (RAW != ';') {
+	xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
+        return;
+    }
+
+    NEXT;
+
+    /*
+     * Increate the number of entity references parsed
+     */
+    ctxt->nbentities++;
+
+    /*
+     * Request the entity from SAX
+     */
+    if ((ctxt->sax != NULL) &&
+	(ctxt->sax->getParameterEntity != NULL))
+	entity = ctxt->sax->getParameterEntity(ctxt->userData,
+					       name);
+    if (entity == NULL) {
+	/*
+	 * [ WFC: Entity Declared ]
+	 * In a document without any DTD, a document with only an
+	 * internal DTD subset which contains no parameter entity
+	 * references, or a document with "standalone='yes'", ...
+	 * ... The declaration of a parameter entity must precede
+	 * any reference to it...
+	 */
+	if ((ctxt->standalone == 1) ||
+	    ((ctxt->hasExternalSubset == 0) &&
+	     (ctxt->hasPErefs == 0))) {
+	    xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
+			      "PEReference: %%%s; not found\n",
+			      name);
+	} else {
+	    /*
+	     * [ VC: Entity Declared ]
+	     * In a document with an external subset or external
+	     * parameter entities with "standalone='no'", ...
+	     * ... The declaration of a parameter entity must
+	     * precede any reference to it...
+	     */
+	    xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
+			  "PEReference: %%%s; not found\n",
+			  name, NULL);
+	    ctxt->valid = 0;
+	}
+    } else {
+	/*
+	 * Internal checking in case the entity quest barfed
+	 */
+	if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) &&
+	    (entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) {
+	    xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
+		  "Internal: %%%s; is not a parameter entity\n",
+			  name, NULL);
+	} else if (ctxt->input->free != deallocblankswrapper) {
+	    input = xmlNewBlanksWrapperInputStream(ctxt, entity);
+	    if (xmlPushInput(ctxt, input) < 0)
+		return;
+	} else {
+	    /*
+	     * TODO !!!
+	     * handle the extra spaces added before and after
+	     * c.f. http://www.w3.org/TR/REC-xml#as-PE
+	     */
+	    input = xmlNewEntityInputStream(ctxt, entity);
+	    if (xmlPushInput(ctxt, input) < 0)
+		return;
+	    if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
+		(CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) &&
+		(IS_BLANK_CH(NXT(5)))) {
+		xmlParseTextDecl(ctxt);
+		if (ctxt->errNo ==
+		    XML_ERR_UNSUPPORTED_ENCODING) {
+		    /*
+		     * The XML REC instructs us to stop parsing
+		     * right here
+		     */
+		    ctxt->instate = XML_PARSER_EOF;
+		    return;
+		}
+	    }
+	}
+    }
+    ctxt->hasPErefs = 1;
+}
+
+/**
+ * xmlLoadEntityContent:
+ * @ctxt:  an XML parser context
+ * @entity: an unloaded system entity
+ *
+ * Load the original content of the given system entity from the
+ * ExternalID/SystemID given. This is to be used for Included in Literal
+ * http://www.w3.org/TR/REC-xml/#inliteral processing of entities references
+ *
+ * Returns 0 in case of success and -1 in case of failure
+ */
+static int
+xmlLoadEntityContent(xmlParserCtxtPtr ctxt, xmlEntityPtr entity) {
+    xmlParserInputPtr input;
+    xmlBufferPtr buf;
+    int l, c;
+    int count = 0;
+
+    if ((ctxt == NULL) || (entity == NULL) ||
+        ((entity->etype != XML_EXTERNAL_PARAMETER_ENTITY) &&
+	 (entity->etype != XML_EXTERNAL_GENERAL_PARSED_ENTITY)) ||
+	(entity->content != NULL)) {
+	xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
+	            "xmlLoadEntityContent parameter error");
+        return(-1);
+    }
+
+    if (xmlParserDebugEntities)
+	xmlGenericError(xmlGenericErrorContext,
+		"Reading %s entity content input\n", entity->name);
+
+    buf = xmlBufferCreate();
+    if (buf == NULL) {
+	xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
+	            "xmlLoadEntityContent parameter error");
+        return(-1);
+    }
+
+    input = xmlNewEntityInputStream(ctxt, entity);
+    if (input == NULL) {
+	xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
+	            "xmlLoadEntityContent input error");
+	xmlBufferFree(buf);
+        return(-1);
+    }
+
+    /*
+     * Push the entity as the current input, read char by char
+     * saving to the buffer until the end of the entity or an error
+     */
+    if (xmlPushInput(ctxt, input) < 0) {
+        xmlBufferFree(buf);
+	return(-1);
+    }
+
+    GROW;
+    c = CUR_CHAR(l);
+    while ((ctxt->input == input) && (ctxt->input->cur < ctxt->input->end) &&
+           (IS_CHAR(c))) {
+        xmlBufferAdd(buf, ctxt->input->cur, l);
+	if (count++ > 100) {
+	    count = 0;
+	    GROW;
+	}
+	NEXTL(l);
+	c = CUR_CHAR(l);
+    }
+
+    if ((ctxt->input == input) && (ctxt->input->cur >= ctxt->input->end)) {
+        xmlPopInput(ctxt);
+    } else if (!IS_CHAR(c)) {
+        xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
+                          "xmlLoadEntityContent: invalid char value %d\n",
+	                  c);
+	xmlBufferFree(buf);
+	return(-1);
+    }
+    entity->content = buf->content;
+    buf->content = NULL;
+    xmlBufferFree(buf);
+
+    return(0);
 }
 
 /**
@@ -6836,7 +7591,7 @@
  *
  * [ WFC: No Recursion ]
  * A parsed entity must not contain a recursive
- * reference to itself, either directly or indirectly. 
+ * reference to itself, either directly or indirectly.
  *
  * [ WFC: Entity Declared ]
  * In a document without any DTD, a document with only an internal DTD
@@ -6866,67 +7621,77 @@
     if ((str == NULL) || (*str == NULL)) return(NULL);
     ptr = *str;
     cur = *ptr;
-    if (cur == '%') {
-        ptr++;
-	cur = *ptr;
-        name = xmlParseStringName(ctxt, &ptr);
-	if (name == NULL) {
-	    xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
-			   "xmlParseStringPEReference: no name\n");
+    if (cur != '%')
+        return(NULL);
+    ptr++;
+    cur = *ptr;
+    name = xmlParseStringName(ctxt, &ptr);
+    if (name == NULL) {
+	xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
+		       "xmlParseStringPEReference: no name\n");
+	*str = ptr;
+	return(NULL);
+    }
+    cur = *ptr;
+    if (cur != ';') {
+	xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
+	xmlFree(name);
+	*str = ptr;
+	return(NULL);
+    }
+    ptr++;
+
+    /*
+     * Increate the number of entity references parsed
+     */
+    ctxt->nbentities++;
+
+    /*
+     * Request the entity from SAX
+     */
+    if ((ctxt->sax != NULL) &&
+	(ctxt->sax->getParameterEntity != NULL))
+	entity = ctxt->sax->getParameterEntity(ctxt->userData,
+					       name);
+    if (entity == NULL) {
+	/*
+	 * [ WFC: Entity Declared ]
+	 * In a document without any DTD, a document with only an
+	 * internal DTD subset which contains no parameter entity
+	 * references, or a document with "standalone='yes'", ...
+	 * ... The declaration of a parameter entity must precede
+	 * any reference to it...
+	 */
+	if ((ctxt->standalone == 1) ||
+	    ((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) {
+	    xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
+		 "PEReference: %%%s; not found\n", name);
 	} else {
-	    cur = *ptr;
-	    if (cur == ';') {
-		ptr++;
-		cur = *ptr;
-		if ((ctxt->sax != NULL) &&
-		    (ctxt->sax->getParameterEntity != NULL))
-		    entity = ctxt->sax->getParameterEntity(ctxt->userData,
-		                                           name);
-		if (entity == NULL) {
-		    /*
-		     * [ WFC: Entity Declared ]
-		     * In a document without any DTD, a document with only an
-		     * internal DTD subset which contains no parameter entity
-		     * references, or a document with "standalone='yes'", ...
-		     * ... The declaration of a parameter entity must precede
-		     * any reference to it...
-		     */
-		    if ((ctxt->standalone == 1) ||
-			((ctxt->hasExternalSubset == 0) &&
-			 (ctxt->hasPErefs == 0))) {
-			xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
-			     "PEReference: %%%s; not found\n", name);
-		    } else {
-			/*
-			 * [ VC: Entity Declared ]
-			 * In a document with an external subset or external
-			 * parameter entities with "standalone='no'", ...
-			 * ... The declaration of a parameter entity must
-			 * precede any reference to it...
-			 */
-			xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
-				      "PEReference: %%%s; not found\n",
-			              name, NULL);
-			ctxt->valid = 0;
-		    }
-		} else {
-		    /*
-		     * Internal checking in case the entity quest barfed
-		     */
-		    if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) &&
-		        (entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) {
-			xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
-			              "%%%s; is not a parameter entity\n",
-				      name, NULL);
-		    }
-		}
-		ctxt->hasPErefs = 1;
-	    } else {
-		xmlFatalErr(ctxt, XML_ERR_ENTITYREF_SEMICOL_MISSING, NULL);
-	    }
-	    xmlFree(name);
+	    /*
+	     * [ VC: Entity Declared ]
+	     * In a document with an external subset or external
+	     * parameter entities with "standalone='no'", ...
+	     * ... The declaration of a parameter entity must
+	     * precede any reference to it...
+	     */
+	    xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
+			  "PEReference: %%%s; not found\n",
+			  name, NULL);
+	    ctxt->valid = 0;
+	}
+    } else {
+	/*
+	 * Internal checking in case the entity quest barfed
+	 */
+	if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) &&
+	    (entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) {
+	    xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
+			  "%%%s; is not a parameter entity\n",
+			  name, NULL);
 	}
     }
+    ctxt->hasPErefs = 1;
+    xmlFree(name);
     *str = ptr;
     return(entity);
 }
@@ -7403,38 +8168,6 @@
  *									*
  ************************************************************************/
 
-static const xmlChar *
-xmlParseNCNameComplex(xmlParserCtxtPtr ctxt) {
-    int len = 0, l;
-    int c;
-    int count = 0;
-
-    /*
-     * Handler for more complex cases
-     */
-    GROW;
-    c = CUR_CHAR(l);
-    if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
-	(!IS_LETTER(c) && (c != '_'))) {
-	return(NULL);
-    }
-
-    while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
-	   ((IS_LETTER(c)) || (IS_DIGIT(c)) ||
-            (c == '.') || (c == '-') || (c == '_') ||
-	    (IS_COMBINING(c)) ||
-	    (IS_EXTENDER(c)))) {
-	if (count++ > 100) {
-	    count = 0;
-	    GROW;
-	}
-	len += l;
-	NEXTL(l);
-	c = CUR_CHAR(l);
-    }
-    return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len));
-}
-
 /*
  * xmlGetNamespace:
  * @ctxt:  an XML parser context
@@ -7460,56 +8193,6 @@
 }
 
 /**
- * xmlParseNCName:
- * @ctxt:  an XML parser context
- * @len:  lenght of the string parsed
- *
- * parse an XML name.
- *
- * [4NS] NCNameChar ::= Letter | Digit | '.' | '-' | '_' |
- *                      CombiningChar | Extender
- *
- * [5NS] NCName ::= (Letter | '_') (NCNameChar)*
- *
- * Returns the Name parsed or NULL
- */
-
-static const xmlChar *
-xmlParseNCName(xmlParserCtxtPtr ctxt) {
-    const xmlChar *in;
-    const xmlChar *ret;
-    int count = 0;
-
-    /*
-     * Accelerator for simple ASCII names
-     */
-    in = ctxt->input->cur;
-    if (((*in >= 0x61) && (*in <= 0x7A)) ||
-	((*in >= 0x41) && (*in <= 0x5A)) ||
-	(*in == '_')) {
-	in++;
-	while (((*in >= 0x61) && (*in <= 0x7A)) ||
-	       ((*in >= 0x41) && (*in <= 0x5A)) ||
-	       ((*in >= 0x30) && (*in <= 0x39)) ||
-	       (*in == '_') || (*in == '-') ||
-	       (*in == '.'))
-	    in++;
-	if ((*in > 0) && (*in < 0x80)) {
-	    count = in - ctxt->input->cur;
-	    ret = xmlDictLookup(ctxt->dict, ctxt->input->cur, count);
-	    ctxt->input->cur = in;
-	    ctxt->nbChars += count;
-	    ctxt->input->col += count;
-	    if (ret == NULL) {
-	        xmlErrMemory(ctxt, NULL);
-	    }
-	    return(ret);
-	}
-    }
-    return(xmlParseNCNameComplex(ctxt));
-}
-
-/**
  * xmlParseQName:
  * @ctxt:  an XML parser context
  * @prefix:  pointer to store the prefix part
@@ -7551,7 +8234,13 @@
 
             xmlNsErr(ctxt, XML_NS_ERR_QNAME,
 	             "Failed to parse QName '%s:'\n", p, NULL, NULL);
-	    tmp = xmlBuildQName(BAD_CAST "", p, NULL, 0);
+	    l = xmlParseNmtoken(ctxt);
+	    if (l == NULL)
+		tmp = xmlBuildQName(BAD_CAST "", p, NULL, 0);
+	    else {
+		tmp = xmlBuildQName(l, p, NULL, 0);
+		xmlFree((char *)l);
+	    }
 	    p = xmlDictLookup(ctxt->dict, tmp, -1);
 	    if (tmp != NULL) xmlFree(tmp);
 	    *prefix = NULL;
@@ -7811,9 +8500,10 @@
 
 static const xmlChar *
 xmlParseAttribute2(xmlParserCtxtPtr ctxt,
-                   const xmlChar *pref, const xmlChar *elem,
-                   const xmlChar **prefix, xmlChar **value,
-		   int *len, int *alloc) {
+                   const xmlChar * pref, const xmlChar * elem,
+                   const xmlChar ** prefix, xmlChar ** value,
+                   int *len, int *alloc)
+{
     const xmlChar *name;
     xmlChar *val, *internal_val = NULL;
     int normalize = 0;
@@ -7822,9 +8512,9 @@
     GROW;
     name = xmlParseQName(ctxt, prefix);
     if (name == NULL) {
-	xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
-	               "error parsing attribute name\n");
-        return(NULL);
+        xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
+                       "error parsing attribute name\n");
+        return (NULL);
     }
 
     /*
@@ -7834,8 +8524,9 @@
         int type;
 
         type = (int) (long) xmlHashQLookup2(ctxt->attsSpecial,
-	                                    pref, elem, *prefix, name);
-	if (type != 0) normalize = 1;
+                                            pref, elem, *prefix, name);
+        if (type != 0)
+            normalize = 1;
     }
 
     /*
@@ -7844,54 +8535,71 @@
     SKIP_BLANKS;
     if (RAW == '=') {
         NEXT;
-	SKIP_BLANKS;
-	val = xmlParseAttValueInternal(ctxt, len, alloc, normalize);
-	ctxt->instate = XML_PARSER_CONTENT;
+        SKIP_BLANKS;
+        val = xmlParseAttValueInternal(ctxt, len, alloc, normalize);
+	if (normalize) {
+	    /*
+	     * Sometimes a second normalisation pass for spaces is needed
+	     * but that only happens if charrefs or entities refernces
+	     * have been used in the attribute value, i.e. the attribute
+	     * value have been extracted in an allocated string already.
+	     */
+	    if (*alloc) {
+	        const xmlChar *val2;
+
+	        val2 = xmlAttrNormalizeSpace2(ctxt, val, len);
+		if ((val2 != NULL) && (val2 != val)) {
+		    xmlFree(val);
+		    val = (xmlChar *) val2;
+		}
+	    }
+	}
+        ctxt->instate = XML_PARSER_CONTENT;
     } else {
-	xmlFatalErrMsgStr(ctxt, XML_ERR_ATTRIBUTE_WITHOUT_VALUE,
-	       "Specification mandate value for attribute %s\n", name);
-	return(NULL);
+        xmlFatalErrMsgStr(ctxt, XML_ERR_ATTRIBUTE_WITHOUT_VALUE,
+                          "Specification mandate value for attribute %s\n",
+                          name);
+        return (NULL);
     }
 
-	if (*prefix == ctxt->str_xml) {
-		/*
-		 * Check that xml:lang conforms to the specification
-		 * No more registered as an error, just generate a warning now
-		 * since this was deprecated in XML second edition
-		 */
-		if ((ctxt->pedantic) && (xmlStrEqual(name, BAD_CAST "lang"))) {
-			internal_val = xmlStrndup(val, *len);
-			if (!xmlCheckLanguageID(internal_val)) {
-				xmlWarningMsg(ctxt, XML_WAR_LANG_VALUE,
-						  "Malformed value for xml:lang : %s\n",
-					  internal_val, NULL);
-			}
-		}
+    if (*prefix == ctxt->str_xml) {
+        /*
+         * Check that xml:lang conforms to the specification
+         * No more registered as an error, just generate a warning now
+         * since this was deprecated in XML second edition
+         */
+        if ((ctxt->pedantic) && (xmlStrEqual(name, BAD_CAST "lang"))) {
+            internal_val = xmlStrndup(val, *len);
+            if (!xmlCheckLanguageID(internal_val)) {
+                xmlWarningMsg(ctxt, XML_WAR_LANG_VALUE,
+                              "Malformed value for xml:lang : %s\n",
+                              internal_val, NULL);
+            }
+        }
 
-		/*
-		 * Check that xml:space conforms to the specification
-		 */
-		if (xmlStrEqual(name, BAD_CAST "space")) {
-			internal_val = xmlStrndup(val, *len);
-			if (xmlStrEqual(internal_val, BAD_CAST "default"))
-				*(ctxt->space) = 0;
-			else if (xmlStrEqual(internal_val, BAD_CAST "preserve"))
-				*(ctxt->space) = 1;
-			else {
-				xmlWarningMsg(ctxt, XML_WAR_SPACE_VALUE,
-"Invalid value \"%s\" for xml:space : \"default\" or \"preserve\" expected\n",
-                                 internal_val, NULL);
-			}
-		}
-		if (internal_val) {
-			xmlFree(internal_val);
-		}
-	}
+        /*
+         * Check that xml:space conforms to the specification
+         */
+        if (xmlStrEqual(name, BAD_CAST "space")) {
+            internal_val = xmlStrndup(val, *len);
+            if (xmlStrEqual(internal_val, BAD_CAST "default"))
+                *(ctxt->space) = 0;
+            else if (xmlStrEqual(internal_val, BAD_CAST "preserve"))
+                *(ctxt->space) = 1;
+            else {
+                xmlWarningMsg(ctxt, XML_WAR_SPACE_VALUE,
+                              "Invalid value \"%s\" for xml:space : \"default\" or \"preserve\" expected\n",
+                              internal_val, NULL);
+            }
+        }
+        if (internal_val) {
+            xmlFree(internal_val);
+        }
+    }
 
     *value = val;
-    return(name);
+    return (name);
 }
-
 /**
  * xmlParseStartTag2:
  * @ctxt:  an XML parser context
@@ -8003,17 +8711,33 @@
                 if (*URL != 0) {
 		    uri = xmlParseURI((const char *) URL);
 		    if (uri == NULL) {
-			xmlWarningMsg(ctxt, XML_WAR_NS_URI,
-				      "xmlns: %s not a valid URI\n",
-				      URL, NULL);
+			xmlNsErr(ctxt, XML_WAR_NS_URI,
+			         "xmlns: '%s' is not a valid URI\n",
+					   URL, NULL, NULL);
 		    } else {
 			if (uri->scheme == NULL) {
-			    xmlWarningMsg(ctxt, XML_WAR_NS_URI_RELATIVE,
-				   "xmlns: URI %s is not absolute\n",
-				          URL, NULL);
+			    xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE,
+				      "xmlns: URI %s is not absolute\n",
+				      URL, NULL, NULL);
 			}
 			xmlFreeURI(uri);
 		    }
+		    if (URL == ctxt->str_xml_ns) {
+			if (attname != ctxt->str_xml) {
+			    xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
+			 "xml namespace URI cannot be the default namespace\n",
+				     NULL, NULL, NULL);
+			}
+			goto skip_default_ns;
+		    }
+		    if ((len == 29) &&
+			(xmlStrEqual(URL,
+				 BAD_CAST "http://www.w3.org/2000/xmlns/"))) {
+			xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
+			     "reuse of the xmlns namespace name is forbidden\n",
+				 NULL, NULL, NULL);
+			goto skip_default_ns;
+		    }
 		}
 		/*
 		 * check that it's not a defined namespace
@@ -8025,6 +8749,7 @@
 		    xmlErrAttributeDup(ctxt, NULL, attname);
 		else
 		    if (nsPush(ctxt, NULL, URL) > 0) nbNs++;
+skip_default_ns:
 		if (alloc != 0) xmlFree(attvalue);
 		SKIP_BLANKS;
 		continue;
@@ -8042,22 +8767,49 @@
 		    /*
 		     * Do not keep a namespace definition node
 		     */
-		    if (alloc != 0) xmlFree(attvalue);
-		    SKIP_BLANKS;
-		    continue;
+		    goto skip_ns;
 		}
-		uri = xmlParseURI((const char *) URL);
-		if (uri == NULL) {
-		    xmlWarningMsg(ctxt, XML_WAR_NS_URI,
-			 "xmlns:%s: '%s' is not a valid URI\n",
-				       attname, URL);
-		} else {
-		    if ((ctxt->pedantic) && (uri->scheme == NULL)) {
-			xmlWarningMsg(ctxt, XML_WAR_NS_URI_RELATIVE,
-				      "xmlns:%s: URI %s is not absolute\n",
-			              attname, URL);
+                if (URL == ctxt->str_xml_ns) {
+		    if (attname != ctxt->str_xml) {
+		        xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
+			         "xml namespace URI mapped to wrong prefix\n",
+			         NULL, NULL, NULL);
 		    }
-		    xmlFreeURI(uri);
+		    goto skip_ns;
+		}
+                if (attname == ctxt->str_xmlns) {
+		    xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
+			     "redefinition of the xmlns prefix is forbidden\n",
+			     NULL, NULL, NULL);
+		    goto skip_ns;
+		}
+		if ((len == 29) &&
+		    (xmlStrEqual(URL,
+		                 BAD_CAST "http://www.w3.org/2000/xmlns/"))) {
+		    xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
+			     "reuse of the xmlns namespace name is forbidden\n",
+			     NULL, NULL, NULL);
+		    goto skip_ns;
+		}
+		if ((URL == NULL) || (URL[0] == 0)) {
+		    xmlNsErr(ctxt, XML_NS_ERR_XML_NAMESPACE,
+		             "xmlns:%s: Empty XML namespace is not allowed\n",
+			          attname, NULL, NULL);
+		    goto skip_ns;
+		} else {
+		    uri = xmlParseURI((const char *) URL);
+		    if (uri == NULL) {
+			xmlNsErr(ctxt, XML_WAR_NS_URI,
+			     "xmlns:%s: '%s' is not a valid URI\n",
+					   attname, URL, NULL);
+		    } else {
+			if ((ctxt->pedantic) && (uri->scheme == NULL)) {
+			    xmlNsWarn(ctxt, XML_WAR_NS_URI_RELATIVE,
+				      "xmlns:%s: URI %s is not absolute\n",
+				      attname, URL, NULL);
+			}
+			xmlFreeURI(uri);
+		    }
 		}
 
 		/*
@@ -8070,6 +8822,7 @@
 		    xmlErrAttributeDup(ctxt, aprefix, attname);
 		else
 		    if (nsPush(ctxt, attname, URL) > 0) nbNs++;
+skip_ns:
 		if (alloc != 0) xmlFree(attvalue);
 		SKIP_BLANKS;
 		if (ctxt->input->base != base) goto base_changed;
@@ -8104,7 +8857,7 @@
 		xmlFree(attvalue);
 	}
 
-failed:     
+failed:
 
 	GROW
 	if (ctxt->input->base != base) goto base_changed;
@@ -8135,8 +8888,8 @@
 	defaults = xmlHashLookup2(ctxt->attsDefault, localname, prefix);
 	if (defaults != NULL) {
 	    for (i = 0;i < defaults->nbAttrs;i++) {
-	        attname = defaults->values[4 * i];
-		aprefix = defaults->values[4 * i + 1];
+	        attname = defaults->values[5 * i];
+		aprefix = defaults->values[5 * i + 1];
 
                 /*
 		 * special work for namespaces defaulted defs
@@ -8151,9 +8904,9 @@
 	            if (j <= nbNs) continue;
 
 		    nsname = xmlGetNamespace(ctxt, NULL);
-		    if (nsname != defaults->values[4 * i + 2]) {
+		    if (nsname != defaults->values[5 * i + 2]) {
 			if (nsPush(ctxt, NULL,
-			           defaults->values[4 * i + 2]) > 0)
+			           defaults->values[5 * i + 2]) > 0)
 			    nbNs++;
 		    }
 		} else if (aprefix == ctxt->str_xmlns) {
@@ -8168,7 +8921,7 @@
 		    nsname = xmlGetNamespace(ctxt, attname);
 		    if (nsname != defaults->values[2]) {
 			if (nsPush(ctxt, attname,
-			           defaults->values[4 * i + 2]) > 0)
+			           defaults->values[5 * i + 2]) > 0)
 			    nbNs++;
 		    }
 		} else {
@@ -8194,8 +8947,14 @@
 			atts[nbatts++] = NULL;
 		    else
 		        atts[nbatts++] = xmlGetNamespace(ctxt, aprefix);
-		    atts[nbatts++] = defaults->values[4 * i + 2];
-		    atts[nbatts++] = defaults->values[4 * i + 3];
+		    atts[nbatts++] = defaults->values[5 * i + 2];
+		    atts[nbatts++] = defaults->values[5 * i + 3];
+		    if ((ctxt->standalone == 1) &&
+		        (defaults->values[5 * i + 4] != NULL)) {
+			xmlValidityError(ctxt, XML_DTD_STANDALONE_DEFAULTED, 
+	  "standalone: attribute %s on %s defaulted from external subset\n",
+	                                 attname, localname);
+		    }
 		    nbdef++;
 		}
 	    }
@@ -8578,10 +9337,11 @@
     xmlNodePtr ret;
     int nsNr = ctxt->nsNr;
 
-    if ((unsigned int) ctxt->nameNr > xmlParserMaxDepth) {
-        xmlFatalErrMsgInt(ctxt, XML_ERR_INTERNAL_ERROR,
-	      "Excessive depth in document: change xmlParserMaxDepth = %d\n",
-	                  xmlParserMaxDepth);
+    if (((unsigned int) ctxt->nameNr > xmlParserMaxDepth) &&
+        ((ctxt->options & XML_PARSE_HUGE) == 0)) {
+	xmlFatalErrMsgInt(ctxt, XML_ERR_INTERNAL_ERROR,
+		 "Excessive depth in document: %d use XML_PARSE_HUGE option\n",
+			  xmlParserMaxDepth);
 	ctxt->instate = XML_PARSER_EOF;
 	return;
     }
@@ -8735,7 +9495,9 @@
  *
  * parse the XML version value.
  *
- * [26] VersionNum ::= ([a-zA-Z0-9_.:] | '-')+
+ * [26] VersionNum ::= '1.' [0-9]+
+ *
+ * In practice allow [0-9].[0-9]+ at that level
  *
  * Returns the string giving the XML version number, or NULL
  */
@@ -8752,17 +9514,28 @@
 	return(NULL);
     }
     cur = CUR;
-    while (((cur >= 'a') && (cur <= 'z')) ||
-           ((cur >= 'A') && (cur <= 'Z')) ||
-           ((cur >= '0') && (cur <= '9')) ||
-           (cur == '_') || (cur == '.') ||
-	   (cur == ':') || (cur == '-')) {
+    if (!((cur >= '0') && (cur <= '9'))) {
+	xmlFree(buf);
+	return(NULL);
+    }
+    buf[len++] = cur;
+    NEXT;
+    cur=CUR;
+    if (cur != '.') {
+	xmlFree(buf);
+	return(NULL);
+    }
+    buf[len++] = cur;
+    NEXT;
+    cur=CUR;
+    while ((cur >= '0') && (cur <= '9')) {
 	if (len + 1 >= size) {
 	    xmlChar *tmp;
 
 	    size *= 2;
 	    tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
 	    if (tmp == NULL) {
+	        xmlFree(buf);
 		xmlErrMemory(ctxt, NULL);
 		return(NULL);
 	    }
@@ -8779,11 +9552,11 @@
 /**
  * xmlParseVersionInfo:
  * @ctxt:  an XML parser context
- * 
+ *
  * parse the XML version.
  *
  * [24] VersionInfo ::= S 'version' Eq (' VersionNum ' | " VersionNum ")
- * 
+ *
  * [25] Eq ::= S? '=' S?
  *
  * Returns the version string, e.g. "1.0"
@@ -8848,7 +9621,7 @@
 	    xmlErrMemory(ctxt, NULL);
 	    return(NULL);
 	}
-	
+
 	buf[len++] = cur;
 	NEXT;
 	cur = CUR;
@@ -8936,6 +9709,18 @@
         if ((encoding != NULL) &&
 	    ((!xmlStrcasecmp(encoding, BAD_CAST "UTF-16")) ||
 	     (!xmlStrcasecmp(encoding, BAD_CAST "UTF16")))) {
+	    /*
+	     * If no encoding was passed to the parser, that we are
+	     * using UTF-16 and no decoder is present i.e. the 
+	     * document is apparently UTF-8 compatible, then raise an
+	     * encoding mismatch fatal error
+	     */
+	    if ((ctxt->encoding == NULL) &&
+	        (ctxt->input->buf != NULL) &&
+	        (ctxt->input->buf->encoder == NULL)) {
+		xmlFatalErrMsg(ctxt, XML_ERR_INVALID_ENCODING,
+		  "Document labelled UTF-16 but has UTF-8 content\n");
+	    }
 	    if (ctxt->encoding != NULL)
 		xmlFree((xmlChar *) ctxt->encoding);
 	    ctxt->encoding = encoding;
@@ -9094,11 +9879,23 @@
     } else {
 	if (!xmlStrEqual(version, (const xmlChar *) XML_DEFAULT_VERSION)) {
 	    /*
-	     * TODO: Blueberry should be detected here
+	     * Changed here for XML-1.0 5th edition
 	     */
-	    xmlWarningMsg(ctxt, XML_WAR_UNKNOWN_VERSION,
-		          "Unsupported version '%s'\n",
-			  version, NULL);
+	    if (ctxt->options & XML_PARSE_OLD10) {
+		xmlFatalErrMsgStr(ctxt, XML_ERR_UNKNOWN_VERSION,
+			          "Unsupported version '%s'\n",
+			          version);
+	    } else {
+	        if ((version[0] == '1') && ((version[1] == '.'))) {
+		    xmlWarningMsg(ctxt, XML_WAR_UNKNOWN_VERSION,
+		                  "Unsupported version '%s'\n",
+				  version, NULL);
+		} else {
+		    xmlFatalErrMsgStr(ctxt, XML_ERR_UNKNOWN_VERSION,
+				      "Unsupported version '%s'\n",
+				      version);
+		}
+	    }
 	}
 	if (ctxt->version != NULL)
 	    xmlFree((void *) ctxt->version);
@@ -9332,6 +10129,15 @@
 	ctxt->myDoc = NULL;
     }
 
+    if ((ctxt->wellFormed) && (ctxt->myDoc != NULL)) {
+        ctxt->myDoc->properties |= XML_DOC_WELLFORMED;
+	if (ctxt->valid)
+	    ctxt->myDoc->properties |= XML_DOC_DTDVALID;
+	if (ctxt->nsWellFormed)
+	    ctxt->myDoc->properties |= XML_DOC_NSVALID;
+	if (ctxt->options & XML_PARSE_OLD10)
+	    ctxt->myDoc->properties |= XML_DOC_OLD10;
+    }
     if (! ctxt->wellFormed) {
 	ctxt->valid = 0;
 	return(-1);
@@ -10163,7 +10969,20 @@
 			ctxt->input->cur += tmp;
 			goto encoding_error;
 		    }
-		    if ((ctxt->sax != NULL) && (base > 0) &&
+		    if ((ctxt->sax != NULL) && (base == 0) &&
+		        (ctxt->sax->cdataBlock != NULL) &&
+		        (!ctxt->disableSAX)) {
+			/*
+			 * Special case to provide identical behaviour
+			 * between pull and push parsers on enpty CDATA
+			 * sections
+			 */
+			 if ((ctxt->input->cur - ctxt->input->base >= 9) &&
+			     (!strncmp((const char *)&ctxt->input->cur[-9],
+			               "<![CDATA[", 9)))
+			     ctxt->sax->cdataBlock(ctxt->userData,
+			                           BAD_CAST "", 0);
+		    } else if ((ctxt->sax != NULL) && (base > 0) &&
 			(!ctxt->disableSAX)) {
 			if (ctxt->sax->cdataBlock != NULL)
 			    ctxt->sax->cdataBlock(ctxt->userData,
@@ -10963,7 +11782,11 @@
     /*
      * plug some encoding conversion routines here.
      */
-    xmlPushInput(ctxt, pinput);
+    if (xmlPushInput(ctxt, pinput) < 0) {
+        if (sax != NULL) ctxt->sax = NULL;
+	xmlFreeParserCtxt(ctxt);
+	return(NULL);
+    }
     if (enc != XML_CHAR_ENCODING_NONE) {
         xmlSwitchEncoding(ctxt, enc);
     }
@@ -10980,6 +11803,11 @@
      */
     ctxt->inSubset = 2;
     ctxt->myDoc = xmlNewDoc(BAD_CAST "1.0");
+    if (ctxt->myDoc == NULL) {
+	xmlErrMemory(ctxt, "New Doc failed");
+	return(NULL);
+    }
+    ctxt->myDoc->properties = XML_DOC_INTERNAL;
     ctxt->myDoc->extSubset = xmlNewDtd(ctxt->myDoc, BAD_CAST "none",
 	                               BAD_CAST "none", BAD_CAST "none");
 
@@ -11092,7 +11920,13 @@
     /*
      * plug some encoding conversion routines here.
      */
-    xmlPushInput(ctxt, input);
+    if (xmlPushInput(ctxt, input) < 0) {
+        if (sax != NULL) ctxt->sax = NULL;
+	xmlFreeParserCtxt(ctxt);
+	if (systemIdCanonic != NULL)
+	    xmlFree(systemIdCanonic);
+	return(NULL);
+    }
     if ((ctxt->input->end - ctxt->input->cur) >= 4) {
 	enc = xmlDetectCharEncoding(ctxt->input->cur, 4);
 	xmlSwitchEncoding(ctxt, enc);
@@ -11113,6 +11947,13 @@
      */
     ctxt->inSubset = 2;
     ctxt->myDoc = xmlNewDoc(BAD_CAST "1.0");
+    if (ctxt->myDoc == NULL) {
+	xmlErrMemory(ctxt, "New Doc failed");
+        if (sax != NULL) ctxt->sax = NULL;
+	xmlFreeParserCtxt(ctxt);
+	return(NULL);
+    }
+    ctxt->myDoc->properties = XML_DOC_INTERNAL;
     ctxt->myDoc->extSubset = xmlNewDtd(ctxt->myDoc, BAD_CAST "none",
 	                               ExternalID, SystemID);
     xmlParseExternalSubset(ctxt, ExternalID, SystemID);
@@ -11139,7 +11980,7 @@
     }
     if (sax != NULL) ctxt->sax = NULL;
     xmlFreeParserCtxt(ctxt);
-    
+
     return(ret);
 }
 
@@ -11150,7 +11991,7 @@
  * @SystemID:  a NAME* containing the URL to the DTD
  *
  * Load and parse an external subset.
- * 
+ *
  * Returns the resulting xmlDtdPtr or NULL in case of error.
  */
 
@@ -11198,7 +12039,8 @@
 
     if (ctx == NULL) return(-1);
 
-    if (ctx->depth > 40) {
+    if (((ctx->depth > 40) && ((ctx->options & XML_PARSE_HUGE) == 0)) ||
+        (ctx->depth > 1024)) {
 	return(XML_ERR_ENTITY_LOOP);
     }
 
@@ -11213,10 +12055,10 @@
     if (ctxt == NULL) {
 	return(-1);
     }
-    
+
     ctxt->userData = ctxt;
     ctxt->_private = ctx->_private;
-    
+
     inputStream = xmlLoadExternalEntity((char *)URL, (char *)ID, ctxt);
     if (inputStream == NULL) {
 	xmlFreeParserCtxt(ctxt);
@@ -11229,7 +12071,7 @@
 	directory = xmlParserGetDirectory((char *)URL);
     if ((ctxt->directory == NULL) && (directory != NULL))
 	ctxt->directory = directory;
-    
+
     oldsax = ctxt->sax;
     ctxt->sax = ctx->sax;
     xmlDetectSAX2(ctxt);
@@ -11238,6 +12080,7 @@
 	xmlFreeParserCtxt(ctxt);
 	return(-1);
     }
+    newDoc->properties = XML_DOC_INTERNAL;
     if (ctx->myDoc->dict) {
 	newDoc->dict = ctx->myDoc->dict;
 	xmlDictReference(newDoc->dict);
@@ -11267,7 +12110,7 @@
 	newDoc->children->doc = ctx->myDoc;
     }
 
-    /* 
+    /*
      * Get the 4 first bytes and decode the charset
      * if enc != XML_CHAR_ENCODING_NONE
      * plug some encoding conversion routines.
@@ -11289,6 +12132,14 @@
      */
     if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) {
 	xmlParseTextDecl(ctxt);
+	/*
+	 * An XML-1.0 document can't reference an entity not XML-1.0
+	 */
+	if ((xmlStrEqual(ctx->version, BAD_CAST "1.0")) &&
+	    (!xmlStrEqual(ctxt->input->version, BAD_CAST "1.0"))) {
+	    xmlFatalErrMsg(ctxt, XML_ERR_VERSION_MISMATCH, 
+	                   "Version mismatch between document and entity\n");
+	}
     }
 
     /*
@@ -11322,7 +12173,7 @@
     ctxt->linenumbers = ctx->linenumbers;
 
     xmlParseContent(ctxt);
-   
+
     ctx->validate = ctxt->validate;
     ctx->valid = ctxt->valid;
     if ((RAW == '<') && (NXT(1) == '/')) {
@@ -11365,7 +12216,7 @@
     newDoc->intSubset = NULL;
     newDoc->extSubset = NULL;
     xmlFreeDoc(newDoc);
-    
+
     return(ret);
 }
 
@@ -11399,12 +12250,12 @@
     xmlChar start[4];
     xmlCharEncoding enc;
 
-    if (depth > 40) {
+    if (((depth > 40) &&
+	((oldctxt == NULL) || (oldctxt->options & XML_PARSE_HUGE) == 0)) ||
+	(depth > 1024)) {
 	return(XML_ERR_ENTITY_LOOP);
     }
 
-
-
     if (list != NULL)
         *list = NULL;
     if ((URL == NULL) && (ID == NULL))
@@ -11450,6 +12301,7 @@
 	xmlFreeParserCtxt(ctxt);
 	return(XML_ERR_INTERNAL_ERROR);
     }
+    newDoc->properties = XML_DOC_INTERNAL;
     newDoc->intSubset = doc->intSubset;
     newDoc->extSubset = doc->extSubset;
     newDoc->dict = doc->dict;
@@ -11476,7 +12328,7 @@
     ctxt->myDoc = doc;
     newRoot->doc = doc;
 
-    /* 
+    /*
      * Get the 4 first bytes and decode the charset
      * if enc != XML_CHAR_ENCODING_NONE
      * plug some encoding conversion routines.
@@ -11504,7 +12356,7 @@
     ctxt->depth = depth;
 
     xmlParseContent(ctxt);
-   
+
     if ((RAW == '<') && (NXT(1) == '/')) {
 	xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL);
     } else if (RAW != 0) {
@@ -11537,6 +12389,25 @@
 	}
 	ret = XML_ERR_OK;
     }
+
+    /*
+     * Record in the parent context the number of entities replacement
+     * done when parsing that reference.
+     */
+    oldctxt->nbentities += ctxt->nbentities;
+    /*
+     * Also record the size of the entity parsed
+     */
+    if (ctxt->input != NULL) {
+	oldctxt->sizeentities += ctxt->input->consumed;
+	oldctxt->sizeentities += (ctxt->input->cur - ctxt->input->base);
+    }
+    /*
+     * And record the last error if any
+     */
+    if (ctxt->lastError.code != XML_ERR_OK)
+        xmlCopyError(&ctxt->lastError, &oldctxt->lastError);
+
     if (sax != NULL) 
 	ctxt->sax = oldsax;
     oldctxt->node_seq.maximum = ctxt->node_seq.maximum;
@@ -11549,7 +12420,7 @@
     newDoc->intSubset = NULL;
     newDoc->extSubset = NULL;
     xmlFreeDoc(newDoc);
-    
+
     return(ret);
 }
 
@@ -11626,9 +12497,9 @@
  *
  * Returns XML_ERR_OK if the chunk is well balanced, and the parser
  * error code otherwise
- *    
+ *
  * In case recover is set to 1, the nodelist will not be empty even if
- * the parsed chunk is not well balanced. 
+ * the parsed chunk is not well balanced.
  */
 static xmlParserErrors
 xmlParseBalancedChunkMemoryInternal(xmlParserCtxtPtr oldctxt,
@@ -11642,7 +12513,8 @@
     int size;
     xmlParserErrors ret = XML_ERR_OK;
 
-    if (oldctxt->depth > 40) {
+    if (((oldctxt->depth > 40) && ((oldctxt->options & XML_PARSE_HUGE) == 0)) ||
+        (oldctxt->depth >  1024)) {
 	return(XML_ERR_ENTITY_LOOP);
     }
 
@@ -11671,7 +12543,7 @@
     xmlDetectSAX2(ctxt);
     ctxt->replaceEntities = oldctxt->replaceEntities;
     ctxt->options = oldctxt->options;
-    
+
     ctxt->_private = oldctxt->_private;
     if (oldctxt->myDoc == NULL) {
 	newDoc = xmlNewDoc(BAD_CAST "1.0");
@@ -11681,6 +12553,7 @@
 	    xmlFreeParserCtxt(ctxt);
 	    return(XML_ERR_INTERNAL_ERROR);
 	}
+	newDoc->properties = XML_DOC_INTERNAL;
 	newDoc->dict = ctxt->dict;
 	xmlDictReference(newDoc->dict);
 	ctxt->myDoc = newDoc;
@@ -11736,7 +12609,7 @@
     } else {
       ret = XML_ERR_OK;
     }
-    
+
     if ((lst != NULL) && (ret == XML_ERR_OK)) {
 	xmlNodePtr cur;
 
@@ -11765,7 +12638,18 @@
         ctxt->myDoc->children = content;
         ctxt->myDoc->last = last;
     }
-	
+
+    /*
+     * Record in the parent context the number of entities replacement
+     * done when parsing that reference.
+     */
+    oldctxt->nbentities += ctxt->nbentities;
+    /*
+     * Also record the last error if any
+     */
+    if (ctxt->lastError.code != XML_ERR_OK)
+        xmlCopyError(&ctxt->lastError, &oldctxt->lastError);
+
     ctxt->sax = oldsax;
     ctxt->dict = NULL;
     ctxt->attsDefault = NULL;
@@ -11774,7 +12658,7 @@
     if (newDoc != NULL) {
 	xmlFreeDoc(newDoc);
     }
-    
+
     return(ret);
 }
 
@@ -11875,7 +12759,7 @@
     } else
         options |= XML_PARSE_NODICT;
 
-    xmlCtxtUseOptions(ctxt, options);
+    xmlCtxtUseOptionsInternal(ctxt, options, NULL);
     xmlDetectSAX2(ctxt);
     ctxt->myDoc = doc;
 
@@ -11907,7 +12791,7 @@
 	    cur = cur->parent;
 	}
 	ctxt->instate = XML_PARSER_CONTENT;
-    } 
+    }
 
     if ((ctxt->validate) || (ctxt->replaceEntities != 0)) {
 	/*
@@ -11942,12 +12826,12 @@
     } else {
         ret = XML_ERR_OK;
     }
-    
+
     /*
      * Return the newly created nodeset after unlinking it from
      * the pseudo sibling.
      */
-    
+
     cur = fake->next;
     fake->next = NULL;
     node->last = fake;
@@ -11975,7 +12859,7 @@
     if (doc->dict != NULL)
         ctxt->dict = NULL;
     xmlFreeParserCtxt(ctxt);
-    
+
     return(ret);
 #else /* !SAX2 */
     return(XML_ERR_INTERNAL_ERROR);
@@ -12003,13 +12887,14 @@
  *
  * Returns 0 if the chunk is well balanced, -1 in case of args problem and
  *    the parser error code otherwise
- *    
+ *
  * In case recover is set to 1, the nodelist will not be empty even if
- * the parsed chunk is not well balanced. 
+ * the parsed chunk is not well balanced, assuming the parsing succeeded to
+ * some extent.
  */
 int
 xmlParseBalancedChunkMemoryRecover(xmlDocPtr doc, xmlSAXHandlerPtr sax,
-     void *user_data, int depth, const xmlChar *string, xmlNodePtr *lst, 
+     void *user_data, int depth, const xmlChar *string, xmlNodePtr *lst,
      int recover) {
     xmlParserCtxtPtr ctxt;
     xmlDocPtr newDoc;
@@ -12044,6 +12929,7 @@
 	xmlFreeParserCtxt(ctxt);
 	return(-1);
     }
+    newDoc->properties = XML_DOC_INTERNAL;
     if ((doc != NULL) && (doc->dict != NULL)) {
         xmlDictFree(ctxt->dict);
 	ctxt->dict = doc->dict;
@@ -12053,7 +12939,7 @@
 	ctxt->str_xml_ns = xmlDictLookup(ctxt->dict, XML_XML_NAMESPACE, 36);
 	ctxt->dictNames = 1;
     } else {
-	xmlCtxtUseOptions(ctxt, XML_PARSE_NODICT);
+	xmlCtxtUseOptionsInternal(ctxt, XML_PARSE_NODICT, NULL);
     }
     if (doc != NULL) {
 	newDoc->intSubset = doc->intSubset;
@@ -12116,7 +13002,7 @@
     } else {
       ret = 0;
     }
-    
+
     if ((lst != NULL) && ((ret == 0) || (recover == 1))) {
 	xmlNodePtr cur;
 
@@ -12133,15 +13019,15 @@
 	}
 	newDoc->children->children = NULL;
     }
-	
-    if (sax != NULL) 
+
+    if (sax != NULL)
 	ctxt->sax = oldsax;
     xmlFreeParserCtxt(ctxt);
     newDoc->intSubset = NULL;
     newDoc->extSubset = NULL;
     newDoc->oldNs = NULL;
     xmlFreeDoc(newDoc);
-    
+
     return(ret);
 }
 
@@ -12189,7 +13075,7 @@
     if (sax != NULL)
         ctxt->sax = NULL;
     xmlFreeParserCtxt(ctxt);
-    
+
     return(ret);
 }
 
@@ -12231,7 +13117,7 @@
     xmlParserInputPtr inputStream;
     char *directory = NULL;
     xmlChar *uri;
-    
+
     ctxt = xmlNewParserCtxt();
     if (ctxt == NULL) {
 	return(NULL);
@@ -12273,7 +13159,7 @@
 
 /************************************************************************
  *									*
- * 		Front ends when parsing from a file			*
+ *		Front ends when parsing from a file			*
  *									*
  ************************************************************************/
 
@@ -12302,9 +13188,9 @@
     }
 
     if (options)
-	xmlCtxtUseOptions(ctxt, options);
+	xmlCtxtUseOptionsInternal(ctxt, options, NULL);
     ctxt->linenumbers = 1;
-    
+
     inputStream = xmlLoadExternalEntity(filename, NULL, ctxt);
     if (inputStream == NULL) {
 	xmlFreeParserCtxt(ctxt);
@@ -12361,7 +13247,6 @@
                         int recovery, void *data) {
     xmlDocPtr ret;
     xmlParserCtxtPtr ctxt;
-    char *directory = NULL;
 
     xmlInitParser();
 
@@ -12379,10 +13264,8 @@
 	ctxt->_private = data;
     }
 
-    if ((ctxt->directory == NULL) && (directory == NULL))
-        directory = xmlParserGetDirectory(filename);
-    if ((ctxt->directory == NULL) && (directory != NULL))
-        ctxt->directory = (char *) xmlStrdup((xmlChar *) directory);
+    if (ctxt->directory == NULL)
+        ctxt->directory = xmlParserGetDirectory(filename);
 
     ctxt->recovery = recovery;
 
@@ -12435,9 +13318,10 @@
  * @cur:  a pointer to an array of xmlChar
  *
  * parse an XML in-memory document and build a tree.
- * In the case the document is not Well Formed, a tree is built anyway
- * 
- * Returns the resulting document tree
+ * In the case the document is not Well Formed, a attempt to build a
+ * tree is tried anyway
+ *
+ * Returns the resulting document tree or NULL in case of failure
  */
 
 xmlDocPtr
@@ -12467,9 +13351,10 @@
  *
  * parse an XML file and build a tree. Automatic support for ZLIB/Compress
  * compressed document is provided by default if found at compile-time.
- * In the case the document is not Well Formed, a tree is built anyway
+ * In the case the document is not Well Formed, it attempts to build
+ * a tree anyway
  *
- * Returns the resulting document tree
+ * Returns the resulting document tree or NULL in case of failure
  */
 
 xmlDocPtr
@@ -12711,9 +13596,10 @@
  * @size:  the size of the array
  *
  * parse an XML in-memory block and build a tree.
- * In the case the document is not Well Formed, a tree is built anyway
- * 
- * Returns the resulting document tree
+ * In the case the document is not Well Formed, an attempt to
+ * build a tree is tried anyway
+ *
+ * Returns the resulting document tree or NULL in case of error
  */
 
 xmlDocPtr xmlRecoverMemory(const char *buffer, int size) {
@@ -12949,12 +13835,15 @@
 /**
  * xmlCleanupParser:
  *
- * Cleanup function for the XML library. It tries to reclaim all
- * parsing related global memory allocated for the library processing.
- * It doesn't deallocate any document related memory. Calling this
- * function should not prevent reusing the library but one should
- * call xmlCleanupParser() only when the process has
- * finished using the library or XML document built with it.
+ * This function name is somewhat misleading. It does not clean up
+ * parser state, it cleans up memory allocated by the library itself.
+ * It is a cleanup function for the XML library. It tries to reclaim all
+ * related global memory allocated for the library processing.
+ * It doesn't deallocate any document related memory. One should
+ * call xmlCleanupParser() only when the process has finished using
+ * the library and all XML/HTML documents built with it.
+ * See also xmlInitParser() which has the opposite function of preparing
+ * the library for operations.
  */
 
 void
@@ -13077,6 +13966,8 @@
     ctxt->depth = 0;
     ctxt->charset = XML_CHAR_ENCODING_UTF8;
     ctxt->catalogs = NULL;
+    ctxt->nbentities = 0;
+    ctxt->sizeentities = 0;
     xmlInitNodeInfoSeq(&ctxt->node_seq);
 
     if (ctxt->attsDefault != NULL) {
@@ -13188,6 +14079,10 @@
     if (encoding != NULL) {
         xmlCharEncodingHandlerPtr hdlr;
 
+        if (ctxt->encoding != NULL)
+	    xmlFree((xmlChar *) ctxt->encoding);
+        ctxt->encoding = xmlStrdup((const xmlChar *) encoding);
+
         hdlr = xmlFindCharEncodingHandler(encoding);
         if (hdlr != NULL) {
             xmlSwitchToEncoding(ctxt, hdlr);
@@ -13202,50 +14097,63 @@
     return(0);
 }
 
+
 /**
- * xmlCtxtUseOptions:
+ * xmlCtxtUseOptionsInternal:
  * @ctxt: an XML parser context
  * @options:  a combination of xmlParserOption
+ * @encoding:  the user provided encoding to use
  *
  * Applies the options to the parser context
  *
  * Returns 0 in case of success, the set of unknown or unimplemented options
  *         in case of error.
  */
-int
-xmlCtxtUseOptions(xmlParserCtxtPtr ctxt, int options)
+static int
+xmlCtxtUseOptionsInternal(xmlParserCtxtPtr ctxt, int options, const char *encoding)
 {
     if (ctxt == NULL)
         return(-1);
+    if (encoding != NULL) {
+        if (ctxt->encoding != NULL)
+	    xmlFree((xmlChar *) ctxt->encoding);
+        ctxt->encoding = xmlStrdup((const xmlChar *) encoding);
+    }
     if (options & XML_PARSE_RECOVER) {
         ctxt->recovery = 1;
         options -= XML_PARSE_RECOVER;
+	ctxt->options |= XML_PARSE_RECOVER;
     } else
         ctxt->recovery = 0;
     if (options & XML_PARSE_DTDLOAD) {
         ctxt->loadsubset = XML_DETECT_IDS;
         options -= XML_PARSE_DTDLOAD;
+	ctxt->options |= XML_PARSE_DTDLOAD;
     } else
         ctxt->loadsubset = 0;
     if (options & XML_PARSE_DTDATTR) {
         ctxt->loadsubset |= XML_COMPLETE_ATTRS;
         options -= XML_PARSE_DTDATTR;
+	ctxt->options |= XML_PARSE_DTDATTR;
     }
     if (options & XML_PARSE_NOENT) {
         ctxt->replaceEntities = 1;
         /* ctxt->loadsubset |= XML_DETECT_IDS; */
         options -= XML_PARSE_NOENT;
+	ctxt->options |= XML_PARSE_NOENT;
     } else
         ctxt->replaceEntities = 0;
     if (options & XML_PARSE_PEDANTIC) {
         ctxt->pedantic = 1;
         options -= XML_PARSE_PEDANTIC;
+	ctxt->options |= XML_PARSE_PEDANTIC;
     } else
         ctxt->pedantic = 0;
     if (options & XML_PARSE_NOBLANKS) {
         ctxt->keepBlanks = 0;
         ctxt->sax->ignorableWhitespace = xmlSAX2IgnorableWhitespace;
         options -= XML_PARSE_NOBLANKS;
+	ctxt->options |= XML_PARSE_NOBLANKS;
     } else
         ctxt->keepBlanks = 1;
     if (options & XML_PARSE_DTDVALID) {
@@ -13255,6 +14163,7 @@
         if (options & XML_PARSE_NOERROR)
             ctxt->vctxt.error = NULL;
         options -= XML_PARSE_DTDVALID;
+	ctxt->options |= XML_PARSE_DTDVALID;
     } else
         ctxt->validate = 0;
     if (options & XML_PARSE_NOWARNING) {
@@ -13274,17 +14183,20 @@
         ctxt->sax->endElementNs = NULL;
         ctxt->sax->initialized = 1;
         options -= XML_PARSE_SAX1;
+	ctxt->options |= XML_PARSE_SAX1;
     }
 #endif /* LIBXML_SAX1_ENABLED */
     if (options & XML_PARSE_NODICT) {
         ctxt->dictNames = 0;
         options -= XML_PARSE_NODICT;
+	ctxt->options |= XML_PARSE_NODICT;
     } else {
         ctxt->dictNames = 1;
     }
     if (options & XML_PARSE_NOCDATA) {
         ctxt->sax->cdataBlock = NULL;
         options -= XML_PARSE_NOCDATA;
+	ctxt->options |= XML_PARSE_NOCDATA;
     }
     if (options & XML_PARSE_NSCLEAN) {
 	ctxt->options |= XML_PARSE_NSCLEAN;
@@ -13298,11 +14210,43 @@
 	ctxt->options |= XML_PARSE_COMPACT;
         options -= XML_PARSE_COMPACT;
     }
+    if (options & XML_PARSE_OLD10) {
+	ctxt->options |= XML_PARSE_OLD10;
+        options -= XML_PARSE_OLD10;
+    }
+    if (options & XML_PARSE_NOBASEFIX) {
+	ctxt->options |= XML_PARSE_NOBASEFIX;
+        options -= XML_PARSE_NOBASEFIX;
+    }
+    if (options & XML_PARSE_HUGE) {
+	ctxt->options |= XML_PARSE_HUGE;
+        options -= XML_PARSE_HUGE;
+    }
+    if (options & XML_PARSE_OLDSAX) {
+	ctxt->options |= XML_PARSE_OLDSAX;
+        options -= XML_PARSE_OLDSAX;
+    }
     ctxt->linenumbers = 1;
     return (options);
 }
 
 /**
+ * xmlCtxtUseOptions:
+ * @ctxt: an XML parser context
+ * @options:  a combination of xmlParserOption
+ *
+ * Applies the options to the parser context
+ *
+ * Returns 0 in case of success, the set of unknown or unimplemented options
+ *         in case of error.
+ */
+int
+xmlCtxtUseOptions(xmlParserCtxtPtr ctxt, int options)
+{
+   return(xmlCtxtUseOptionsInternal(ctxt, options, NULL));
+}
+
+/**
  * xmlDoRead:
  * @ctxt:  an XML parser context
  * @URL:  the base URL to use for the document
@@ -13311,7 +14255,7 @@
  * @reuse:  keep the context for reuse
  *
  * Common front-end for the xmlRead functions
- * 
+ *
  * Returns the resulting document tree or NULL
  */
 static xmlDocPtr
@@ -13319,8 +14263,8 @@
           int options, int reuse)
 {
     xmlDocPtr ret;
-    
-    xmlCtxtUseOptions(ctxt, options);
+
+    xmlCtxtUseOptionsInternal(ctxt, options, encoding);
     if (encoding != NULL) {
         xmlCharEncodingHandlerPtr hdlr;
 
diff --git a/parserInternals.c b/parserInternals.c
index d7aa4cf..758c6b3 100644
--- a/parserInternals.c
+++ b/parserInternals.c
@@ -1399,7 +1399,8 @@
     if (input == NULL) {
 	return(NULL);
     }
-    input->filename = (char *) entity->URI;
+    if (entity->URI != NULL)
+	input->filename = (char *) xmlStrdup((xmlChar *) entity->URI);
     input->base = entity->content;
     input->cur = entity->content;
     input->length = entity->length;
@@ -1669,6 +1670,7 @@
     ctxt->depth = 0;
     ctxt->charset = XML_CHAR_ENCODING_UTF8;
     ctxt->catalogs = NULL;
+    ctxt->nbentities = 0;
     xmlInitNodeInfoSeq(&ctxt->node_seq);
     return(0);
 }
diff --git a/pattern.c b/pattern.c
index ee51968..0e38c2d 100644
--- a/pattern.c
+++ b/pattern.c
@@ -2285,9 +2285,13 @@
 	if (stream->blockLevel == stream->level)
 	    stream->blockLevel = -1;
 
-	stream->level--;
-	if (stream->level < 0)
-	    return(-1);		
+	/*
+	 *  stream->level can be zero when XML_FINAL_IS_ANY_NODE is set
+	 *  (see the thread at
+	 *  http://mail.gnome.org/archives/xslt/2008-July/msg00027.html)
+	 */
+	if (stream->level)
+	    stream->level--;
 	/*
 	 * Check evolution of existing states
 	 */	
diff --git a/relaxng.c b/relaxng.c
index 60fdbab..6459769 100644
--- a/relaxng.c
+++ b/relaxng.c
@@ -6495,6 +6495,8 @@
                     ctxt);
     }
 
+    /* @@@@ */
+
     ctxt->grammar = old;
     return (ret);
 }
@@ -8812,6 +8814,8 @@
             }
         case XML_RELAXNG_REF:
         case XML_RELAXNG_PARENTREF:
+	    if (define->content == NULL) {
+	    }
             ret = xmlRelaxNGValidateValue(ctxt, define->content);
             break;
         default:
diff --git a/schematron.c b/schematron.c
index 146ffc9..03fa357 100644
--- a/schematron.c
+++ b/schematron.c
@@ -168,6 +168,12 @@
     xmlOutputWriteCallback iowrite; /* if using XML_SCHEMATRON_OUT_IO */
     xmlOutputCloseCallback  ioclose;
     void *ioctx;
+
+    /* error reporting data */
+    void *userData;                      /* user specific data block */
+    xmlSchematronValidityErrorFunc error;/* the callback in case of errors */
+    xmlSchematronValidityWarningFunc warning;/* callback in case of warning */
+    xmlStructuredErrorFunc serror;       /* the structured function */
 };
 
 struct _xmlSchematronParserCtxt {
@@ -193,12 +199,11 @@
     int maxIncludes;		/* size of the array */
     xmlNodePtr *includes;	/* the array of includes */
 
-    /* error rreporting data */
+    /* error reporting data */
     void *userData;                      /* user specific data block */
     xmlSchematronValidityErrorFunc error;/* the callback in case of errors */
     xmlSchematronValidityWarningFunc warning;/* callback in case of warning */
     xmlStructuredErrorFunc serror;       /* the structured function */
-
 };
 
 #define XML_STRON_CTXT_PARSER 1
@@ -1361,7 +1366,7 @@
  */
 static void
 xmlSchematronReportSuccess(xmlSchematronValidCtxtPtr ctxt, 
-		   xmlSchematronTestPtr test, xmlNodePtr cur, int success) {
+		   xmlSchematronTestPtr test, xmlNodePtr cur, xmlSchematronPatternPtr pattern, int success) {
     if ((ctxt == NULL) || (cur == NULL) || (test == NULL))
         return;
     /* if quiet and not SVRL report only failures */
@@ -1392,18 +1397,41 @@
             report = xmlSchematronFormatReport(ctxt, test->node, cur);
 	if (report == NULL) {
 	    if (test->type == XML_SCHEMATRON_ASSERT) {
-		snprintf(msg, 999, "%s line %ld: node failed assert\n",
-		         (const char *) path, line);
+            report = xmlStrdup((const xmlChar *) "node failed assert");
 	    } else {
-		snprintf(msg, 999, "%s line %ld: node failed report\n",
-		         (const char *) path, line);
+            report = xmlStrdup((const xmlChar *) "node failed report");
 	    }
-	} else {
+	    }
 	    snprintf(msg, 999, "%s line %ld: %s\n", (const char *) path,
 		     line, (const char *) report);
-	    xmlFree((char *) report);
+
+    if (ctxt->flags & XML_SCHEMATRON_OUT_ERROR) {
+        xmlStructuredErrorFunc schannel = NULL;
+        xmlGenericErrorFunc channel = NULL;
+        void *data = NULL;
+
+        if (ctxt != NULL) {
+            if (ctxt->serror != NULL)
+                schannel = ctxt->serror;
+            else
+                channel = ctxt->error;
+            data = ctxt->userData;
 	}
+
+        __xmlRaiseError(schannel, channel, data,
+                        NULL, cur, XML_FROM_SCHEMATRONV,
+                        (test->type == XML_SCHEMATRON_ASSERT)?XML_SCHEMATRONV_ASSERT:XML_SCHEMATRONV_REPORT,
+                        XML_ERR_ERROR, NULL, line,
+                        (pattern == NULL)?NULL:((const char *) pattern->name),
+                        (const char *) path,
+                        (const char *) report, 0, 0,
+                        msg);
+    } else {
 	xmlSchematronReportOutput(ctxt, cur, &msg[0]);
+    }
+
+    xmlFree((char *) report);
+
 	if ((path != NULL) && (path != (xmlChar *) cur->name))
 	    xmlFree(path);
     }
@@ -1421,7 +1449,7 @@
 			   xmlSchematronPatternPtr pattern) {
     if ((ctxt == NULL) || (pattern == NULL))
         return;
-    if (ctxt->flags & XML_SCHEMATRON_OUT_QUIET)
+    if ((ctxt->flags & XML_SCHEMATRON_OUT_QUIET) || (ctxt->flags & XML_SCHEMATRON_OUT_ERROR)) /* Error gives pattern name as part of error */
         return;
     if (ctxt->flags & XML_SCHEMATRON_OUT_XML) {
         TODO
@@ -1443,6 +1471,26 @@
  ************************************************************************/
 
 /**
+ * xmlSchematronSetValidStructuredErrors:
+ * @ctxt:  a Schematron validation context
+ * @serror:  the structured error function
+ * @ctx: the functions context
+ *
+ * Set the structured error callback
+ */
+void
+xmlSchematronSetValidStructuredErrors(xmlSchematronValidCtxtPtr ctxt,
+                                      xmlStructuredErrorFunc serror, void *ctx)
+{
+    if (ctxt == NULL)
+        return;
+    ctxt->serror = serror;
+    ctxt->error = NULL;
+    ctxt->warning = NULL;
+    ctxt->userData = ctx;
+}
+
+/**
  * xmlSchematronNewValidCtxt:
  * @schema:  a precompiled XML Schematrons
  * @options: a set of xmlSchematronValidOptions
@@ -1550,7 +1598,7 @@
  */
 static int
 xmlSchematronRunTest(xmlSchematronValidCtxtPtr ctxt,
-     xmlSchematronTestPtr test, xmlDocPtr instance, xmlNodePtr cur)
+     xmlSchematronTestPtr test, xmlDocPtr instance, xmlNodePtr cur, xmlSchematronPatternPtr pattern)
 {
     xmlXPathObjectPtr ret;
     int failed;
@@ -1597,7 +1645,7 @@
     else if ((!failed) && (test->type == XML_SCHEMATRON_REPORT))
         ctxt->nberrors++;
 
-    xmlSchematronReportSuccess(ctxt, test, cur, !failed);
+    xmlSchematronReportSuccess(ctxt, test, cur, pattern, !failed);
 
     return(!failed);
 }
@@ -1643,7 +1691,7 @@
 		if (xmlPatternMatch(rule->pattern, cur) == 1) {
 		    test = rule->tests;
 		    while (test != NULL) {
-			xmlSchematronRunTest(ctxt, test, instance, cur);
+			xmlSchematronRunTest(ctxt, test, instance, cur, (xmlSchematronPatternPtr)rule->pattern);
 			test = test->next;
 		    }
 		}
@@ -1674,7 +1722,7 @@
 		    if (xmlPatternMatch(rule->pattern, cur) == 1) {
 			test = rule->tests;
 			while (test != NULL) {
-			    xmlSchematronRunTest(ctxt, test, instance, cur);
+			    xmlSchematronRunTest(ctxt, test, instance, cur, pattern);
 			    test = test->next;
 			}
 		    }
diff --git a/threads.c b/threads.c
index d5a177d..2223e8a 100644
--- a/threads.c
+++ b/threads.c
@@ -1,5 +1,5 @@
 /**
- * threads.c: set of generic threading related routines 
+ * threads.c: set of generic threading related routines
  *
  * See Copyright for the status of this software.
  *
@@ -63,6 +63,8 @@
 extern int pthread_key_create (pthread_key_t *__key,
                                void (*__destr_function) (void *))
 	   __attribute((weak));
+extern int pthread_key_delete (pthread_key_t __key)
+	   __attribute((weak));
 extern int pthread_mutex_init ()
 	   __attribute((weak));
 extern int pthread_mutex_destroy ()
@@ -73,12 +75,18 @@
 	   __attribute((weak));
 extern int pthread_cond_init ()
 	   __attribute((weak));
+extern int pthread_cond_destroy ()
+	   __attribute((weak));
+extern int pthread_cond_wait ()
+	   __attribute((weak));
 extern int pthread_equal ()
 	   __attribute((weak));
 extern pthread_t pthread_self ()
 	   __attribute((weak));
 extern int pthread_key_create ()
 	   __attribute((weak));
+extern int pthread_key_delete ()
+	   __attribute((weak));
 extern int pthread_cond_signal ()
 	   __attribute((weak));
 #endif
@@ -101,8 +109,8 @@
 #elif defined HAVE_WIN32_THREADS
     HANDLE mutex;
 #elif defined HAVE_BEOS_THREADS
-	sem_id sem;
-	thread_id tid;
+    sem_id sem;
+    thread_id tid;
 #else
     int empty;
 #endif
@@ -114,21 +122,22 @@
 struct _xmlRMutex {
 #ifdef HAVE_PTHREAD_H
     pthread_mutex_t lock;
-    unsigned int    held;
-    unsigned int    waiters;
-    pthread_t       tid;
-    pthread_cond_t  cv;
+    unsigned int held;
+    unsigned int waiters;
+    pthread_t tid;
+    pthread_cond_t cv;
 #elif defined HAVE_WIN32_THREADS
     CRITICAL_SECTION cs;
     unsigned int count;
 #elif defined HAVE_BEOS_THREADS
-	xmlMutexPtr lock;
-	thread_id tid;
-	int32 count;
+    xmlMutexPtr lock;
+    thread_id tid;
+    int32 count;
 #else
     int empty;
 #endif
 };
+
 /*
  * This module still has some internal static data.
  *   - xmlLibraryLock a global lock
@@ -136,8 +145,8 @@
  */
 
 #ifdef HAVE_PTHREAD_H
-static pthread_key_t	globalkey;
-static pthread_t	mainthread;
+static pthread_key_t globalkey;
+static pthread_t mainthread;
 static pthread_once_t once_control = PTHREAD_ONCE_INIT;
 static pthread_mutex_t global_init_lock = PTHREAD_MUTEX_INITIALIZER;
 #elif defined HAVE_WIN32_THREADS
@@ -148,12 +157,12 @@
 static DWORD globalkey = TLS_OUT_OF_INDEXES;
 #endif /* HAVE_COMPILER_TLS */
 static DWORD mainthread;
-static struct
-{
+static struct {
     DWORD done;
     DWORD control;
-} run_once = { 0, 0 };
+} run_once = { 0, 0};
 static volatile LPCRITICAL_SECTION global_init_lock = NULL;
+
 /* endif HAVE_WIN32_THREADS */
 #elif defined HAVE_BEOS_THREADS
 int32 globalkey = 0;
@@ -163,7 +172,8 @@
 static vint32 global_init_count = 0;
 #endif
 
-static xmlRMutexPtr	xmlLibraryLock = NULL;
+static xmlRMutexPtr xmlLibraryLock = NULL;
+
 #ifdef LIBXML_THREAD_ENABLED
 static void xmlOnceInit(void);
 #endif
@@ -185,15 +195,15 @@
         return (NULL);
 #ifdef HAVE_PTHREAD_H
     if (libxml_is_threaded != 0)
-	pthread_mutex_init(&tok->lock, NULL);
+        pthread_mutex_init(&tok->lock, NULL);
 #elif defined HAVE_WIN32_THREADS
     tok->mutex = CreateMutex(NULL, FALSE, NULL);
 #elif defined HAVE_BEOS_THREADS
-	if ((tok->sem = create_sem(1, "xmlMutex")) < B_OK) {
-		free(tok);
-		return NULL;
-	}
-	tok->tid = -1;
+    if ((tok->sem = create_sem(1, "xmlMutex")) < B_OK) {
+        free(tok);
+        return NULL;
+    }
+    tok->tid = -1;
 #endif
     return (tok);
 }
@@ -208,15 +218,16 @@
 void
 xmlFreeMutex(xmlMutexPtr tok)
 {
-    if (tok == NULL) return;
+    if (tok == NULL)
+        return;
 
 #ifdef HAVE_PTHREAD_H
     if (libxml_is_threaded != 0)
-	pthread_mutex_destroy(&tok->lock);
+        pthread_mutex_destroy(&tok->lock);
 #elif defined HAVE_WIN32_THREADS
     CloseHandle(tok->mutex);
 #elif defined HAVE_BEOS_THREADS
-	delete_sem(tok->sem);
+    delete_sem(tok->sem);
 #endif
     free(tok);
 }
@@ -234,17 +245,18 @@
         return;
 #ifdef HAVE_PTHREAD_H
     if (libxml_is_threaded != 0)
-	pthread_mutex_lock(&tok->lock);
+        pthread_mutex_lock(&tok->lock);
 #elif defined HAVE_WIN32_THREADS
     WaitForSingleObject(tok->mutex, INFINITE);
 #elif defined HAVE_BEOS_THREADS
-	if (acquire_sem(tok->sem) != B_NO_ERROR) {
+    if (acquire_sem(tok->sem) != B_NO_ERROR) {
 #ifdef DEBUG_THREADS
-		xmlGenericError(xmlGenericErrorContext, "xmlMutexLock():BeOS:Couldn't aquire semaphore\n");
-		exit();
+        xmlGenericError(xmlGenericErrorContext,
+                        "xmlMutexLock():BeOS:Couldn't aquire semaphore\n");
+        exit();
 #endif
-	}
-	tok->tid = find_thread(NULL);
+    }
+    tok->tid = find_thread(NULL);
 #endif
 
 }
@@ -262,14 +274,14 @@
         return;
 #ifdef HAVE_PTHREAD_H
     if (libxml_is_threaded != 0)
-	pthread_mutex_unlock(&tok->lock);
+        pthread_mutex_unlock(&tok->lock);
 #elif defined HAVE_WIN32_THREADS
     ReleaseMutex(tok->mutex);
 #elif defined HAVE_BEOS_THREADS
-	if (tok->tid == find_thread(NULL)) {
-		tok->tid = -1;
-		release_sem(tok->sem);
-	}
+    if (tok->tid == find_thread(NULL)) {
+        tok->tid = -1;
+        release_sem(tok->sem);
+    }
 #endif
 }
 
@@ -292,20 +304,20 @@
         return (NULL);
 #ifdef HAVE_PTHREAD_H
     if (libxml_is_threaded != 0) {
-	pthread_mutex_init(&tok->lock, NULL);
-	tok->held = 0;
-	tok->waiters = 0;
-	pthread_cond_init(&tok->cv, NULL);
+        pthread_mutex_init(&tok->lock, NULL);
+        tok->held = 0;
+        tok->waiters = 0;
+        pthread_cond_init(&tok->cv, NULL);
     }
 #elif defined HAVE_WIN32_THREADS
     InitializeCriticalSection(&tok->cs);
     tok->count = 0;
 #elif defined HAVE_BEOS_THREADS
-	if ((tok->lock = xmlNewMutex()) == NULL) {
-		free(tok);
-		return NULL;
-	}
-	tok->count = 0;
+    if ((tok->lock = xmlNewMutex()) == NULL) {
+        free(tok);
+        return NULL;
+    }
+    tok->count = 0;
 #endif
     return (tok);
 }
@@ -324,13 +336,13 @@
         return;
 #ifdef HAVE_PTHREAD_H
     if (libxml_is_threaded != 0) {
-	pthread_mutex_destroy(&tok->lock);
-	pthread_cond_destroy(&tok->cv);
+        pthread_mutex_destroy(&tok->lock);
+        pthread_cond_destroy(&tok->cv);
     }
 #elif defined HAVE_WIN32_THREADS
     DeleteCriticalSection(&tok->cs);
 #elif defined HAVE_BEOS_THREADS
-	xmlFreeMutex(tok->lock);
+    xmlFreeMutex(tok->lock);
 #endif
     free(tok);
 }
@@ -370,13 +382,13 @@
     EnterCriticalSection(&tok->cs);
     ++tok->count;
 #elif defined HAVE_BEOS_THREADS
-	if (tok->lock->tid == find_thread(NULL)) {
-		tok->count++;
-		return;
-	} else {
-		xmlMutexLock(tok->lock);
-		tok->count = 1;
-	}
+    if (tok->lock->tid == find_thread(NULL)) {
+        tok->count++;
+        return;
+    } else {
+        xmlMutexLock(tok->lock);
+        tok->count = 1;
+    }
 #endif
 }
 
@@ -394,7 +406,7 @@
 #ifdef HAVE_PTHREAD_H
     if (libxml_is_threaded == 0)
         return;
-    
+
     pthread_mutex_lock(&tok->lock);
     tok->held--;
     if (tok->held == 0) {
@@ -404,16 +416,16 @@
     }
     pthread_mutex_unlock(&tok->lock);
 #elif defined HAVE_WIN32_THREADS
-    if (!--tok->count) 
-	LeaveCriticalSection(&tok->cs);
+    if (!--tok->count)
+        LeaveCriticalSection(&tok->cs);
 #elif defined HAVE_BEOS_THREADS
-	if (tok->lock->tid == find_thread(NULL)) {
-		tok->count--;
-		if (tok->count == 0) {
-			xmlMutexUnlock(tok->lock);
-		}
-		return;
-	}
+    if (tok->lock->tid == find_thread(NULL)) {
+        tok->count--;
+        if (tok->count == 0) {
+            xmlMutexUnlock(tok->lock);
+        }
+        return;
+    }
 #endif
 }
 
@@ -435,23 +447,29 @@
 
     /* Create a new critical section */
     if (global_init_lock == NULL) {
-	cs = malloc(sizeof(CRITICAL_SECTION));
-	InitializeCriticalSection(cs);
+        cs = malloc(sizeof(CRITICAL_SECTION));
+        if (cs == NULL) {
+            xmlGenericError(xmlGenericErrorContext,
+                            "xmlGlobalInitMutexLock: out of memory\n");
+            return;
+        }
+        InitializeCriticalSection(cs);
 
-	/* Swap it into the global_init_lock */
+        /* Swap it into the global_init_lock */
 #ifdef InterlockedCompareExchangePointer
-	InterlockedCompareExchangePointer(&global_init_lock, cs, NULL);
-#else  /* Use older void* version */
-    InterlockedCompareExchange((void **)&global_init_lock, (void *)cs, NULL);
+        InterlockedCompareExchangePointer(&global_init_lock, cs, NULL);
+#else /* Use older void* version */
+        InterlockedCompareExchange((void **) &global_init_lock,
+                                   (void *) cs, NULL);
 #endif /* InterlockedCompareExchangePointer */
 
-	/* If another thread successfully recorded its critical
-	 * section in the global_init_lock then discard the one
-	 * allocated by this thread. */
-	if (global_init_lock != cs) {
-		DeleteCriticalSection(cs);
-	    free(cs);
-	}
+        /* If another thread successfully recorded its critical
+         * section in the global_init_lock then discard the one
+         * allocated by this thread. */
+        if (global_init_lock != cs) {
+            DeleteCriticalSection(cs);
+            free(cs);
+        }
     }
 
     /* Lock the chosen critical section */
@@ -463,25 +481,26 @@
     sem = create_sem(1, "xmlGlobalinitMutex");
 
     while (global_init_lock == -1) {
-	if (atomic_add(&global_init_count, 1) == 0) {
-	    global_init_lock = sem;
-	} else {
-	    snooze(1);
-	    atomic_add(&global_init_count, -1);
-	}
+        if (atomic_add(&global_init_count, 1) == 0) {
+            global_init_lock = sem;
+        } else {
+            snooze(1);
+            atomic_add(&global_init_count, -1);
+        }
     }
 
     /* If another thread successfully recorded its critical
      * section in the global_init_lock then discard the one
      * allocated by this thread. */
     if (global_init_lock != sem)
-	delete_sem(sem);
+        delete_sem(sem);
 
     /* Acquire the chosen semaphore */
     if (acquire_sem(global_init_lock) != B_NO_ERROR) {
 #ifdef DEBUG_THREADS
-	xmlGenericError(xmlGenericErrorContext, "xmlGlobalInitMutexLock():BeOS:Couldn't acquire semaphore\n");
-	exit();
+        xmlGenericError(xmlGenericErrorContext,
+                        "xmlGlobalInitMutexLock():BeOS:Couldn't acquire semaphore\n");
+        exit();
 #endif
     }
 #endif
@@ -493,7 +512,9 @@
 #ifdef HAVE_PTHREAD_H
     pthread_mutex_unlock(&global_init_lock);
 #elif defined HAVE_WIN32_THREADS
-    LeaveCriticalSection(global_init_lock);
+    if (global_init_lock != NULL) {
+	LeaveCriticalSection(global_init_lock);
+    }
 #elif defined HAVE_BEOS_THREADS
     release_sem(global_init_lock);
 #endif
@@ -505,14 +526,14 @@
  * Makes sure that the global initialization mutex is destroyed before
  * application termination.
  */
-void __xmlGlobalInitMutexDestroy(void)
+void
+__xmlGlobalInitMutexDestroy(void)
 {
 #if defined HAVE_WIN32_THREADS
-    if (global_init_lock != NULL)
-    {
-	DeleteCriticalSection(global_init_lock);
-	free(global_init_lock);
-	global_init_lock = NULL;
+    if (global_init_lock != NULL) {
+        DeleteCriticalSection(global_init_lock);
+        free(global_init_lock);
+        global_init_lock = NULL;
     }
 #endif
 }
@@ -527,6 +548,7 @@
 #ifdef xmlLastError
 #undef xmlLastError
 #endif
+
 /**
  * xmlFreeGlobalState:
  * @state:  a thread global state
@@ -557,10 +579,13 @@
 xmlNewGlobalState(void)
 {
     xmlGlobalState *gs;
-    
+
     gs = malloc(sizeof(xmlGlobalState));
-    if (gs == NULL)
-	return(NULL);
+    if (gs == NULL) {
+	xmlGenericError(xmlGenericErrorContext,
+			"xmlGetGlobalState: out of memory\n");
+        return (NULL);
+    }
 
     memset(gs, 0, sizeof(xmlGlobalState));
     xmlInitializeGlobalState(gs);
@@ -572,15 +597,16 @@
 #ifdef HAVE_WIN32_THREADS
 #if !defined(HAVE_COMPILER_TLS)
 #if defined(LIBXML_STATIC) && !defined(LIBXML_STATIC_FOR_DLL)
-typedef struct _xmlGlobalStateCleanupHelperParams
-{
+typedef struct _xmlGlobalStateCleanupHelperParams {
     HANDLE thread;
     void *memory;
 } xmlGlobalStateCleanupHelperParams;
 
-static void XMLCDECL xmlGlobalStateCleanupHelper (void *p)
+static void XMLCDECL
+xmlGlobalStateCleanupHelper(void *p)
 {
-    xmlGlobalStateCleanupHelperParams *params = (xmlGlobalStateCleanupHelperParams *) p;
+    xmlGlobalStateCleanupHelperParams *params =
+        (xmlGlobalStateCleanupHelperParams *) p;
     WaitForSingleObject(params->thread, INFINITE);
     CloseHandle(params->thread);
     xmlFreeGlobalState(params->memory);
@@ -589,14 +615,13 @@
 }
 #else /* LIBXML_STATIC && !LIBXML_STATIC_FOR_DLL */
 
-typedef struct _xmlGlobalStateCleanupHelperParams
-{
+typedef struct _xmlGlobalStateCleanupHelperParams {
     void *memory;
-    struct _xmlGlobalStateCleanupHelperParams * prev;
-    struct _xmlGlobalStateCleanupHelperParams * next;
+    struct _xmlGlobalStateCleanupHelperParams *prev;
+    struct _xmlGlobalStateCleanupHelperParams *next;
 } xmlGlobalStateCleanupHelperParams;
 
-static xmlGlobalStateCleanupHelperParams * cleanup_helpers_head = NULL;
+static xmlGlobalStateCleanupHelperParams *cleanup_helpers_head = NULL;
 static CRITICAL_SECTION cleanup_helpers_cs;
 
 #endif /* LIBXMLSTATIC && !LIBXML_STATIC_FOR_DLL */
@@ -604,17 +629,20 @@
 #endif /* HAVE_WIN32_THREADS */
 
 #if defined HAVE_BEOS_THREADS
+
 /**
  * xmlGlobalStateCleanup:
  * @data: unused parameter
  *
  * Used for Beos only
  */
-void xmlGlobalStateCleanup(void *data)
+void
+xmlGlobalStateCleanup(void *data)
 {
-	void *globalval = tls_get(globalkey);
-	if (globalval != NULL)
-		xmlFreeGlobalState(globalval);
+    void *globalval = tls_get(globalkey);
+
+    if (globalval != NULL)
+        xmlFreeGlobalState(globalval);
 }
 #endif
 
@@ -632,13 +660,15 @@
     xmlGlobalState *globalval;
 
     if (libxml_is_threaded == 0)
-        return(NULL);
+        return (NULL);
 
     pthread_once(&once_control, xmlOnceInit);
 
     if ((globalval = (xmlGlobalState *)
-		pthread_getspecific(globalkey)) == NULL) {
+         pthread_getspecific(globalkey)) == NULL) {
         xmlGlobalState *tsd = xmlNewGlobalState();
+	if (tsd == NULL)
+	    return(NULL);
 
         pthread_setspecific(globalkey, tsd);
         return (tsd);
@@ -647,43 +677,54 @@
 #elif defined HAVE_WIN32_THREADS
 #if defined(HAVE_COMPILER_TLS)
     if (!tlstate_inited) {
-	tlstate_inited = 1;
-	xmlInitializeGlobalState(&tlstate);
+        tlstate_inited = 1;
+        xmlInitializeGlobalState(&tlstate);
     }
     return &tlstate;
 #else /* HAVE_COMPILER_TLS */
     xmlGlobalState *globalval;
-    xmlGlobalStateCleanupHelperParams * p;
+    xmlGlobalStateCleanupHelperParams *p;
 
     xmlOnceInit();
 #if defined(LIBXML_STATIC) && !defined(LIBXML_STATIC_FOR_DLL)
-    globalval = (xmlGlobalState *)TlsGetValue(globalkey);
+    globalval = (xmlGlobalState *) TlsGetValue(globalkey);
 #else
-    p = (xmlGlobalStateCleanupHelperParams*)TlsGetValue(globalkey);
-    globalval = (xmlGlobalState *)(p ? p->memory : NULL);
+    p = (xmlGlobalStateCleanupHelperParams *) TlsGetValue(globalkey);
+    globalval = (xmlGlobalState *) (p ? p->memory : NULL);
 #endif
     if (globalval == NULL) {
-	xmlGlobalState *tsd = xmlNewGlobalState();
-	p = (xmlGlobalStateCleanupHelperParams *) malloc(sizeof(xmlGlobalStateCleanupHelperParams));
-	p->memory = tsd;
+        xmlGlobalState *tsd = xmlNewGlobalState();
+
+        if (tsd == NULL)
+	    return(NULL);
+        p = (xmlGlobalStateCleanupHelperParams *)
+            malloc(sizeof(xmlGlobalStateCleanupHelperParams));
+	if (p == NULL) {
+            xmlGenericError(xmlGenericErrorContext,
+                            "xmlGetGlobalState: out of memory\n");
+            xmlFreeGlobalState(tsd);
+	    return(NULL);
+	}
+        p->memory = tsd;
 #if defined(LIBXML_STATIC) && !defined(LIBXML_STATIC_FOR_DLL)
-	DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), 
-		GetCurrentProcess(), &p->thread, 0, TRUE, DUPLICATE_SAME_ACCESS);
-	TlsSetValue(globalkey, tsd);
-	_beginthread(xmlGlobalStateCleanupHelper, 0, p);
+        DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
+                        GetCurrentProcess(), &p->thread, 0, TRUE,
+                        DUPLICATE_SAME_ACCESS);
+        TlsSetValue(globalkey, tsd);
+        _beginthread(xmlGlobalStateCleanupHelper, 0, p);
 #else
-	EnterCriticalSection(&cleanup_helpers_cs);	
+        EnterCriticalSection(&cleanup_helpers_cs);
         if (cleanup_helpers_head != NULL) {
             cleanup_helpers_head->prev = p;
         }
-	p->next = cleanup_helpers_head;
-	p->prev = NULL;
-	cleanup_helpers_head = p;
-	TlsSetValue(globalkey, p);
-	LeaveCriticalSection(&cleanup_helpers_cs);	
+        p->next = cleanup_helpers_head;
+        p->prev = NULL;
+        cleanup_helpers_head = p;
+        TlsSetValue(globalkey, p);
+        LeaveCriticalSection(&cleanup_helpers_cs);
 #endif
 
-	return (tsd);
+        return (tsd);
     }
     return (globalval);
 #endif /* HAVE_COMPILER_TLS */
@@ -692,9 +733,10 @@
 
     xmlOnceInit();
 
-    if ((globalval = (xmlGlobalState *)
-		tls_get(globalkey)) == NULL) {
+    if ((globalval = (xmlGlobalState *) tls_get(globalkey)) == NULL) {
         xmlGlobalState *tsd = xmlNewGlobalState();
+	if (tsd == NULL)
+	    return (NULL);
 
         tls_set(globalkey, tsd);
         on_exit_thread(xmlGlobalStateCleanup, NULL);
@@ -702,7 +744,7 @@
     }
     return (globalval);
 #else
-    return(NULL);
+    return (NULL);
 #endif
 }
 
@@ -724,14 +766,14 @@
 {
 #ifdef HAVE_PTHREAD_H
     if (libxml_is_threaded == 0)
-        return(0);
-    return((int) pthread_self());
+        return (0);
+    return ((int) pthread_self());
 #elif defined HAVE_WIN32_THREADS
     return GetCurrentThreadId();
 #elif defined HAVE_BEOS_THREADS
-	return find_thread(NULL);
+    return find_thread(NULL);
 #else
-    return((int) 0);
+    return ((int) 0);
 #endif
 }
 
@@ -749,25 +791,25 @@
     if (libxml_is_threaded == -1)
         xmlInitThreads();
     if (libxml_is_threaded == 0)
-        return(1);
+        return (1);
     pthread_once(&once_control, xmlOnceInit);
 #elif defined HAVE_WIN32_THREADS
-    xmlOnceInit (); 
+    xmlOnceInit();
 #elif defined HAVE_BEOS_THREADS
     xmlOnceInit();
 #endif
-        
+
 #ifdef DEBUG_THREADS
     xmlGenericError(xmlGenericErrorContext, "xmlIsMainThread()\n");
 #endif
 #ifdef HAVE_PTHREAD_H
-    return(mainthread == pthread_self());
+    return (mainthread == pthread_self());
 #elif defined HAVE_WIN32_THREADS
-    return(mainthread == GetCurrentThreadId ());
+    return (mainthread == GetCurrentThreadId());
 #elif defined HAVE_BEOS_THREADS
-	return(mainthread == find_thread(NULL));
+    return (mainthread == find_thread(NULL));
 #else
-    return(1);
+    return (1);
 #endif
 }
 
@@ -819,24 +861,28 @@
 #ifdef HAVE_PTHREAD_H
     if (libxml_is_threaded == -1) {
         if ((pthread_once != NULL) &&
-	    (pthread_getspecific != NULL) &&
-	    (pthread_setspecific != NULL) &&
-	    (pthread_key_create != NULL) &&
-	    (pthread_mutex_init != NULL) &&
-	    (pthread_mutex_destroy != NULL) &&
-	    (pthread_mutex_lock != NULL) &&
-	    (pthread_mutex_unlock != NULL) &&
-	    (pthread_cond_init != NULL) &&
-	    (pthread_equal != NULL) &&
-	    (pthread_self != NULL) &&
-	    (pthread_key_create != NULL) &&
-	    (pthread_cond_signal != NULL)) {
-	    libxml_is_threaded = 1;
+            (pthread_getspecific != NULL) &&
+            (pthread_setspecific != NULL) &&
+            (pthread_key_create != NULL) &&
+            (pthread_key_delete != NULL) &&
+            (pthread_mutex_init != NULL) &&
+            (pthread_mutex_destroy != NULL) &&
+            (pthread_mutex_lock != NULL) &&
+            (pthread_mutex_unlock != NULL) &&
+            (pthread_cond_init != NULL) &&
+            (pthread_cond_destroy != NULL) &&
+            (pthread_cond_wait != NULL) &&
+            (pthread_equal != NULL) &&
+            (pthread_self != NULL) &&
+            (pthread_cond_signal != NULL)) {
+            libxml_is_threaded = 1;
+
 /* fprintf(stderr, "Running multithreaded\n"); */
-	} else {
+        } else {
+
 /* fprintf(stderr, "Running without multithread\n"); */
-	    libxml_is_threaded = 0;
-	}
+            libxml_is_threaded = 0;
+        }
     }
 #endif
 }
@@ -855,25 +901,31 @@
 #endif
 #if defined(HAVE_WIN32_THREADS) && !defined(HAVE_COMPILER_TLS) && (!defined(LIBXML_STATIC) || defined(LIBXML_STATIC_FOR_DLL))
     if (globalkey != TLS_OUT_OF_INDEXES) {
-	xmlGlobalStateCleanupHelperParams * p;
-	EnterCriticalSection(&cleanup_helpers_cs);
-	p = cleanup_helpers_head;
-	while (p != NULL) {
-		xmlGlobalStateCleanupHelperParams * temp = p;
-		p = p->next;
-		xmlFreeGlobalState(temp->memory);
-		free(temp);
-	}
-	cleanup_helpers_head = 0;
-	LeaveCriticalSection(&cleanup_helpers_cs);
-	TlsFree(globalkey);
-	globalkey = TLS_OUT_OF_INDEXES;
+        xmlGlobalStateCleanupHelperParams *p;
+
+        EnterCriticalSection(&cleanup_helpers_cs);
+        p = cleanup_helpers_head;
+        while (p != NULL) {
+            xmlGlobalStateCleanupHelperParams *temp = p;
+
+            p = p->next;
+            xmlFreeGlobalState(temp->memory);
+            free(temp);
+        }
+        cleanup_helpers_head = 0;
+        LeaveCriticalSection(&cleanup_helpers_cs);
+        TlsFree(globalkey);
+        globalkey = TLS_OUT_OF_INDEXES;
     }
     DeleteCriticalSection(&cleanup_helpers_cs);
+#elif defined HAVE_PTHREAD_H
+    if ((libxml_is_threaded)  && (pthread_key_delete != NULL))
+        pthread_key_delete(globalkey);
 #endif
 }
 
 #ifdef LIBXML_THREAD_ENABLED
+
 /**
  * xmlOnceInit
  *
@@ -884,7 +936,8 @@
  * details.
  */
 static void
-xmlOnceInit(void) {
+xmlOnceInit(void)
+{
 #ifdef HAVE_PTHREAD_H
     (void) pthread_key_create(&globalkey, xmlFreeGlobalState);
     mainthread = pthread_self();
@@ -892,15 +945,13 @@
 
 #if defined(HAVE_WIN32_THREADS)
     if (!run_once.done) {
-        if (InterlockedIncrement(&run_once.control) == 1)
-        {
+        if (InterlockedIncrement(&run_once.control) == 1) {
 #if !defined(HAVE_COMPILER_TLS)
             globalkey = TlsAlloc();
 #endif
             mainthread = GetCurrentThreadId();
             run_once.done = 1;
-        }
-        else {
+        } else {
             /* Another thread is working; give up our slice and
              * wait until they're done. */
             while (!run_once.done)
@@ -910,12 +961,12 @@
 #endif
 
 #ifdef HAVE_BEOS_THREADS
-	if (atomic_add(&run_once_init, 1) == 0) {
-		globalkey = tls_allocate();
-		tls_set(globalkey, NULL);
-		mainthread = find_thread(NULL);
-	} else
-		atomic_add(&run_once_init, -1);
+    if (atomic_add(&run_once_init, 1) == 0) {
+        globalkey = tls_allocate();
+        tls_set(globalkey, NULL);
+        mainthread = find_thread(NULL);
+    } else
+        atomic_add(&run_once_init, -1);
 #endif
 }
 #endif
@@ -933,36 +984,38 @@
  */
 #if defined(HAVE_WIN32_THREADS) && !defined(HAVE_COMPILER_TLS) && (!defined(LIBXML_STATIC) || defined(LIBXML_STATIC_FOR_DLL))
 #if defined(LIBXML_STATIC_FOR_DLL)
-BOOL XMLCALL xmlDllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) 
+BOOL XMLCALL
+xmlDllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
 #else
-BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) 
+BOOL WINAPI
+DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
 #endif
 {
-    switch(fdwReason) {
-    case DLL_THREAD_DETACH:
-	if (globalkey != TLS_OUT_OF_INDEXES) {
-	    xmlGlobalState *globalval = NULL;
-	    xmlGlobalStateCleanupHelperParams * p =
-		(xmlGlobalStateCleanupHelperParams*)TlsGetValue(globalkey);
-	    globalval = (xmlGlobalState *)(p ? p->memory : NULL);
-            if (globalval) {
-                xmlFreeGlobalState(globalval);
-                TlsSetValue(globalkey,NULL);
+    switch (fdwReason) {
+        case DLL_THREAD_DETACH:
+            if (globalkey != TLS_OUT_OF_INDEXES) {
+                xmlGlobalState *globalval = NULL;
+                xmlGlobalStateCleanupHelperParams *p =
+                    (xmlGlobalStateCleanupHelperParams *)
+                    TlsGetValue(globalkey);
+                globalval = (xmlGlobalState *) (p ? p->memory : NULL);
+                if (globalval) {
+                    xmlFreeGlobalState(globalval);
+                    TlsSetValue(globalkey, NULL);
+                }
+                if (p) {
+                    EnterCriticalSection(&cleanup_helpers_cs);
+                    if (p == cleanup_helpers_head)
+                        cleanup_helpers_head = p->next;
+                    else
+                        p->prev->next = p->next;
+                    if (p->next != NULL)
+                        p->next->prev = p->prev;
+                    LeaveCriticalSection(&cleanup_helpers_cs);
+                    free(p);
+                }
             }
-	    if (p)
-	    {
-		EnterCriticalSection(&cleanup_helpers_cs);
-                if (p == cleanup_helpers_head)
-		    cleanup_helpers_head = p->next;
-                else
-		    p->prev->next = p->next;
-                if (p->next != NULL)
-                    p->next->prev = p->prev;
-		LeaveCriticalSection(&cleanup_helpers_cs);
-		free(p);
-	    }
-	}
-	break;
+            break;
     }
     return TRUE;
 }
diff --git a/tree.c b/tree.c
index 432007e..8e393da 100644
--- a/tree.c
+++ b/tree.c
@@ -14,7 +14,7 @@
 #include "libxml.h"
 
 #include <string.h> /* for memset() only ! */
-
+#include <limits.h>
 #ifdef HAVE_CTYPE_H
 #include <ctype.h>
 #endif
@@ -45,7 +45,7 @@
 
 /************************************************************************
  *									*
- * 		Forward declarations					*
+ *		Forward declarations					*
  *									*
  ************************************************************************/
 
@@ -55,7 +55,7 @@
 
 /************************************************************************
  *									*
- * 		Tree memory error handler				*
+ *		Tree memory error handler				*
  *									*
  ************************************************************************/
 /**
@@ -92,6 +92,9 @@
 	case XML_TREE_UNTERMINATED_ENTITY:
 	    msg = "unterminated entity reference %15s\n";
 	    break;
+	case XML_TREE_NOT_UTF8:
+	    msg = "string is not in UTF-8\n";
+	    break;
 	default:
 	    msg = "unexpected error number\n";
     }
@@ -100,7 +103,7 @@
 
 /************************************************************************
  *									*
- * 		A few static variables and macros			*
+ *		A few static variables and macros			*
  *									*
  ************************************************************************/
 /* #undef xmlStringText */
@@ -120,7 +123,7 @@
         (n)->last = NULL;						\
     } else {								\
         while (ulccur->next != NULL) {					\
-	       	ulccur->parent = (n);					\
+		ulccur->parent = (n);					\
 		ulccur = ulccur->next;					\
 	}								\
 	ulccur->parent = (n);						\
@@ -135,12 +138,12 @@
 
 /************************************************************************
  *									*
- *		Functions to move to entities.c once the 		*
+ *		Functions to move to entities.c once the		*
  *		API freeze is smoothen and they can be made public.	*
  *									*
  ************************************************************************/
 #include <libxml/hash.h>
- 
+
 #ifdef LIBXML_TREE_ENABLED
 /**
  * xmlGetEntityFromDtd:
@@ -149,17 +152,17 @@
  *
  * Do an entity lookup in the DTD entity hash table and
  * return the corresponding entity, if found.
- * 
+ *
  * Returns A pointer to the entity structure or NULL if not found.
  */
 static xmlEntityPtr
 xmlGetEntityFromDtd(xmlDtdPtr dtd, const xmlChar *name) {
     xmlEntitiesTablePtr table;
-    
+
     if((dtd != NULL) && (dtd->entities != NULL)) {
 	table = (xmlEntitiesTablePtr) dtd->entities;
 	return((xmlEntityPtr) xmlHashLookup(table, name));
-    	/* return(xmlGetEntityFromTable(table, name)); */
+	/* return(xmlGetEntityFromTable(table, name)); */
     }
     return(NULL);
 }
@@ -167,7 +170,7 @@
  * xmlGetParameterEntityFromDtd:
  * @dtd:  A pointer to the DTD to search
  * @name:  The entity name
- * 
+ *
  * Do an entity lookup in the DTD pararmeter entity hash table and
  * return the corresponding entity, if found.
  *
@@ -176,7 +179,7 @@
 static xmlEntityPtr
 xmlGetParameterEntityFromDtd(xmlDtdPtr dtd, const xmlChar *name) {
     xmlEntitiesTablePtr table;
-    
+
     if ((dtd != NULL) && (dtd->pentities != NULL)) {
 	table = (xmlEntitiesTablePtr) dtd->pentities;
 	return((xmlEntityPtr) xmlHashLookup(table, name));
@@ -237,7 +240,7 @@
 /**
  * xmlSplitQName2:
  * @name:  the full QName
- * @prefix:  a xmlChar ** 
+ * @prefix:  a xmlChar **
  *
  * parse an XML qualified name string
  *
@@ -275,9 +278,9 @@
      * we are not trying to validate but just to cut, and yes it will
      * work even if this is as set of UTF-8 encoded chars
      */
-    while ((name[len] != 0) && (name[len] != ':')) 
+    while ((name[len] != 0) && (name[len] != ':'))
 	len++;
-    
+
     if (name[len] == 0)
 	return(NULL);
 
@@ -326,9 +329,9 @@
      * we are not trying to validate but just to cut, and yes it will
      * work even if this is as set of UTF-8 encoded chars
      */
-    while ((name[l] != 0) && (name[l] != ':')) 
+    while ((name[l] != 0) && (name[l] != ':'))
 	l++;
-    
+
     if (name[l] == 0)
 	return(NULL);
 
@@ -342,7 +345,7 @@
  *		Check Name, NCName and QName strings			*
  *									*
  ************************************************************************/
- 
+
 #define CUR_SCHAR(s, l) xmlStringCurrentChar(NULL, s, &l)
 
 #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XPATH_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) || defined(LIBXML_DEBUG_ENABLED) || defined (LIBXML_HTML_ENABLED) || defined(LIBXML_SAX1_ENABLED) || defined(LIBXML_HTML_ENABLED) || defined(LIBXML_WRITER_ENABLED) || defined(LIBXML_DOCB_ENABLED)
@@ -665,19 +668,21 @@
  *		Allocation and deallocation of basic structures		*
  *									*
  ************************************************************************/
- 
+
 /**
  * xmlSetBufferAllocationScheme:
  * @scheme:  allocation method to use
- * 
+ *
  * Set the buffer allocation method.  Types are
  * XML_BUFFER_ALLOC_EXACT - use exact sizes, keeps memory usage down
- * XML_BUFFER_ALLOC_DOUBLEIT - double buffer when extra needed, 
+ * XML_BUFFER_ALLOC_DOUBLEIT - double buffer when extra needed,
  *                             improves performance
  */
 void
 xmlSetBufferAllocationScheme(xmlBufferAllocationScheme scheme) {
-    xmlBufferAllocScheme = scheme;
+    if ((scheme == XML_BUFFER_ALLOC_EXACT) ||
+        (scheme == XML_BUFFER_ALLOC_DOUBLEIT))
+	xmlBufferAllocScheme = scheme;
 }
 
 /**
@@ -685,9 +690,9 @@
  *
  * Types are
  * XML_BUFFER_ALLOC_EXACT - use exact sizes, keeps memory usage down
- * XML_BUFFER_ALLOC_DOUBLEIT - double buffer when extra needed, 
+ * XML_BUFFER_ALLOC_DOUBLEIT - double buffer when extra needed,
  *                             improves performance
- * 
+ *
  * Returns the current allocation scheme
  */
 xmlBufferAllocationScheme
@@ -730,9 +735,9 @@
     cur->type = XML_LOCAL_NAMESPACE;
 
     if (href != NULL)
-	cur->href = xmlStrdup(href); 
+	cur->href = xmlStrdup(href);
     if (prefix != NULL)
-	cur->prefix = xmlStrdup(prefix); 
+	cur->prefix = xmlStrdup(prefix);
 
     /*
      * Add it at the end to preserve parsing order ...
@@ -748,14 +753,14 @@
 		(xmlStrEqual(prev->prefix, cur->prefix))) {
 		xmlFreeNs(cur);
 		return(NULL);
-	    }    
+	    }
 	    while (prev->next != NULL) {
 	        prev = prev->next;
 		if (((prev->prefix == NULL) && (cur->prefix == NULL)) ||
 		    (xmlStrEqual(prev->prefix, cur->prefix))) {
 		    xmlFreeNs(cur);
 		    return(NULL);
-		}    
+		}
 	    }
 	    prev->next = cur;
 	}
@@ -864,11 +869,11 @@
     cur->type = XML_DTD_NODE;
 
     if (name != NULL)
-	cur->name = xmlStrdup(name); 
+	cur->name = xmlStrdup(name);
     if (ExternalID != NULL)
-	cur->ExternalID = xmlStrdup(ExternalID); 
+	cur->ExternalID = xmlStrdup(ExternalID);
     if (SystemID != NULL)
-	cur->SystemID = xmlStrdup(SystemID); 
+	cur->SystemID = xmlStrdup(SystemID);
     if (doc != NULL)
 	doc->extSubset = cur;
     cur->doc = doc;
@@ -946,7 +951,7 @@
 	}
     }
     if (ExternalID != NULL) {
-	cur->ExternalID = xmlStrdup(ExternalID); 
+	cur->ExternalID = xmlStrdup(ExternalID);
 	if (cur->ExternalID  == NULL) {
 	    xmlTreeErrMemory("building internal subset");
 	    if (cur->name != NULL)
@@ -956,7 +961,7 @@
 	}
     }
     if (SystemID != NULL) {
-	cur->SystemID = xmlStrdup(SystemID); 
+	cur->SystemID = xmlStrdup(SystemID);
 	if (cur->SystemID == NULL) {
 	    xmlTreeErrMemory("building internal subset");
 	    if (cur->name != NULL)
@@ -1019,7 +1024,7 @@
  * current scope
  */
 #define DICT_FREE(str)						\
-	if ((str) && ((!dict) || 				\
+	if ((str) && ((!dict) ||				\
 	    (xmlDictOwns(dict, (const xmlChar *)(str)) == 0)))	\
 	    xmlFree((char *)(str));
 
@@ -1102,7 +1107,7 @@
     /* TODO !!! */
     if (cur->notations != NULL)
         xmlFreeNotationTable((xmlNotationTablePtr) cur->notations);
-    
+
     if (cur->elements != NULL)
         xmlFreeElementTable((xmlElementTablePtr) cur->elements);
     if (cur->attributes != NULL)
@@ -1141,15 +1146,17 @@
     memset(cur, 0, sizeof(xmlDoc));
     cur->type = XML_DOCUMENT_NODE;
 
-    cur->version = xmlStrdup(version); 
+    cur->version = xmlStrdup(version);
     if (cur->version == NULL) {
 	xmlTreeErrMemory("building doc");
 	xmlFree(cur);
-    	return(NULL);
+	return(NULL);
     }
     cur->standalone = -1;
     cur->compression = -1; /* not initialized */
     cur->doc = cur;
+    cur->parseFlags = 0;
+    cur->properties = XML_DOC_USERBUILT;
     /*
      * The in memory encoding is always UTF8
      * This field will never change and would
@@ -1277,7 +1284,7 @@
 		else
 		    tmp = 0;
 		while (tmp != ';') { /* Non input consuming loop */
-		    if ((tmp >= '0') && (tmp <= '9')) 
+		    if ((tmp >= '0') && (tmp <= '9'))
 			charval = charval * 16 + (tmp - '0');
 		    else if ((tmp >= 'a') && (tmp <= 'f'))
 			charval = charval * 16 + (tmp - 'a') + 10;
@@ -1305,7 +1312,7 @@
 		else
 		    tmp = 0;
 		while (tmp != ';') { /* Non input consuming loops */
-		    if ((tmp >= '0') && (tmp <= '9')) 
+		    if ((tmp >= '0') && (tmp <= '9'))
 			charval = charval * 10 + (tmp - '0');
 		    else {
 			xmlTreeErr(XML_TREE_INVALID_DEC, (xmlNodePtr) doc,
@@ -1350,7 +1357,7 @@
 			    last = xmlAddNextSibling(last, node);
 			} else
 			    xmlNodeAddContent(last, ent->content);
-			    
+
 		    } else {
 			/*
 			 * Create a new REFERENCE_REF node
@@ -1471,7 +1478,7 @@
 		cur += 3;
 		tmp = *cur;
 		while (tmp != ';') { /* Non input consuming loop */
-		    if ((tmp >= '0') && (tmp <= '9')) 
+		    if ((tmp >= '0') && (tmp <= '9'))
 			charval = charval * 16 + (tmp - '0');
 		    else if ((tmp >= 'a') && (tmp <= 'f'))
 			charval = charval * 16 + (tmp - 'a') + 10;
@@ -1493,7 +1500,7 @@
 		cur += 2;
 		tmp = *cur;
 		while (tmp != ';') { /* Non input consuming loops */
-		    if ((tmp >= '0') && (tmp <= '9')) 
+		    if ((tmp >= '0') && (tmp <= '9'))
 			charval = charval * 10 + (tmp - '0');
 		    else {
 			xmlTreeErr(XML_TREE_INVALID_DEC, (xmlNodePtr) doc,
@@ -1535,7 +1542,7 @@
 			    last = xmlAddNextSibling(last, node);
 			} else
 			    xmlNodeAddContent(last, ent->content);
-			    
+
 		    } else {
 			/*
 			 * Create a new REFERENCE_REF node
@@ -1780,7 +1787,9 @@
     xmlDocPtr doc = NULL;
 
     if ((node != NULL) && (node->type != XML_ELEMENT_NODE)) {
-        if (eatname == 1)
+        if ((eatname == 1) &&
+	    ((node->doc == NULL) ||
+	     (!(xmlDictOwns(node->doc->dict, name)))))
             xmlFree((xmlChar *) name);
         return (NULL);
     }
@@ -1790,7 +1799,9 @@
      */
     cur = (xmlAttrPtr) xmlMalloc(sizeof(xmlAttr));
     if (cur == NULL) {
-        if (eatname == 1)
+        if ((eatname == 1) &&
+	    ((node->doc == NULL) ||
+	     (!(xmlDictOwns(node->doc->dict, name)))))
             xmlFree((xmlChar *) name);
         xmlTreeErrMemory("building attribute");
         return (NULL);
@@ -1814,11 +1825,15 @@
         cur->name = name;
 
     if (value != NULL) {
-        xmlChar *buffer;
         xmlNodePtr tmp;
 
-        buffer = xmlEncodeEntitiesReentrant(doc, value);
-        cur->children = xmlStringGetNodeList(doc, buffer);
+        if(!xmlCheckUTF8(value)) {
+            xmlTreeErr(XML_TREE_NOT_UTF8, (xmlNodePtr) doc,
+                       NULL);
+            if (doc != NULL)
+                doc->encoding = xmlStrdup(BAD_CAST "ISO-8859-1");
+        }
+        cur->children = xmlNewDocText(doc, value);
         cur->last = NULL;
         tmp = cur->children;
         while (tmp != NULL) {
@@ -1827,7 +1842,6 @@
                 cur->last = tmp;
             tmp = tmp->next;
         }
-        xmlFree(buffer);
     }
 
     /*
@@ -1927,7 +1941,7 @@
 	return(NULL);
     }
 
-	return xmlNewPropInternal(node, ns, name, value, 1);
+    return xmlNewPropInternal(node, ns, name, value, 1);
 }
 
 /**
@@ -1966,7 +1980,7 @@
 	cur->name = xmlDictLookup(doc->dict, name, -1);
     else
 	cur->name = xmlStrdup(name);
-    cur->doc = doc; 
+    cur->doc = doc;
     if (value != NULL) {
 	xmlNodePtr tmp;
 
@@ -2173,7 +2187,7 @@
     }
     memset(cur, 0, sizeof(xmlNode));
     cur->type = XML_ELEMENT_NODE;
-    
+
     cur->name = xmlStrdup(name);
     cur->ns = ns;
 
@@ -2210,13 +2224,13 @@
      */
     cur = (xmlNodePtr) xmlMalloc(sizeof(xmlNode));
     if (cur == NULL) {
-	xmlFree(name);
 	xmlTreeErrMemory("building node");
+	/* we can't check here that name comes from the doc dictionnary */
 	return(NULL);
     }
     memset(cur, 0, sizeof(xmlNode));
     cur->type = XML_ELEMENT_NODE;
-    
+
     cur->name = name;
     cur->ns = ns;
 
@@ -2290,6 +2304,11 @@
 	    cur->children = xmlStringGetNodeList(doc, content);
 	    UPDATE_LAST_CHILD_AND_PARENT(cur)
 	}
+    } else {
+        /* if name don't come from the doc dictionnary free it here */
+        if ((name != NULL) && (doc != NULL) &&
+	    (!(xmlDictOwns(doc->dict, name))))
+	    xmlFree(name);
     }
     return(cur);
 }
@@ -2399,9 +2418,9 @@
  * a child TEXT node will be created containing the string @content.
  * NOTE: Use xmlNewChild() if @content will contain entities that need to be
  * preserved. Use this function, xmlNewTextChild(), if you need to ensure that
- * reserved XML chars that might appear in @content, such as the ampersand, 
- * greater-than or less-than signs, are automatically replaced by their XML 
- * escaped entity representations. 
+ * reserved XML chars that might appear in @content, such as the ampersand,
+ * greater-than or less-than signs, are automatically replaced by their XML
+ * escaped entity representations.
  *
  * Returns a pointer to the new node object.
  */
@@ -2849,14 +2868,14 @@
 
 /**
  * xmlAddPropSibling:
- * @prev:  the attribute to which @prop is added after 
+ * @prev:  the attribute to which @prop is added after
  * @cur:   the base attribute passed to calling function
  * @prop:  the new attribute
  *
  * Add a new attribute after @prev using @cur as base attribute.
  * When inserting before @cur, @prev is passed as @cur->prev.
  * When inserting after @cur, @prev is passed as @cur.
- * If an existing attribute is found it is detroyed prior to adding @prop. 
+ * If an existing attribute is found it is detroyed prior to adding @prop.
  *
  * Returns the attribute being inserted or NULL in case of error.
  */
@@ -2906,7 +2925,7 @@
  * first unlinked from its existing context.
  * As a result of text merging @elem may be freed.
  * If the new node is ATTRIBUTE, it is added into properties instead of children.
- * If there is an attribute with equal name, it is first destroyed. 
+ * If there is an attribute with equal name, it is first destroyed.
  *
  * Returns the new node or NULL in case of error.
  */
@@ -2984,7 +3003,7 @@
  * If the new node was already inserted in a document it is
  * first unlinked from its existing context.
  * If the new node is ATTRIBUTE, it is added into properties instead of children.
- * If there is an attribute with equal name, it is first destroyed. 
+ * If there is an attribute with equal name, it is first destroyed.
  *
  * Returns the new node or NULL in case of error.
  */
@@ -3088,7 +3107,7 @@
      * Constant time is we can rely on the ->parent->last to find
      * the last sibling.
      */
-    if ((cur->type != XML_ATTRIBUTE_NODE) && (cur->parent != NULL) && 
+    if ((cur->type != XML_ATTRIBUTE_NODE) && (cur->parent != NULL) &&
 	(cur->parent->children != NULL) &&
 	(cur->parent->last != NULL) &&
 	(cur->parent->last->next == NULL)) {
@@ -3170,10 +3189,10 @@
 	/*
 	 * If cur and parent->last both are TEXT nodes, then merge them.
 	 */
-	if ((cur->type == XML_TEXT_NODE) && 
+	if ((cur->type == XML_TEXT_NODE) &&
 	    (parent->last->type == XML_TEXT_NODE) &&
 	    (cur->name == parent->last->name)) {
-    	    xmlNodeAddContent(parent->last, cur->content);
+	    xmlNodeAddContent(parent->last, cur->content);
 	    /*
 	     * if it's the only child, nothing more to be done.
 	     */
@@ -3197,7 +3216,10 @@
         cur = cur->next;
     }
     cur->parent = parent;
-    cur->doc = parent->doc; /* the parent may not be linked to a doc ! */
+    /* the parent may not be linked to a doc ! */
+    if (cur->doc != parent->doc) {
+        xmlSetTreeDoc(cur, parent->doc);
+    }
     parent->last = cur;
 
     return(cur);
@@ -3211,7 +3233,7 @@
  * Add a new node to @parent, at the end of the child (or property) list
  * merging adjacent TEXT nodes (in which case @cur is freed)
  * If the new node is ATTRIBUTE, it is added into properties instead of children.
- * If there is an attribute with equal name, it is first destroyed. 
+ * If there is an attribute with equal name, it is first destroyed.
  *
  * Returns the child or NULL in case of error.
  */
@@ -3290,9 +3312,7 @@
     if (cur->type == XML_ATTRIBUTE_NODE) {
 		if (parent->type != XML_ELEMENT_NODE)
 			return(NULL);
-	if (parent->properties == NULL) {
-	    parent->properties = (xmlAttrPtr) cur;
-	} else {
+	if (parent->properties != NULL) {
 	    /* check if an attribute with the same name exists */
 	    xmlAttrPtr lastattr;
 
@@ -3307,8 +3327,13 @@
 	    }
 		if (lastattr == (xmlAttrPtr) cur)
 			return(cur);
+
+	}
+	if (parent->properties == NULL) {
+	    parent->properties = (xmlAttrPtr) cur;
+	} else {
 	    /* find the end */
-	    lastattr = parent->properties;
+	    xmlAttrPtr lastattr = parent->properties;
 	    while (lastattr->next != NULL) {
 		lastattr = lastattr->next;
 	    }
@@ -3348,6 +3373,199 @@
     return(parent->last);
 }
 
+#ifdef LIBXML_TREE_ENABLED
+/*
+ * 5 interfaces from DOM ElementTraversal
+ */
+
+/**
+ * xmlChildElementCount:
+ * @parent: the parent node
+ *
+ * Finds the current number of child nodes of that element which are
+ * element nodes.
+ * Note the handling of entities references is different than in
+ * the W3C DOM element traversal spec since we don't have back reference
+ * from entities content to entities references.
+ *
+ * Returns the count of element child or 0 if not available
+ */
+unsigned long
+xmlChildElementCount(xmlNodePtr parent) {
+    unsigned long ret = 0;
+    xmlNodePtr cur = NULL;
+
+    if (parent == NULL)
+        return(0);
+    switch (parent->type) {
+        case XML_ELEMENT_NODE:
+        case XML_ENTITY_NODE:
+        case XML_DOCUMENT_NODE:
+        case XML_HTML_DOCUMENT_NODE:
+            cur = parent->children;
+            break;
+        default:
+            return(0);
+    }
+    while (cur != NULL) {
+        if (cur->type == XML_ELEMENT_NODE)
+            ret++;
+        cur = cur->next;
+    }
+    return(ret);
+}
+
+/**
+ * xmlFirstElementChild:
+ * @parent: the parent node
+ *
+ * Finds the first child node of that element which is a Element node
+ * Note the handling of entities references is different than in
+ * the W3C DOM element traversal spec since we don't have back reference
+ * from entities content to entities references.
+ *
+ * Returns the first element child or NULL if not available
+ */
+xmlNodePtr
+xmlFirstElementChild(xmlNodePtr parent) {
+    xmlNodePtr cur = NULL;
+
+    if (parent == NULL)
+        return(NULL);
+    switch (parent->type) {
+        case XML_ELEMENT_NODE:
+        case XML_ENTITY_NODE:
+        case XML_DOCUMENT_NODE:
+        case XML_HTML_DOCUMENT_NODE:
+            cur = parent->children;
+            break;
+        default:
+            return(NULL);
+    }
+    while (cur != NULL) {
+        if (cur->type == XML_ELEMENT_NODE)
+            return(cur);
+        cur = cur->next;
+    }
+    return(NULL);
+}
+
+/**
+ * xmlLastElementChild:
+ * @parent: the parent node
+ *
+ * Finds the last child node of that element which is a Element node
+ * Note the handling of entities references is different than in
+ * the W3C DOM element traversal spec since we don't have back reference
+ * from entities content to entities references.
+ *
+ * Returns the last element child or NULL if not available
+ */
+xmlNodePtr
+xmlLastElementChild(xmlNodePtr parent) {
+    xmlNodePtr cur = NULL;
+
+    if (parent == NULL)
+        return(NULL);
+    switch (parent->type) {
+        case XML_ELEMENT_NODE:
+        case XML_ENTITY_NODE:
+        case XML_DOCUMENT_NODE:
+        case XML_HTML_DOCUMENT_NODE:
+            cur = parent->last;
+            break;
+        default:
+            return(NULL);
+    }
+    while (cur != NULL) {
+        if (cur->type == XML_ELEMENT_NODE)
+            return(cur);
+        cur = cur->prev;
+    }
+    return(NULL);
+}
+
+/**
+ * xmlPreviousElementSibling:
+ * @node: the current node
+ *
+ * Finds the first closest previous sibling of the node which is an
+ * element node.
+ * Note the handling of entities references is different than in
+ * the W3C DOM element traversal spec since we don't have back reference
+ * from entities content to entities references.
+ *
+ * Returns the previous element sibling or NULL if not available
+ */
+xmlNodePtr
+xmlPreviousElementSibling(xmlNodePtr node) {
+    if (node == NULL)
+        return(NULL);
+    switch (node->type) {
+        case XML_ELEMENT_NODE:
+        case XML_TEXT_NODE:
+        case XML_CDATA_SECTION_NODE:
+        case XML_ENTITY_REF_NODE:
+        case XML_ENTITY_NODE:
+        case XML_PI_NODE:
+        case XML_COMMENT_NODE:
+        case XML_XINCLUDE_START:
+        case XML_XINCLUDE_END:
+            node = node->prev;
+            break;
+        default:
+            return(NULL);
+    }
+    while (node != NULL) {
+        if (node->type == XML_ELEMENT_NODE)
+            return(node);
+        node = node->next;
+    }
+    return(NULL);
+}
+
+/**
+ * xmlNextElementSibling:
+ * @node: the current node
+ *
+ * Finds the first closest next sibling of the node which is an
+ * element node.
+ * Note the handling of entities references is different than in
+ * the W3C DOM element traversal spec since we don't have back reference
+ * from entities content to entities references.
+ *
+ * Returns the next element sibling or NULL if not available
+ */
+xmlNodePtr
+xmlNextElementSibling(xmlNodePtr node) {
+    if (node == NULL)
+        return(NULL);
+    switch (node->type) {
+        case XML_ELEMENT_NODE:
+        case XML_TEXT_NODE:
+        case XML_CDATA_SECTION_NODE:
+        case XML_ENTITY_REF_NODE:
+        case XML_ENTITY_NODE:
+        case XML_PI_NODE:
+        case XML_COMMENT_NODE:
+        case XML_DTD_NODE:
+        case XML_XINCLUDE_START:
+        case XML_XINCLUDE_END:
+            node = node->next;
+            break;
+        default:
+            return(NULL);
+    }
+    while (node != NULL) {
+        if (node->type == XML_ELEMENT_NODE)
+            return(node);
+        node = node->next;
+    }
+    return(NULL);
+}
+
+#endif /* LIBXML_TREE_ENABLED */
+
 /**
  * xmlFreeNodeList:
  * @cur:  the first node in the list
@@ -3450,6 +3668,11 @@
 
     if (cur->doc != NULL) dict = cur->doc->dict;
 
+    if (cur->type == XML_ENTITY_DECL) {
+        xmlEntityPtr ent = (xmlEntityPtr) cur;
+	DICT_FREE(ent->SystemID);
+	DICT_FREE(ent->ExternalID);
+    }
     if ((cur->children != NULL) &&
 	(cur->type != XML_ENTITY_REF_NODE))
 	xmlFreeNodeList(cur->children);
@@ -3510,6 +3733,28 @@
 		doc->extSubset = NULL;
 	}
     }
+    if (cur->type == XML_ENTITY_DECL) {
+        xmlDocPtr doc;
+	doc = cur->doc;
+	if (doc != NULL) {
+	    if (doc->intSubset != NULL) {
+	        if (xmlHashLookup(doc->intSubset->entities, cur->name) == cur)
+		    xmlHashRemoveEntry(doc->intSubset->entities, cur->name,
+		                       NULL);
+	        if (xmlHashLookup(doc->intSubset->pentities, cur->name) == cur)
+		    xmlHashRemoveEntry(doc->intSubset->pentities, cur->name,
+		                       NULL);
+	    }
+	    if (doc->extSubset != NULL) {
+	        if (xmlHashLookup(doc->extSubset->entities, cur->name) == cur)
+		    xmlHashRemoveEntry(doc->extSubset->entities, cur->name,
+		                       NULL);
+	        if (xmlHashLookup(doc->extSubset->pentities, cur->name) == cur)
+		    xmlHashRemoveEntry(doc->extSubset->pentities, cur->name,
+		                       NULL);
+	    }
+	}
+    }
     if (cur->parent != NULL) {
 	xmlNodePtr parent;
 	parent = cur->parent;
@@ -3605,7 +3850,7 @@
  *		Copy operations						*
  *									*
  ************************************************************************/
- 
+
 /**
  * xmlCopyNamespace:
  * @cur:  the namespace
@@ -3722,7 +3967,7 @@
           ret->ns = xmlNewReconciliedNs(target->doc, target, cur->ns);
         }
       }
- 
+
     } else
         ret->ns = NULL;
 
@@ -3843,7 +4088,7 @@
 		return((xmlNodePtr) xmlCopyPropInternal(doc, parent, (xmlAttrPtr) node));
         case XML_NAMESPACE_DECL:
 	    return((xmlNodePtr) xmlCopyNamespaceList((xmlNsPtr) node));
-	    
+
         case XML_DOCUMENT_NODE:
         case XML_HTML_DOCUMENT_NODE:
 #ifdef LIBXML_DOCB_ENABLED
@@ -3873,7 +4118,7 @@
     ret->type = node->type;
 
     ret->doc = doc;
-    ret->parent = parent; 
+    ret->parent = parent;
     if (node->name == xmlStringText)
 	ret->name = xmlStringText;
     else if (node->name == xmlStringTextNoenc)
@@ -3912,7 +4157,7 @@
 	if (tmp != ret)
 	    return(tmp);
     }
-    
+
     if (!extended)
 	goto out;
     if ((node->type == XML_ELEMENT_NODE) && (node->nsDef != NULL))
@@ -4108,7 +4353,7 @@
     if (dtd->pentities != NULL)
 	ret->pentities = (void *) xmlCopyEntitiesTable(
 			    (xmlEntitiesTablePtr) dtd->pentities);
-    
+
     cur = dtd->children;
     while (cur != NULL) {
 	q = NULL;
@@ -4123,7 +4368,7 @@
 		    break;
 		case XML_INTERNAL_PARAMETER_ENTITY:
 		case XML_EXTERNAL_PARAMETER_ENTITY:
-    		    q = (xmlNodePtr) 
+		    q = (xmlNodePtr)
 			xmlGetParameterEntityFromDtd(ret, tmp->name);
 		    break;
 		case XML_INTERNAL_PREDEFINED_ENTITY:
@@ -4135,27 +4380,27 @@
 		xmlGetDtdQElementDesc(ret, tmp->name, tmp->prefix);
 	} else if (cur->type == XML_ATTRIBUTE_DECL) {
 	    xmlAttributePtr tmp = (xmlAttributePtr) cur;
-	    q = (xmlNodePtr) 
+	    q = (xmlNodePtr)
 		xmlGetDtdQAttrDesc(ret, tmp->elem, tmp->name, tmp->prefix);
 	} else if (cur->type == XML_COMMENT_NODE) {
 	    q = xmlCopyNode(cur, 0);
 	}
-	
+
 	if (q == NULL) {
 	    cur = cur->next;
 	    continue;
 	}
-	
+
 	if (p == NULL)
 	    ret->children = q;
 	else
-    	    p->next = q;
-	
-    	q->prev = p;
-    	q->parent = (xmlNodePtr) ret;
+	    p->next = q;
+
+	q->prev = p;
+	q->parent = (xmlNodePtr) ret;
 	q->next = NULL;
 	ret->last = q;
-    	p = q;
+	p = q;
 	cur = cur->next;
     }
 
@@ -4205,7 +4450,7 @@
         ret->oldNs = xmlCopyNamespaceList(doc->oldNs);
     if (doc->children != NULL) {
 	xmlNodePtr tmp;
-	
+
 	ret->children = xmlStaticCopyNodeList(doc->children, ret,
 		                               (xmlNodePtr)ret);
 	ret->last = NULL;
@@ -4225,7 +4470,7 @@
  *		Content access functions				*
  *									*
  ************************************************************************/
- 
+
 /**
  * xmlGetLineNo:
  * @node: valid node
@@ -4317,7 +4562,7 @@
             if (cur->ns) {
 		if (cur->ns->prefix != NULL) {
                     snprintf(nametemp, sizeof(nametemp) - 1, "%s:%s",
-		    	(char *)cur->ns->prefix, (char *)cur->name);
+			(char *)cur->ns->prefix, (char *)cur->name);
 		    nametemp[sizeof(nametemp) - 1] = 0;
 		    name = nametemp;
 		} else {
@@ -4327,7 +4572,7 @@
 		    */
 		    generic = 1;
 		    name = "*";
-		}                
+		}
             }
             next = cur->parent;
 
@@ -4415,7 +4660,7 @@
 		    {
 			occur = 1;
 			break;
-		    }			
+		    }
 		    tmp = tmp->next;
 		}
             } else
@@ -4458,10 +4703,10 @@
             if (cur->ns) {
 	        if (cur->ns->prefix != NULL)
                     snprintf(nametemp, sizeof(nametemp) - 1, "%s:%s",
-		    	(char *)cur->ns->prefix, (char *)cur->name);
+			(char *)cur->ns->prefix, (char *)cur->name);
 		else
 		    snprintf(nametemp, sizeof(nametemp) - 1, "%s",
-		    	(char *)cur->name);
+			(char *)cur->name);
                 nametemp[sizeof(nametemp) - 1] = 0;
                 name = nametemp;
             }
@@ -4529,7 +4774,7 @@
     }
     return(ret);
 }
- 
+
 #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_WRITER_ENABLED)
 /**
  * xmlDocSetRootElement:
@@ -4571,7 +4816,7 @@
     return(old);
 }
 #endif
- 
+
 #if defined(LIBXML_TREE_ENABLED)
 /**
  * xmlNodeSetLang:
@@ -4619,7 +4864,7 @@
     xmlSetNsProp(cur, ns, BAD_CAST "lang", lang);
 }
 #endif /* LIBXML_TREE_ENABLED */
- 
+
 /**
  * xmlNodeGetLang:
  * @cur:  the node being checked
@@ -4642,7 +4887,7 @@
     }
     return(NULL);
 }
- 
+
 
 #ifdef LIBXML_TREE_ENABLED
 /**
@@ -4730,7 +4975,7 @@
     }
     return(-1);
 }
- 
+
 #ifdef LIBXML_TREE_ENABLED
 /**
  * xmlNodeSetName:
@@ -4788,7 +5033,7 @@
     }
 }
 #endif
- 
+
 #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XINCLUDE_ENABLED)
 /**
  * xmlNodeSetBase:
@@ -4841,7 +5086,7 @@
 	    return;
 	}
     }
-    
+
     ns = xmlSearchNsByHref(cur->doc, cur, XML_XML_NAMESPACE);
     if (ns == NULL)
 	return;
@@ -4877,9 +5122,9 @@
     xmlChar *oldbase = NULL;
     xmlChar *base, *newbase;
 
-    if ((cur == NULL) && (doc == NULL)) 
+    if ((cur == NULL) && (doc == NULL))
         return(NULL);
-    if (doc == NULL) doc = cur->doc;	
+    if (doc == NULL) doc = cur->doc;
     if ((doc != NULL) && (doc->type == XML_HTML_DOCUMENT_NODE)) {
         cur = doc->children;
 	while ((cur != NULL) && (cur->name != NULL)) {
@@ -4941,7 +5186,7 @@
     }
     return(oldbase);
 }
- 
+
 /**
  * xmlNodeBufGetContent:
  * @buffer:  a buffer
@@ -4952,7 +5197,7 @@
  * of the values carried by this node child's (TEXT and ENTITY_REF).
  * Entity references are substituted.
  * Fills up the buffer @buffer with this value
- * 
+ *
  * Returns 0 in case of success and -1 in case of error.
  */
 int
@@ -5231,12 +5476,12 @@
 	        if (!((cur->doc != NULL) && (cur->doc->dict != NULL) &&
 		    (xmlDictOwns(cur->doc->dict, cur->content))))
 		    xmlFree(cur->content);
-	    }	
+	    }
 	    if (cur->children != NULL) xmlFreeNodeList(cur->children);
 	    cur->last = cur->children = NULL;
 	    if (content != NULL) {
 		cur->content = xmlStrdup(content);
-	    } else 
+	    } else
 		cur->content = NULL;
 	    cur->properties = NULL;
 	    cur->nsDef = NULL;
@@ -5309,12 +5554,12 @@
 	        if (!((cur->doc != NULL) && (cur->doc->dict != NULL) &&
 		    (xmlDictOwns(cur->doc->dict, cur->content))))
 		    xmlFree(cur->content);
-	    }	
+	    }
 	    if (cur->children != NULL) xmlFreeNodeList(cur->children);
 	    cur->children = cur->last = NULL;
 	    if (content != NULL) {
 		cur->content = xmlStrndup(content, len);
-	    } else 
+	    } else
 		cur->content = NULL;
 	    cur->properties = NULL;
 	    cur->nsDef = NULL;
@@ -5348,7 +5593,7 @@
  * @cur:  the node being modified
  * @content:  extra content
  * @len:  the size of @content
- * 
+ *
  * Append the extra substring to the node content.
  * NOTE: In contrast to xmlNodeSetContentLen(), @content is supposed to be
  *       raw text, so unescaped XML special chars are allowed, entity
@@ -5423,7 +5668,7 @@
  * xmlNodeAddContent:
  * @cur:  the node being modified
  * @content:  extra content
- * 
+ *
  * Append the extra substring to the node content.
  * NOTE: In contrast to xmlNodeSetContent(), @content is supposed to be
  *       raw text, so unescaped XML special chars are allowed, entity
@@ -5449,7 +5694,7 @@
  * xmlTextMerge:
  * @first:  the first text node
  * @second:  the second text node being merged
- * 
+ *
  * Merge two text nodes into one
  * Returns the first text node augmented
  */
@@ -5534,9 +5779,9 @@
 /*
 * xmlTreeEnsureXMLDecl:
 * @doc: the doc
-* 
+*
 * Ensures that there is an XML namespace declaration on the doc.
-* 
+*
 * Returns the XML ns-struct or NULL on API and internal errors.
 */
 static xmlNsPtr
@@ -5556,7 +5801,7 @@
 	}
 	memset(ns, 0, sizeof(xmlNs));
 	ns->type = XML_LOCAL_NAMESPACE;
-	ns->href = xmlStrdup(XML_XML_NAMESPACE); 
+	ns->href = xmlStrdup(XML_XML_NAMESPACE);
 	ns->prefix = xmlStrdup((const xmlChar *)"xml");
 	doc->oldNs = ns;
 	return (ns);
@@ -5581,7 +5826,7 @@
  */
 xmlNsPtr
 xmlSearchNs(xmlDocPtr doc, xmlNodePtr node, const xmlChar *nameSpace) {
-	
+
     xmlNsPtr cur;
     xmlNodePtr orig = node;
 
@@ -5601,8 +5846,8 @@
 	    }
 	    memset(cur, 0, sizeof(xmlNs));
 	    cur->type = XML_LOCAL_NAMESPACE;
-	    cur->href = xmlStrdup(XML_XML_NAMESPACE); 
-	    cur->prefix = xmlStrdup((const xmlChar *)"xml"); 
+	    cur->href = xmlStrdup(XML_XML_NAMESPACE);
+	    cur->prefix = xmlStrdup((const xmlChar *)"xml");
 	    cur->next = node->nsDef;
 	    node->nsDef = cur;
 	    return(cur);
@@ -5637,7 +5882,7 @@
 		    return(cur);
 		cur = cur->next;
 	    }
-	    if (orig != node) { 
+	    if (orig != node) {
 	        cur = node->ns;
 	        if (cur != NULL) {
 		    if ((cur->prefix == NULL) && (nameSpace == NULL) &&
@@ -5648,7 +5893,7 @@
 		        (xmlStrEqual(cur->prefix, nameSpace)))
 		        return(cur);
 	        }
-	    }    
+	    }
 	}
 	node = node->parent;
     }
@@ -5664,7 +5909,7 @@
  *
  * Verify that the given namespace held on @ancestor is still in scope
  * on node.
- * 
+ *
  * Returns 1 if true, 0 if false and -1 in case of error.
  */
 static int
@@ -5697,7 +5942,7 @@
         return (-1);
     return (1);
 }
-                  
+
 /**
  * xmlSearchNsByHref:
  * @doc:  the document
@@ -5751,7 +5996,7 @@
 	if (doc->oldNs == NULL)
 	    return(xmlTreeEnsureXMLDecl(doc));
 	else
-	    return(doc->oldNs);        
+	    return(doc->oldNs);
     }
     is_attr = (node->type == XML_ATTRIBUTE_NODE);
     while (node != NULL) {
@@ -5780,7 +6025,7 @@
 			    return (cur);
                     }
                 }
-            }    
+            }
         }
         node = node->parent;
     }
@@ -5843,7 +6088,7 @@
 	    snprintf((char *) prefix, sizeof(prefix), "default%d", counter++);
 	else
 	    snprintf((char *) prefix, sizeof(prefix), "%.20s%d",
-	    	(char *)ns->prefix, counter++);
+		(char *)ns->prefix, counter++);
 	def = xmlSearchNs(doc, tree, prefix);
     }
 
@@ -6038,7 +6283,7 @@
 		}
 	    }
 	    /* exit condition */
-	    if (node == tree) 
+	    if (node == tree)
 	        node = NULL;
 	} else
 	    break;
@@ -6094,14 +6339,14 @@
     /*
      * Check if there is a default/fixed attribute declaration in
      * the internal or external subset.
-     */    
+     */
     if ((node->doc != NULL) && (node->doc->intSubset != NULL)) {
 	xmlDocPtr doc = node->doc;
 	xmlAttributePtr attrDecl = NULL;
 	xmlChar *elemQName, *tmpstr = NULL;
 
 	/*
-	* We need the QName of the element for the DTD-lookup.	
+	* We need the QName of the element for the DTD-lookup.
 	*/
 	if ((node->ns != NULL) && (node->ns->prefix != NULL)) {
 	    tmpstr = xmlStrdup(node->ns->prefix);
@@ -6152,7 +6397,7 @@
 		cur++;
 	    }
 	    xmlFree(nsList);
-	}	
+	}
 	if (tmpstr != NULL)
 	    xmlFree(tmpstr);
 	/*
@@ -6196,7 +6441,7 @@
     } else if (prop->type == XML_ATTRIBUTE_DECL) {
 	return(xmlStrdup(((xmlAttributePtr)prop)->defaultValue));
     }
-    return(NULL); 
+    return(NULL);
 }
 
 /**
@@ -6208,7 +6453,7 @@
  * This function also looks in DTD attribute declaration for #FIXED or
  * default declaration values unless DTD use has been turned off.
  *
- * Returns the attribute or the attribute declaration or NULL if 
+ * Returns the attribute or the attribute declaration or NULL if
  *         neither was found.
  */
 xmlAttrPtr
@@ -6290,12 +6535,12 @@
  */
 xmlChar *
 xmlGetProp(xmlNodePtr node, const xmlChar *name) {
-    xmlAttrPtr prop;    
+    xmlAttrPtr prop;
 
     prop = xmlHasProp(node, name);
     if (prop == NULL)
 	return(NULL);
-    return(xmlGetPropNodeValueInternal(prop));     
+    return(xmlGetPropNodeValueInternal(prop));
 }
 
 /**
@@ -6316,7 +6561,7 @@
 xmlChar *
 xmlGetNoNsProp(xmlNodePtr node, const xmlChar *name) {
     xmlAttrPtr prop;
-    
+
     prop = xmlGetPropNodeInternal(node, name, NULL, xmlCheckDTD);
     if (prop == NULL)
 	return(NULL);
@@ -6382,7 +6627,7 @@
 int
 xmlUnsetNsProp(xmlNodePtr node, xmlNsPtr ns, const xmlChar *name) {
     xmlAttrPtr prop;
-    
+
     prop = xmlGetPropNodeInternal(node, name, (ns != NULL) ? ns->href : NULL, 0);
     if (prop == NULL)
 	return(-1);
@@ -6405,7 +6650,7 @@
  * error it there's no such ns-binding for the prefix in
  * scope.
  * Returns the attribute pointer.
- * 
+ *
  */
 xmlAttrPtr
 xmlSetProp(xmlNodePtr node, const xmlChar *name, const xmlChar *value) {
@@ -6448,7 +6693,7 @@
 	     const xmlChar *value)
 {
     xmlAttrPtr prop;
-    
+
     if (ns && (ns->href == NULL))
 	return(NULL);
     prop = xmlGetPropNodeInternal(node, name, (ns != NULL) ? ns->href : NULL, 0);
@@ -6460,17 +6705,21 @@
 	    xmlRemoveID(node->doc, prop);
 	    prop->atype = XML_ATTRIBUTE_ID;
 	}
-	if (prop->children != NULL) 
+	if (prop->children != NULL)
 	    xmlFreeNodeList(prop->children);
 	prop->children = NULL;
 	prop->last = NULL;
 	prop->ns = ns;
 	if (value != NULL) {
-	    xmlChar *buffer;
 	    xmlNodePtr tmp;
-	    
-	    buffer = xmlEncodeEntitiesReentrant(node->doc, value);
-	    prop->children = xmlStringGetNodeList(node->doc, buffer);
+
+	    if(!xmlCheckUTF8(value)) {
+	        xmlTreeErr(XML_TREE_NOT_UTF8, (xmlNodePtr) node->doc,
+	                   NULL);
+                if (node->doc != NULL)
+                    node->doc->encoding = xmlStrdup(BAD_CAST "ISO-8859-1");
+	    }
+	    prop->children = xmlNewDocText(node->doc, value);
 	    prop->last = NULL;
 	    tmp = prop->children;
 	    while (tmp != NULL) {
@@ -6479,7 +6728,6 @@
 		    prop->last = tmp;
 		tmp = tmp->next;
 	    }
-	    xmlFree(buffer);
 	}
 	if (prop->atype == XML_ATTRIBUTE_ID)
 	    xmlAddID(NULL, node->doc, value, prop);
@@ -6496,7 +6744,7 @@
 /**
  * xmlNodeIsText:
  * @node:  the node
- * 
+ *
  * Is this node a Text node ?
  * Returns 1 yes, 0 no
  */
@@ -6511,7 +6759,7 @@
 /**
  * xmlIsBlankNode:
  * @node:  the node
- * 
+ *
  * Checks whether this node is an empty or whitespace only
  * (and possibly ignorable) text-node.
  *
@@ -6540,7 +6788,7 @@
  * @node:  the node
  * @content:  the content
  * @len:  @content length
- * 
+ *
  * Concat the given string at the end of the existing node content
  *
  * Returns -1 in case of error, 0 otherwise
@@ -6605,6 +6853,7 @@
         return(NULL);
     }
     ret->content[0] = 0;
+    ret->contentIO = NULL;
     return(ret);
 }
 
@@ -6637,6 +6886,7 @@
         ret->content[0] = 0;
     } else
 	ret->content = NULL;
+    ret->contentIO = NULL;
     return(ret);
 }
 
@@ -6678,7 +6928,7 @@
  * Sets the allocation scheme for this buffer
  */
 void
-xmlBufferSetAllocationScheme(xmlBufferPtr buf, 
+xmlBufferSetAllocationScheme(xmlBufferPtr buf,
                              xmlBufferAllocationScheme scheme) {
     if (buf == NULL) {
 #ifdef DEBUG_BUFFER
@@ -6687,9 +6937,12 @@
 #endif
         return;
     }
-    if (buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) return;
-
-    buf->alloc = scheme;
+    if ((buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) ||
+        (buf->alloc == XML_BUFFER_ALLOC_IO)) return;
+    if ((scheme == XML_BUFFER_ALLOC_DOUBLEIT) ||
+        (scheme == XML_BUFFER_ALLOC_EXACT) ||
+        (scheme == XML_BUFFER_ALLOC_IMMUTABLE))
+	buf->alloc = scheme;
 }
 
 /**
@@ -6709,7 +6962,10 @@
 	return;
     }
 
-    if ((buf->content != NULL) &&
+    if ((buf->alloc == XML_BUFFER_ALLOC_IO) &&
+        (buf->contentIO != NULL)) {
+        xmlFree(buf->contentIO);
+    } else if ((buf->content != NULL) &&
         (buf->alloc != XML_BUFFER_ALLOC_IMMUTABLE)) {
         xmlFree(buf->content);
     }
@@ -6729,8 +6985,15 @@
     buf->use = 0;
     if (buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) {
         buf->content = BAD_CAST "";
+    } else if ((buf->alloc == XML_BUFFER_ALLOC_IO) &&
+               (buf->contentIO != NULL)) {
+        size_t start_buf = buf->content - buf->contentIO;
+
+	buf->size += start_buf;
+        buf->content = buf->contentIO;
+        buf->content[0] = 0;
     } else {
-	memset(buf->content, 0, buf->size);
+        buf->content[0] = 0;
     }
 }
 
@@ -6750,10 +7013,30 @@
     if (len > buf->use) return(-1);
 
     buf->use -= len;
-    if (buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) {
+    if ((buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) ||
+        ((buf->alloc == XML_BUFFER_ALLOC_IO) && (buf->contentIO != NULL))) {
+	/*
+	 * we just move the content pointer, but also make sure
+	 * the perceived buffer size has shrinked accordingly
+	 */
         buf->content += len;
+	buf->size -= len;
+
+        /*
+	 * sometimes though it maybe be better to really shrink
+	 * on IO buffers
+	 */
+	if ((buf->alloc == XML_BUFFER_ALLOC_IO) && (buf->contentIO != NULL)) {
+	    size_t start_buf = buf->content - buf->contentIO;
+	    if (start_buf >= buf->size) {
+		memmove(buf->contentIO, &buf->content[0], buf->use);
+		buf->content = buf->contentIO;
+		buf->content[buf->use] = 0;
+		buf->size += start_buf;
+	    }
+	}
     } else {
-	memmove(buf->content, &buf->content[len], buf->use * sizeof(xmlChar));
+	memmove(buf->content, &buf->content[len], buf->use);
 	buf->content[buf->use] = 0;
     }
     return(len);
@@ -6791,12 +7074,24 @@
     size = buf->use + len + 100;
 #endif
 
-    newbuf = (xmlChar *) xmlRealloc(buf->content, size);
-    if (newbuf == NULL) {
-	xmlTreeErrMemory("growing buffer");
-        return(-1);
+    if ((buf->alloc == XML_BUFFER_ALLOC_IO) && (buf->contentIO != NULL)) {
+        size_t start_buf = buf->content - buf->contentIO;
+
+	newbuf = (xmlChar *) xmlRealloc(buf->contentIO, start_buf + size);
+	if (newbuf == NULL) {
+	    xmlTreeErrMemory("growing buffer");
+	    return(-1);
+	}
+	buf->contentIO = newbuf;
+	buf->content = newbuf + start_buf;
+    } else {
+	newbuf = (xmlChar *) xmlRealloc(buf->content, size);
+	if (newbuf == NULL) {
+	    xmlTreeErrMemory("growing buffer");
+	    return(-1);
+	}
+	buf->content = newbuf;
     }
-    buf->content = newbuf;
     buf->size = size;
     return(buf->size - buf->use);
 }
@@ -6853,7 +7148,7 @@
 
 /**
  * xmlBufferLength:
- * @buf:  the buffer 
+ * @buf:  the buffer
  *
  * Function to get the length of a buffer
  *
@@ -6883,6 +7178,7 @@
 {
     unsigned int newSize;
     xmlChar* rebuf = NULL;
+    size_t start_buf;
 
     if (buf == NULL)
         return(0);
@@ -6895,42 +7191,68 @@
 
     /* figure out new size */
     switch (buf->alloc){
-    case XML_BUFFER_ALLOC_DOUBLEIT:
-	/*take care of empty case*/
-        newSize = (buf->size ? buf->size*2 : size + 10);
-        while (size > newSize) newSize *= 2;
-        break;
-    case XML_BUFFER_ALLOC_EXACT:
-        newSize = size+10;
-        break;
-    default:
-        newSize = size+10;
-        break;
+	case XML_BUFFER_ALLOC_IO:
+	case XML_BUFFER_ALLOC_DOUBLEIT:
+	    /*take care of empty case*/
+	    newSize = (buf->size ? buf->size*2 : size + 10);
+	    while (size > newSize) {
+	        if (newSize > UINT_MAX / 2) {
+	            xmlTreeErrMemory("growing buffer");
+	            return 0;
+	        }
+	        newSize *= 2;
+	    }
+	    break;
+	case XML_BUFFER_ALLOC_EXACT:
+	    newSize = size+10;
+	    break;
+	default:
+	    newSize = size+10;
+	    break;
     }
 
-    if (buf->content == NULL)
-	rebuf = (xmlChar *) xmlMallocAtomic(newSize * sizeof(xmlChar));
-    else if (buf->size - buf->use < 100) {
-	rebuf = (xmlChar *) xmlRealloc(buf->content, 
-				       newSize * sizeof(xmlChar));
-   } else {
-        /*
-	 * if we are reallocating a buffer far from being full, it's
-	 * better to make a new allocation and copy only the used range
-	 * and free the old one.
-	 */
-	rebuf = (xmlChar *) xmlMallocAtomic(newSize * sizeof(xmlChar));
-	if (rebuf != NULL) {
-	    memcpy(rebuf, buf->content, buf->use);
-	    xmlFree(buf->content);
-	    rebuf[buf->use] = 0;
+    if ((buf->alloc == XML_BUFFER_ALLOC_IO) && (buf->contentIO != NULL)) {
+        start_buf = buf->content - buf->contentIO;
+
+        if (start_buf > newSize) {
+	    /* move data back to start */
+	    memmove(buf->contentIO, buf->content, buf->use);
+	    buf->content = buf->contentIO;
+	    buf->content[buf->use] = 0;
+	    buf->size += start_buf;
+	} else {
+	    rebuf = (xmlChar *) xmlRealloc(buf->contentIO, start_buf + newSize);
+	    if (rebuf == NULL) {
+		xmlTreeErrMemory("growing buffer");
+		return 0;
+	    }
+	    buf->contentIO = rebuf;
+	    buf->content = rebuf + start_buf;
 	}
+    } else {
+	if (buf->content == NULL) {
+	    rebuf = (xmlChar *) xmlMallocAtomic(newSize);
+	} else if (buf->size - buf->use < 100) {
+	    rebuf = (xmlChar *) xmlRealloc(buf->content, newSize);
+        } else {
+	    /*
+	     * if we are reallocating a buffer far from being full, it's
+	     * better to make a new allocation and copy only the used range
+	     * and free the old one.
+	     */
+	    rebuf = (xmlChar *) xmlMallocAtomic(newSize);
+	    if (rebuf != NULL) {
+		memcpy(rebuf, buf->content, buf->use);
+		xmlFree(buf->content);
+		rebuf[buf->use] = 0;
+	    }
+	}
+	if (rebuf == NULL) {
+	    xmlTreeErrMemory("growing buffer");
+	    return 0;
+	}
+	buf->content = rebuf;
     }
-    if (rebuf == NULL) {
-	xmlTreeErrMemory("growing buffer");
-        return 0;
-    }
-    buf->content = rebuf;
     buf->size = newSize;
 
     return 1;
@@ -7025,6 +7347,20 @@
 
     if (len <= 0) return -1;
 
+    if ((buf->alloc == XML_BUFFER_ALLOC_IO) && (buf->contentIO != NULL)) {
+        size_t start_buf = buf->content - buf->contentIO;
+
+	if (start_buf > (unsigned int) len) {
+	    /*
+	     * We can add it in the space previously shrinked
+	     */
+	    buf->content -= len;
+            memmove(&buf->content[0], str, len);
+	    buf->use += len;
+	    buf->size += len;
+	    return(0);
+	}
+    }
     needSize = buf->use + len + 2;
     if (needSize > buf->size){
         if (!xmlBufferResize(buf, needSize)){
@@ -7033,8 +7369,8 @@
         }
     }
 
-    memmove(&buf->content[len], &buf->content[0], buf->use * sizeof(xmlChar));
-    memmove(&buf->content[0], str, len * sizeof(xmlChar));
+    memmove(&buf->content[len], &buf->content[0], buf->use);
+    memmove(&buf->content[0], str, len);
     buf->use += len;
     buf->content[buf->use] = 0;
     return 0;
@@ -7281,7 +7617,7 @@
 /*
 * xmlDOMWrapNsMapFree:
 * @map: the ns-map
-* 
+*
 * Frees the ns-map
 */
 static void
@@ -7312,7 +7648,7 @@
 * @oldNs: the old ns-struct
 * @newNs: the new ns-struct
 * @depth: depth and ns-kind information
-* 
+*
 * Adds an ns-mapping item.
 */
 static xmlNsMapItemPtr
@@ -7340,7 +7676,7 @@
 	memset(map, 0, sizeof(struct xmlNsMap));
 	*nsmap = map;
     }
-    
+
     if (map->pool != NULL) {
 	/*
 	* Reuse an item from the pool.
@@ -7359,11 +7695,11 @@
 	}
 	memset(ret, 0, sizeof(struct xmlNsMapItem));
     }
-    
+
     if (map->first == NULL) {
 	/*
 	* First ever.
-	*/	 
+	*/
 	map->first = ret;
 	map->last = ret;
     } else if (position == -1) {
@@ -7372,14 +7708,14 @@
 	*/
 	ret->prev = map->last;
 	map->last->next = ret;
-	map->last = ret;		
+	map->last = ret;
     } else if (position == 0) {
 	/*
 	* Set on first position.
 	*/
 	map->first->prev = ret;
-	ret->next = map->first;		
-	map->first = ret;		
+	ret->next = map->first;
+	map->first = ret;
     } else
 	return(NULL);
 
@@ -7395,10 +7731,10 @@
 * @doc: the doc
 * @nsName: the namespace name
 * @prefix: the prefix
-* 
+*
 * Creates or reuses an xmlNs struct on doc->oldNs with
 * the given prefix and namespace name.
-* 
+*
 * Returns the aquired ns struct or NULL in case of an API
 *         or internal error.
 */
@@ -7438,7 +7774,7 @@
 *
 * Allocates and initializes a new DOM-wrapper context.
 *
-* Returns the xmlDOMWrapCtxtPtr or NULL in case of an internal errror. 
+* Returns the xmlDOMWrapCtxtPtr or NULL in case of an internal errror.
 */
 xmlDOMWrapCtxtPtr
 xmlDOMWrapNewCtxt(void)
@@ -7477,9 +7813,9 @@
 * xmlTreeLookupNsListByPrefix:
 * @nsList: a list of ns-structs
 * @prefix: the searched prefix
-* 
+*
 * Searches for a ns-decl with the given prefix in @nsList.
-* 
+*
 * Returns the ns-decl if found, NULL if not found and on
 *         API errors.
 */
@@ -7507,9 +7843,9 @@
 * xmlDOMWrapNSNormGatherInScopeNs:
 * @map: the namespace map
 * @node: the node to start with
-* 
+*
 * Puts in-scope namespaces into the ns-map.
-* 
+*
 * Returns 0 on success, -1 on API or internal errors.
 */
 static int
@@ -7601,7 +7937,7 @@
 *
 * For internal use. Adds a ns-decl mapping.
 *
-* Returns 0 on success, -1 on internal errors. 
+* Returns 0 on success, -1 on internal errors.
 */
 static int
 xmlDOMWrapNSNormAddNsMapItem2(xmlNsPtr **list, int *size, int *number,
@@ -7645,7 +7981,7 @@
 * NOTE: This function was not intensively tested.
 *
 * Returns 0 on success, 1 if the node is not supported,
-*         -1 on API and internal errors. 
+*         -1 on API and internal errors.
 */
 int
 xmlDOMWrapRemoveNode(xmlDOMWrapCtxtPtr ctxt, xmlDocPtr doc,
@@ -7662,7 +7998,7 @@
     if (node->parent == NULL)
 	return (0);
 
-    switch (node->type) {    	
+    switch (node->type) {
 	case XML_TEXT_NODE:
 	case XML_CDATA_SECTION_NODE:
 	case XML_ENTITY_REF_NODE:
@@ -7670,7 +8006,7 @@
 	case XML_COMMENT_NODE:
 	    xmlUnlinkNode(node);
 	    return (0);
-	case XML_ELEMENT_NODE:	    
+	case XML_ELEMENT_NODE:
 	case XML_ATTRIBUTE_NODE:
 	    break;
 	default:
@@ -7694,7 +8030,7 @@
 		}
 		/* No break on purpose. */
 	    case XML_ATTRIBUTE_NODE:
-		if (node->ns != NULL) {		    
+		if (node->ns != NULL) {
 		    /*
 		    * Find a mapping.
 		    */
@@ -7738,14 +8074,14 @@
 		break;
 	    default:
 		goto next_sibling;
-	}	
-next_node:	 
+	}
+next_node:
 	if ((node->type == XML_ELEMENT_NODE) &&
 	    (node->children != NULL)) {
 	    node = node->children;
 	    continue;
 	}
-next_sibling:	
+next_sibling:
 	if (node == NULL)
 	    break;
 	if (node->next != NULL)
@@ -7838,7 +8174,7 @@
 			*/
 			if (out) {
 			    int ret;
-			    
+
 			    ret = xmlNsInScope(doc, node, prev, ns->prefix);
 			    if (ret < 0)
 				return (-1);
@@ -7906,7 +8242,7 @@
 	if (cur->type == XML_ELEMENT_NODE) {
 	    if (cur->nsDef != NULL) {
 		ns = cur->nsDef;
-		do {		
+		do {
 		    if ((prefix == ns->prefix) ||
 			xmlStrEqual(prefix, ns->prefix))
 		    {
@@ -7920,7 +8256,7 @@
 			return (1);
 		    }
 		    ns = ns->next;
-		} while (ns != NULL);	
+		} while (ns != NULL);
 	    }
 	} else if ((cur->type == XML_ENTITY_NODE) ||
             (cur->type == XML_ENTITY_DECL))
@@ -8027,12 +8363,12 @@
 				   xmlNsPtr ns,
 				   xmlNsPtr *retNs,
 				   xmlNsMapPtr *nsMap,
-				   
+
 				   int depth,
 				   int ancestorsOnly,
 				   int prefixed)
 {
-    xmlNsMapItemPtr mi;    
+    xmlNsMapItemPtr mi;
 
     if ((doc == NULL) || (ns == NULL) || (retNs == NULL) ||
 	(nsMap == NULL))
@@ -8057,13 +8393,13 @@
     */
     if ((XML_NSMAP_NOTEMPTY(*nsMap)) &&
 	(! (ancestorsOnly && (elem == NULL))))
-    {	
+    {
 	/*
 	* Try to find an equal ns-name in in-scope ns-decls.
 	*/
 	XML_NSMAP_FOREACH(*nsMap, mi) {
-	    if ((mi->depth >= XML_TREE_NSMAP_PARENT) && 				
-		/* 
+	    if ((mi->depth >= XML_TREE_NSMAP_PARENT) &&
+		/*
 		* ancestorsOnly: This should be turned on to gain speed,
 		* if one knows that the branch itself was already
 		* ns-wellformed and no stale references existed.
@@ -8071,10 +8407,10 @@
 		*/
 		((! ancestorsOnly) || (mi->depth == XML_TREE_NSMAP_PARENT)) &&
 		/* Skip shadowed prefixes. */
-		(mi->shadowDepth == -1) &&		
+		(mi->shadowDepth == -1) &&
 		/* Skip xmlns="" or xmlns:foo="". */
 		((mi->newNs->href != NULL) &&
-		(mi->newNs->href[0] != 0)) &&		
+		(mi->newNs->href[0] != 0)) &&
 		/* Ensure a prefix if wanted. */
 		((! prefixed) || (mi->newNs->prefix != NULL)) &&
 		/* Equal ns name */
@@ -8101,7 +8437,7 @@
 	    return (-1);
 	/*
 	* Insert mapping.
-	*/	
+	*/
 	if (xmlDOMWrapNsMapAddItem(nsMap, -1, ns,
 		tmpns, XML_TREE_NSMAP_DOC) == NULL) {
 	    xmlFreeNs(tmpns);
@@ -8143,7 +8479,7 @@
 }
 
 typedef enum {
-    XML_DOM_RECONNS_REMOVEREDUND = 1<<0    
+    XML_DOM_RECONNS_REMOVEREDUND = 1<<0
 } xmlDOMReconcileNSOptions;
 
 /*
@@ -8161,7 +8497,7 @@
 * NOTE: This function was not intensively tested.
 *
 * Returns 0 if succeeded, -1 otherwise and on API/internal errors.
-*/   
+*/
 
 int
 xmlDOMWrapReconcileNamespaces(xmlDOMWrapCtxtPtr ctxt ATTRIBUTE_UNUSED,
@@ -8176,7 +8512,7 @@
     xmlNsMapItemPtr /* topmi = NULL, */ mi;
     /* @ancestorsOnly should be set by an option flag. */
     int ancestorsOnly = 0;
-    int optRemoveRedundantNS = 
+    int optRemoveRedundantNS =
 	((xmlDOMReconcileNSOptions) options & XML_DOM_RECONNS_REMOVEREDUND) ? 1 : 0;
     xmlNsPtr *listRedund = NULL;
     int sizeRedund = 0, nbRedund = 0, ret, i, j;
@@ -8212,7 +8548,7 @@
 			    }
 			    parnsdone = 1;
 			}
-			
+
 			/*
 			* Lookup the ns ancestor-axis for equal ns-decls in scope.
 			*/
@@ -8224,7 +8560,7 @@
 				      xmlStrEqual(ns->prefix, mi->newNs->prefix)) &&
 				    ((ns->href == mi->newNs->href) ||
 				      xmlStrEqual(ns->href, mi->newNs->href)))
-				{				    
+				{
 				    /*
 				    * A redundant ns-decl was found.
 				    * Add it to the list of redundant ns-decls.
@@ -8234,11 +8570,11 @@
 					goto internal_error;
 				    /*
 				    * Remove the ns-decl from the element-node.
-				    */				    
+				    */
 				    if (prevns)
 					prevns->next = ns->next;
 				    else
-					cur->nsDef = ns->next;				    				    
+					cur->nsDef = ns->next;
 				    goto next_ns_decl;
 				}
 			    }
@@ -8249,7 +8585,7 @@
 			* ns-decl is declared on the same element.
 			*/
 			if ((cur->ns != NULL) && adoptns && (cur->ns == ns))
-			    adoptns = 0;						
+			    adoptns = 0;
 			/*
 			* Does it shadow any ns-decl?
 			*/
@@ -8259,7 +8595,7 @@
 				    (mi->shadowDepth == -1) &&
 				    ((ns->prefix == mi->newNs->prefix) ||
 				    xmlStrEqual(ns->prefix, mi->newNs->prefix))) {
-				    
+
 				    mi->shadowDepth = depth;
 				}
 			    }
@@ -8269,11 +8605,11 @@
 			*/
 			if (xmlDOMWrapNsMapAddItem(&nsMap, -1, ns, ns,
 			    depth) == NULL)
-			    goto internal_error;			
+			    goto internal_error;
 
 			prevns = ns;
 next_ns_decl:
-			ns = ns->next;			
+			ns = ns->next;
 		    }
 		}
 		if (! adoptns)
@@ -8283,7 +8619,7 @@
 		/* No ns, no fun. */
 		if (cur->ns == NULL)
 		    goto ns_end;
-		
+
 		if (! parnsdone) {
 		    if ((elem->parent) &&
 			((xmlNodePtr) elem->parent->doc != elem->parent)) {
@@ -8302,7 +8638,7 @@
 			   cur->ns = listRedund[++j];
 			   break;
 		       }
-		   } 
+		   }
 		}
 		/*
 		* Adopt ns-references.
@@ -8340,7 +8676,7 @@
 		    cur = (xmlNodePtr) cur->properties;
 		    continue;
 		}
-		break;		
+		break;
 	    default:
 		goto next_sibling;
 	}
@@ -8353,18 +8689,18 @@
 	    cur = cur->children;
 	    continue;
 	}
-next_sibling:	
+next_sibling:
 	if (cur == elem)
 	    break;
 	if (cur->type == XML_ELEMENT_NODE) {
-	    if (XML_NSMAP_NOTEMPTY(nsMap)) {	    
+	    if (XML_NSMAP_NOTEMPTY(nsMap)) {
 		/*
 		* Pop mappings.
 		*/
 		while ((nsMap->last != NULL) &&
 		    (nsMap->last->depth >= depth))
 		{
-		    XML_NSMAP_POP(nsMap, mi)		    
+		    XML_NSMAP_POP(nsMap, mi)
 		}
 		/*
 		* Unshadow.
@@ -8373,7 +8709,7 @@
 		    if (mi->shadowDepth >= depth)
 			mi->shadowDepth = -1;
 		}
-	    }	    
+	    }
 	    depth--;
 	}
 	if (cur->next != NULL)
@@ -8387,13 +8723,13 @@
 	    goto next_sibling;
 	}
     } while (cur != NULL);
-    
+
     ret = 0;
     goto exit;
 internal_error:
     ret = -1;
 exit:
-    if (listRedund) {	
+    if (listRedund) {
 	for (i = 0, j = 0; i < nbRedund; i++, j += 2) {
 	    xmlFreeNs(listRedund[j]);
 	}
@@ -8444,7 +8780,7 @@
     int parnsdone;
     /* @ancestorsOnly should be set per option. */
     int ancestorsOnly = 0;
-    
+
     /*
     * Optimize string adoption for equal or none dicts.
     */
@@ -8498,17 +8834,17 @@
 	}
 	cur->doc = destDoc;
 	switch (cur->type) {
-	    case XML_XINCLUDE_START:		
+	    case XML_XINCLUDE_START:
 	    case XML_XINCLUDE_END:
 		/*
 		* TODO
 		*/
 		return (-1);
-	    case XML_ELEMENT_NODE:   	
+	    case XML_ELEMENT_NODE:
 		curElem = cur;
 		depth++;
 		/*
-		* Namespace declarations.		
+		* Namespace declarations.
 		* - ns->href and ns->prefix are never in the dict, so
 		*   we need not move the values over to the destination dict.
 		* - Note that for custom handling of ns-references,
@@ -8532,10 +8868,10 @@
 			* NOTE: ns->prefix and ns->href are never in the dict.
 			* XML_TREE_ADOPT_STR(ns->prefix)
 			* XML_TREE_ADOPT_STR(ns->href)
-			*/			
+			*/
 			/*
 			* Does it shadow any ns-decl?
-			*/			
+			*/
 			if (XML_NSMAP_NOTEMPTY(nsMap)) {
 			    XML_NSMAP_FOREACH(nsMap, mi) {
 				if ((mi->depth >= XML_TREE_NSMAP_PARENT) &&
@@ -8543,7 +8879,7 @@
 				    ((ns->prefix == mi->newNs->prefix) ||
 				    xmlStrEqual(ns->prefix,
 				    mi->newNs->prefix))) {
-				    
+
 				    mi->shadowDepth = depth;
 				}
 			    }
@@ -8606,7 +8942,7 @@
 		    * Aquire a normalized ns-decl and add it to the map.
 		    */
 		    if (xmlDOMWrapNSNormAquireNormalizedNs(destDoc,
-			/* ns-decls on curElem or on destDoc->oldNs */			
+			/* ns-decls on curElem or on destDoc->oldNs */
 			destParent ? curElem : NULL,
 			cur->ns, &ns,
 			&nsMap, depth,
@@ -8642,7 +8978,7 @@
 		    */
 		    if ((sourceDoc != NULL) &&
 			(((xmlAttrPtr) cur)->atype == XML_ATTRIBUTE_ID))
-		    {			
+		    {
 			xmlRemoveID(sourceDoc, (xmlAttrPtr) cur);
 		    }
 		    ((xmlAttrPtr) cur)->atype = 0;
@@ -8650,13 +8986,13 @@
 		}
 		break;
 	    case XML_TEXT_NODE:
-	    case XML_CDATA_SECTION_NODE:		
+	    case XML_CDATA_SECTION_NODE:
 		/*
 		* This puts the content in the dest dict, only if
 		* it was previously in the source dict.
 		*/
-		XML_TREE_ADOPT_STR_2(cur->content)		
-		goto leave_node;	   
+		XML_TREE_ADOPT_STR_2(cur->content)
+		goto leave_node;
 	    case XML_ENTITY_REF_NODE:
 		/*
 		* Remove reference to the entitity-node.
@@ -8681,7 +9017,7 @@
 		XML_TREE_ADOPT_STR(cur->name)
 		XML_TREE_ADOPT_STR_2(cur->content)
 		break;
-	    case XML_COMMENT_NODE:	    
+	    case XML_COMMENT_NODE:
 		break;
 	    default:
 		goto internal_error;
@@ -8704,15 +9040,15 @@
 	    /*
 	    * TODO: Do we expect nsDefs on XML_XINCLUDE_START?
 	    */
-	    if (XML_NSMAP_NOTEMPTY(nsMap)) {	    
+	    if (XML_NSMAP_NOTEMPTY(nsMap)) {
 		/*
 		* Pop mappings.
 		*/
 		while ((nsMap->last != NULL) &&
 		    (nsMap->last->depth >= depth))
 		{
-		    XML_NSMAP_POP(nsMap, mi)		    
-		}		
+		    XML_NSMAP_POP(nsMap, mi)
+		}
 		/*
 		* Unshadow.
 		*/
@@ -8734,10 +9070,10 @@
 	    goto leave_node;
 	}
     }
-    
+
     goto exit;
 
-internal_error:    
+internal_error:
     ret = -1;
 
 exit:
@@ -8755,7 +9091,7 @@
 		nsMap->pool = nsMap->first;
 		nsMap->first = NULL;
 	    }
-	} else    
+	} else
 	    xmlDOMWrapNsMapFree(nsMap);
     }
     return(ret);
@@ -8777,7 +9113,7 @@
 * 2) If *no* @destParent is given, then @destDoc->oldNs entries are used.
 *    This is the case when you don't know already where the cloned branch
 *    will be added to.
-* 
+*
 * If @destParent is given, it ensures that the tree is namespace
 * wellformed by creating additional ns-decls where needed.
 * Note that, since prefixes of already existent ns-decls can be
@@ -8811,7 +9147,7 @@
     /* gather @parent's ns-decls. */
     int parnsdone = 0;
     /*
-    * @ancestorsOnly: 
+    * @ancestorsOnly:
     * TODO: @ancestorsOnly should be set per option.
     *
     */
@@ -8838,7 +9174,7 @@
 	return (-1);
     }
     if (sourceDoc == NULL)
-	sourceDoc = node->doc;    
+	sourceDoc = node->doc;
     if (sourceDoc == NULL)
         return (-1);
 
@@ -8850,7 +9186,7 @@
 	nsMap = (xmlNsMapPtr) ctxt->namespaceMap;
 
     *resNode = NULL;
-   
+
     cur = node;
     while (cur != NULL) {
 	if (cur->doc != sourceDoc) {
@@ -8859,7 +9195,7 @@
 	    * TODO: Do we need to reconciliate XIncluded nodes?
 	    * TODO: This here returns -1 in this case.
 	    */
-	    goto internal_error;	
+	    goto internal_error;
 	}
 	/*
 	* Create a new node.
@@ -8874,9 +9210,9 @@
 		break;
 	    case XML_ELEMENT_NODE:
 	    case XML_TEXT_NODE:
-	    case XML_CDATA_SECTION_NODE:	    
+	    case XML_CDATA_SECTION_NODE:
 	    case XML_COMMENT_NODE:
-	    case XML_PI_NODE:	    
+	    case XML_PI_NODE:
 	    case XML_DOCUMENT_FRAG_NODE:
 	    case XML_ENTITY_REF_NODE:
 	    case XML_ENTITY_NODE:
@@ -8888,20 +9224,20 @@
 		    xmlTreeErrMemory("xmlDOMWrapCloneNode(): allocating a node");
 		    goto internal_error;
 		}
-		memset(clone, 0, sizeof(xmlNode));		
+		memset(clone, 0, sizeof(xmlNode));
 		/*
 		* Set hierachical links.
 		*/
-		if (resultClone != NULL) {	    
+		if (resultClone != NULL) {
 		    clone->parent = parentClone;
 		    if (prevClone) {
 			prevClone->next = clone;
 			clone->prev = prevClone;
-		    } else 
+		    } else
 			parentClone->children = clone;
 		} else
 		    resultClone = clone;
-		
+
 		break;
 	    case XML_ATTRIBUTE_NODE:
 		/*
@@ -8912,7 +9248,7 @@
 		    xmlTreeErrMemory("xmlDOMWrapCloneNode(): allocating an attr-node");
 		    goto internal_error;
 		}
-		memset(clone, 0, sizeof(xmlAttr));		
+		memset(clone, 0, sizeof(xmlAttr));
 		/*
 		* Set hierachical links.
 		* TODO: Change this to add to the end of attributes.
@@ -8922,7 +9258,7 @@
 		    if (prevClone) {
 			prevClone->next = clone;
 			clone->prev = prevClone;
-		    } else 
+		    } else
 			parentClone->properties = (xmlAttrPtr) clone;
 		} else
 		    resultClone = clone;
@@ -8935,8 +9271,8 @@
 	}
 
 	clone->type = cur->type;
-	clone->doc = destDoc;	
-		
+	clone->doc = destDoc;
+
 	/*
 	* Clone the name of the node if any.
 	*/
@@ -8946,14 +9282,14 @@
 	    /*
 	    * NOTE: Although xmlStringTextNoenc is never assigned to a node
 	    *   in tree.c, it might be set in Libxslt via
-	    *   "xsl:disable-output-escaping".	   
+	    *   "xsl:disable-output-escaping".
 	    */
 	    clone->name = xmlStringTextNoenc;
 	else if (cur->name == xmlStringComment)
 	    clone->name = xmlStringComment;
 	else if (cur->name != NULL) {
 	    DICT_CONST_COPY(cur->name, clone->name);
-	}				    
+	}
 
 	switch (cur->type) {
 	    case XML_XINCLUDE_START:
@@ -8976,7 +9312,7 @@
 			    */
 			    if (xmlDOMWrapNSNormGatherInScopeNs(&nsMap,
 				destParent) == -1)
-				goto internal_error;			    
+				goto internal_error;
 			}
 			parnsdone = 1;
 		    }
@@ -8996,7 +9332,7 @@
 			}
 			memset(cloneNs, 0, sizeof(xmlNs));
 			cloneNs->type = XML_LOCAL_NAMESPACE;
-			
+
 			if (ns->href != NULL)
 			    cloneNs->href = xmlStrdup(ns->href);
 			if (ns->prefix != NULL)
@@ -9017,7 +9353,7 @@
 			    * Does it shadow any ns-decl?
 			    */
 			    if (XML_NSMAP_NOTEMPTY(nsMap)) {
-				XML_NSMAP_FOREACH(nsMap, mi) {				
+				XML_NSMAP_FOREACH(nsMap, mi) {
 				    if ((mi->depth >= XML_TREE_NSMAP_PARENT) &&
 					(mi->shadowDepth == -1) &&
 					((ns->prefix == mi->newNs->prefix) ||
@@ -9042,7 +9378,7 @@
 		}
 		/* cur->ns will be processed further down. */
 		break;
-	    case XML_ATTRIBUTE_NODE:				
+	    case XML_ATTRIBUTE_NODE:
 		/* IDs will be processed further down. */
 		/* cur->ns will be processed further down. */
 		break;
@@ -9051,12 +9387,12 @@
 		/*
 		* Note that this will also cover the values of attributes.
 		*/
-		DICT_COPY(cur->content, clone->content);		
+		DICT_COPY(cur->content, clone->content);
 		goto leave_node;
 	    case XML_ENTITY_NODE:
 		/* TODO: What to do here? */
 		goto leave_node;
-	    case XML_ENTITY_REF_NODE:		
+	    case XML_ENTITY_REF_NODE:
 		if (sourceDoc != destDoc) {
 		    if ((destDoc->intSubset) || (destDoc->extSubset)) {
 			xmlEntityPtr ent;
@@ -9096,13 +9432,13 @@
 /* handle_ns_reference: */
 	/*
 	** The following will take care of references to ns-decls ********
-	** and is intended only for element- and attribute-nodes.	
+	** and is intended only for element- and attribute-nodes.
 	**
 	*/
 	if (! parnsdone) {
 	    if (destParent && (ctxt == NULL)) {
 		if (xmlDOMWrapNSNormGatherInScopeNs(&nsMap, destParent) == -1)
-		    goto internal_error;		
+		    goto internal_error;
 	    }
 	    parnsdone = 1;
 	}
@@ -9113,7 +9449,7 @@
 	    /*
 	    * Search for a mapping.
 	    */
-	    XML_NSMAP_FOREACH(nsMap, mi) {	    
+	    XML_NSMAP_FOREACH(nsMap, mi) {
 		if ((mi->shadowDepth == -1) &&
 		    (cur->ns == mi->oldNs)) {
 		    /*
@@ -9145,7 +9481,7 @@
 	    * Aquire a normalized ns-decl and add it to the map.
 	    */
 	    if (xmlDOMWrapNSNormAquireNormalizedNs(destDoc,
-		/* ns-decls on curElem or on destDoc->oldNs */			
+		/* ns-decls on curElem or on destDoc->oldNs */
 		destParent ? curElem : NULL,
 		cur->ns, &ns,
 		&nsMap, depth,
@@ -9168,9 +9504,9 @@
 	    (clone->parent != NULL))
 	{
 	    if (xmlIsID(destDoc, clone->parent, (xmlAttrPtr) clone)) {
-	   
+
 		xmlChar *idVal;
-		
+
 		idVal = xmlNodeListGetString(cur->doc, cur->children, 1);
 		if (idVal != NULL) {
 		    if (xmlAddID(NULL, destDoc, idVal, (xmlAttrPtr) cur) == NULL) {
@@ -9186,12 +9522,12 @@
 	**
 	** The following will traverse the tree **************************
 	**
-	*	
+	*
 	* Walk the element's attributes before descending into child-nodes.
 	*/
 	if ((cur->type == XML_ELEMENT_NODE) && (cur->properties != NULL)) {
 	    prevClone = NULL;
-	    parentClone = clone;	    
+	    parentClone = clone;
 	    cur = (xmlNodePtr) cur->properties;
 	    continue;
 	}
@@ -9221,14 +9557,14 @@
 	    /*
 	    * TODO: Do we expect nsDefs on XML_XINCLUDE_START?
 	    */
-	    if (XML_NSMAP_NOTEMPTY(nsMap)) {	    
+	    if (XML_NSMAP_NOTEMPTY(nsMap)) {
 		/*
 		* Pop mappings.
 		*/
 		while ((nsMap->last != NULL) &&
 		    (nsMap->last->depth >= depth))
 		{
-		    XML_NSMAP_POP(nsMap, mi)		    
+		    XML_NSMAP_POP(nsMap, mi)
 		}
 		/*
 		* Unshadow.
@@ -9237,7 +9573,7 @@
 		    if (mi->shadowDepth >= depth)
 			mi->shadowDepth = -1;
 		}
-	    }	    
+	    }
 	    depth--;
 	}
 	if (cur->next != NULL) {
@@ -9250,7 +9586,7 @@
 	    if (clone->parent != NULL)
 		clone->parent->last = clone;
 	    clone = clone->parent;
-	    parentClone = clone->parent; 
+	    parentClone = clone->parent;
 	    /*
 	    * Process parent --> next;
 	    */
@@ -9259,14 +9595,14 @@
 	} else {
 	    /* This is for attributes only. */
 	    clone = clone->parent;
-	    parentClone = clone->parent; 
+	    parentClone = clone->parent;
 	    /*
 	    * Process parent-element --> children.
 	    */
 	    cur = cur->parent;
-	    goto into_content;	    
+	    goto into_content;
 	}
-    }        
+    }
     goto exit;
 
 internal_error:
@@ -9287,7 +9623,7 @@
 		nsMap->pool = nsMap->first;
 		nsMap->first = NULL;
 	    }
-	} else    
+	} else
 	    xmlDOMWrapNsMapFree(nsMap);
     }
     /*
@@ -9327,7 +9663,7 @@
 
     if ((attr == NULL) || (destDoc == NULL))
 	return (-1);
-    
+
     attr->doc = destDoc;
     if (attr->ns != NULL) {
 	xmlNsPtr ns = NULL;
@@ -9354,13 +9690,13 @@
 		ns = xmlDOMWrapNSNormDeclareNsForced(destDoc, destParent,
 		    attr->ns->href, attr->ns->prefix, 1);
 	    }
-	}	    
+	}
 	if (ns == NULL)
 	    goto internal_error;
 	attr->ns = ns;
-    }   
-    
-    XML_TREE_ADOPT_STR(attr->name);    
+    }
+
+    XML_TREE_ADOPT_STR(attr->name);
     attr->atype = 0;
     attr->psvi = NULL;
     /*
@@ -9375,7 +9711,7 @@
 	    case XML_TEXT_NODE:
 	    case XML_CDATA_SECTION_NODE:
 		XML_TREE_ADOPT_STR_2(cur->content)
-		break;	   
+		break;
 	    case XML_ENTITY_REF_NODE:
 		/*
 		* Remove reference to the entitity-node.
@@ -9393,7 +9729,7 @@
 			cur->content = ent->content;
 			cur->children = (xmlNodePtr) ent;
 			cur->last = (xmlNodePtr) ent;
-		    }	    	    		
+		    }
 		}
 		break;
 	    default:
@@ -9431,8 +9767,8 @@
 * 1) If @destParent is given, then nsDef entries on element-nodes are used
 * 2) If *no* @destParent is given, then @destDoc->oldNs entries are used
 *    This is the case when you have an unliked node and just want to move it
-*    to the context of 
-* 
+*    to the context of
+*
 * If @destParent is given, it ensures that the tree is namespace
 * wellformed by creating additional ns-decls where needed.
 * Note that, since prefixes of already existent ns-decls can be
@@ -9449,7 +9785,7 @@
 xmlDOMWrapAdoptNode(xmlDOMWrapCtxtPtr ctxt,
 		    xmlDocPtr sourceDoc,
 		    xmlNodePtr node,
-		    xmlDocPtr destDoc,		    
+		    xmlDocPtr destDoc,
 		    xmlNodePtr destParent,
 		    int options)
 {
@@ -9458,7 +9794,7 @@
 	return(-1);
     /*
     * Check node->doc sanity.
-    */    
+    */
     if ((node->doc != NULL) && (sourceDoc != NULL) &&
 	(node->doc != sourceDoc)) {
 	/*
@@ -9471,7 +9807,7 @@
     if (sourceDoc == destDoc)
 	return (-1);
     switch (node->type) {
-	case XML_ELEMENT_NODE:	    
+	case XML_ELEMENT_NODE:
 	case XML_ATTRIBUTE_NODE:
 	case XML_TEXT_NODE:
 	case XML_CDATA_SECTION_NODE:
@@ -9497,7 +9833,7 @@
     } else if (node->type == XML_ATTRIBUTE_NODE) {
 	    return (xmlDOMWrapAdoptAttr(ctxt, sourceDoc,
 		(xmlAttrPtr) node, destDoc, destParent, options));
-    } else {	
+    } else {
 	xmlNodePtr cur = node;
 	int adoptStr = 1;
 
@@ -9509,7 +9845,7 @@
 	    (sourceDoc->dict == destDoc->dict))
 		adoptStr = 0;
 	switch (node->type) {
-	    case XML_TEXT_NODE:	    
+	    case XML_TEXT_NODE:
 	    case XML_CDATA_SECTION_NODE:
 		XML_TREE_ADOPT_STR_2(node->content)
 		    break;
@@ -9542,7 +9878,7 @@
 	    default:
 		break;
 	}
-    }	
+    }
     return (0);
 }
 
diff --git a/uri.c b/uri.c
index 34841af..28401c8 100644
--- a/uri.c
+++ b/uri.c
@@ -1,7 +1,7 @@
 /**
  * uri.c: set of generic URI related routines 
  *
- * Reference: RFCs 2396, 2732 and 2373
+ * Reference: RFCs 3986, 2732 and 2373
  *
  * See Copyright for the status of this software.
  *
@@ -18,14 +18,10 @@
 #include <libxml/globals.h>
 #include <libxml/xmlerror.h>
 
-/************************************************************************
- *									*
- *		Macros to differentiate various character type		*
- *			directly extracted from RFC 2396		*
- *									*
- ************************************************************************/
+static void xmlCleanURI(xmlURIPtr uri);
 
 /*
+ * Old rule from 2396 used in legacy handling code
  * alpha    = lowalpha | upalpha
  */
 #define IS_ALPHA(x) (IS_LOWALPHA(x) || IS_UPALPHA(x))
@@ -61,31 +57,30 @@
 #define IS_ALPHANUM(x) (IS_ALPHA(x) || IS_DIGIT(x))
 
 /*
- * hex = digit | "A" | "B" | "C" | "D" | "E" | "F" |
- *               "a" | "b" | "c" | "d" | "e" | "f"
- */
-
-#define IS_HEX(x) ((IS_DIGIT(x)) || (((x) >= 'a') && ((x) <= 'f')) || \
-	    (((x) >= 'A') && ((x) <= 'F')))
-
-/*
  * mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
  */
 
-#define IS_MARK(x) (((x) == '-') || ((x) == '_') || ((x) == '.') ||	\
-    ((x) == '!') || ((x) == '~') || ((x) == '*') || ((x) == '\'') ||	\
+#define IS_MARK(x) (((x) == '-') || ((x) == '_') || ((x) == '.') ||     \
+    ((x) == '!') || ((x) == '~') || ((x) == '*') || ((x) == '\'') ||    \
     ((x) == '(') || ((x) == ')'))
 
-
 /*
- * reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | "," |
- * 	      "[" | "]"
+ * unwise = "{" | "}" | "|" | "\" | "^" | "`"
  */
 
-#define IS_RESERVED(x) (((x) == ';') || ((x) == '/') || ((x) == '?') ||	\
-        ((x) == ':') || ((x) == '@') || ((x) == '&') || ((x) == '=') ||	\
-	((x) == '+') || ((x) == '$') || ((x) == ',') || ((x) == '[') || \
-	((x) == ']'))
+#define IS_UNWISE(p)                                                    \
+      (((*(p) == '{')) || ((*(p) == '}')) || ((*(p) == '|')) ||         \
+       ((*(p) == '\\')) || ((*(p) == '^')) || ((*(p) == '[')) ||        \
+       ((*(p) == ']')) || ((*(p) == '`')))
+/*
+ * reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | "," |
+ *            "[" | "]"
+ */
+
+#define IS_RESERVED(x) (((x) == ';') || ((x) == '/') || ((x) == '?') || \
+        ((x) == ':') || ((x) == '@') || ((x) == '&') || ((x) == '=') || \
+        ((x) == '+') || ((x) == '$') || ((x) == ',') || ((x) == '[') || \
+        ((x) == ']'))
 
 /*
  * unreserved = alphanum | mark
@@ -94,82 +89,6 @@
 #define IS_UNRESERVED(x) (IS_ALPHANUM(x) || IS_MARK(x))
 
 /*
- * escaped = "%" hex hex
- */
-
-#define IS_ESCAPED(p) ((*(p) == '%') && (IS_HEX((p)[1])) &&		\
-	    (IS_HEX((p)[2])))
-
-/*
- * uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" |
- *                        "&" | "=" | "+" | "$" | ","
- */
-#define IS_URIC_NO_SLASH(p) ((IS_UNRESERVED(*(p))) || (IS_ESCAPED(p)) ||\
-	        ((*(p) == ';')) || ((*(p) == '?')) || ((*(p) == ':')) ||\
-	        ((*(p) == '@')) || ((*(p) == '&')) || ((*(p) == '=')) ||\
-	        ((*(p) == '+')) || ((*(p) == '$')) || ((*(p) == ',')))
-
-/*
- * pchar = unreserved | escaped | ":" | "@" | "&" | "=" | "+" | "$" | ","
- */
-#define IS_PCHAR(p) ((IS_UNRESERVED(*(p))) || (IS_ESCAPED(p)) ||	\
-	        ((*(p) == ':')) || ((*(p) == '@')) || ((*(p) == '&')) ||\
-	        ((*(p) == '=')) || ((*(p) == '+')) || ((*(p) == '$')) ||\
-	        ((*(p) == ',')))
-
-/*
- * rel_segment   = 1*( unreserved | escaped |
- *                 ";" | "@" | "&" | "=" | "+" | "$" | "," )
- */
-
-#define IS_SEGMENT(p) ((IS_UNRESERVED(*(p))) || (IS_ESCAPED(p)) ||	\
-          ((*(p) == ';')) || ((*(p) == '@')) || ((*(p) == '&')) ||	\
-	  ((*(p) == '=')) || ((*(p) == '+')) || ((*(p) == '$')) ||	\
-	  ((*(p) == ',')))
-
-/*
- * scheme = alpha *( alpha | digit | "+" | "-" | "." )
- */
-
-#define IS_SCHEME(x) ((IS_ALPHA(x)) || (IS_DIGIT(x)) ||			\
-	              ((x) == '+') || ((x) == '-') || ((x) == '.'))
-
-/*
- * reg_name = 1*( unreserved | escaped | "$" | "," |
- *                ";" | ":" | "@" | "&" | "=" | "+" )
- */
-
-#define IS_REG_NAME(p) ((IS_UNRESERVED(*(p))) || (IS_ESCAPED(p)) ||	\
-       ((*(p) == '$')) || ((*(p) == ',')) || ((*(p) == ';')) ||		\
-       ((*(p) == ':')) || ((*(p) == '@')) || ((*(p) == '&')) ||		\
-       ((*(p) == '=')) || ((*(p) == '+')))
-
-/*
- * userinfo = *( unreserved | escaped | ";" | ":" | "&" | "=" |
- *                      "+" | "$" | "," )
- */
-#define IS_USERINFO(p) ((IS_UNRESERVED(*(p))) || (IS_ESCAPED(p)) ||	\
-       ((*(p) == ';')) || ((*(p) == ':')) || ((*(p) == '&')) ||		\
-       ((*(p) == '=')) || ((*(p) == '+')) || ((*(p) == '$')) ||		\
-       ((*(p) == ',')))
-
-/*
- * uric = reserved | unreserved | escaped
- */
-
-#define IS_URIC(p) ((IS_UNRESERVED(*(p))) || (IS_ESCAPED(p)) ||		\
-	            (IS_RESERVED(*(p))))
-
-/*                                                                              
-* unwise = "{" | "}" | "|" | "\" | "^" | "`"
-*/                                                                             
-
-#define IS_UNWISE(p)                                                    \
-      (((*(p) == '{')) || ((*(p) == '}')) || ((*(p) == '|')) ||         \
-       ((*(p) == '\\')) || ((*(p) == '^')) || ((*(p) == '[')) ||        \
-       ((*(p) == ']')) || ((*(p) == '`')))  
-
-/*
  * Skip to next pointer char, handle escaped sequences
  */
 
@@ -189,6 +108,845 @@
 
 /************************************************************************
  *									*
+ *                         RFC 3986 parser				*
+ *									*
+ ************************************************************************/
+
+#define ISA_DIGIT(p) ((*(p) >= '0') && (*(p) <= '9'))
+#define ISA_ALPHA(p) (((*(p) >= 'a') && (*(p) <= 'z')) ||		\
+                      ((*(p) >= 'A') && (*(p) <= 'Z')))
+#define ISA_HEXDIG(p)							\
+       (ISA_DIGIT(p) || ((*(p) >= 'a') && (*(p) <= 'f')) ||		\
+        ((*(p) >= 'A') && (*(p) <= 'F')))
+
+/*
+ *    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
+ *                     / "*" / "+" / "," / ";" / "="
+ */
+#define ISA_SUB_DELIM(p)						\
+      (((*(p) == '!')) || ((*(p) == '$')) || ((*(p) == '&')) ||		\
+       ((*(p) == '(')) || ((*(p) == ')')) || ((*(p) == '*')) ||		\
+       ((*(p) == '+')) || ((*(p) == ',')) || ((*(p) == ';')) ||		\
+       ((*(p) == '=')))
+
+/*
+ *    gen-delims    = ":" / "/" / "?" / "#" / "[" / "]" / "@"
+ */
+#define ISA_GEN_DELIM(p)						\
+      (((*(p) == ':')) || ((*(p) == '/')) || ((*(p) == '?')) ||         \
+       ((*(p) == '#')) || ((*(p) == '[')) || ((*(p) == ']')) ||         \
+       ((*(p) == '@')))
+
+/*
+ *    reserved      = gen-delims / sub-delims
+ */
+#define ISA_RESERVED(p) (ISA_GEN_DELIM(p) || (ISA_SUB_DELIM(p)))
+
+/*
+ *    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
+ */
+#define ISA_UNRESERVED(p)						\
+      ((ISA_ALPHA(p)) || (ISA_DIGIT(p)) || ((*(p) == '-')) ||		\
+       ((*(p) == '.')) || ((*(p) == '_')) || ((*(p) == '~')))
+
+/*
+ *    pct-encoded   = "%" HEXDIG HEXDIG
+ */
+#define ISA_PCT_ENCODED(p)						\
+     ((*(p) == '%') && (ISA_HEXDIG(p + 1)) && (ISA_HEXDIG(p + 2)))
+
+/*
+ *    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
+ */
+#define ISA_PCHAR(p)							\
+     (ISA_UNRESERVED(p) || ISA_PCT_ENCODED(p) || ISA_SUB_DELIM(p) ||	\
+      ((*(p) == ':')) || ((*(p) == '@')))
+
+/**
+ * xmlParse3986Scheme:
+ * @uri:  pointer to an URI structure
+ * @str:  pointer to the string to analyze
+ *
+ * Parse an URI scheme
+ *
+ * ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
+ *
+ * Returns 0 or the error code
+ */
+static int
+xmlParse3986Scheme(xmlURIPtr uri, const char **str) {
+    const char *cur;
+
+    if (str == NULL)
+	return(-1);
+
+    cur = *str;
+    if (!ISA_ALPHA(cur))
+	return(2);
+    cur++;
+    while (ISA_ALPHA(cur) || ISA_DIGIT(cur) ||
+           (*cur == '+') || (*cur == '-') || (*cur == '.')) cur++;
+    if (uri != NULL) {
+	if (uri->scheme != NULL) xmlFree(uri->scheme);
+	uri->scheme = STRNDUP(*str, cur - *str);
+    }
+    *str = cur;
+    return(0);
+}
+
+/**
+ * xmlParse3986Fragment:
+ * @uri:  pointer to an URI structure
+ * @str:  pointer to the string to analyze
+ *
+ * Parse the query part of an URI
+ *
+ * fragment      = *( pchar / "/" / "?" )
+ * NOTE: the strict syntax as defined by 3986 does not allow '[' and ']'
+ *       in the fragment identifier but this is used very broadly for
+ *       xpointer scheme selection, so we are allowing it here to not break
+ *       for example all the DocBook processing chains.
+ *
+ * Returns 0 or the error code
+ */
+static int
+xmlParse3986Fragment(xmlURIPtr uri, const char **str)
+{
+    const char *cur;
+
+    if (str == NULL)
+        return (-1);
+
+    cur = *str;
+
+    while ((ISA_PCHAR(cur)) || (*cur == '/') || (*cur == '?') ||
+           (*cur == '[') || (*cur == ']') ||
+           ((uri != NULL) && (uri->cleanup & 1) && (IS_UNWISE(cur))))
+        NEXT(cur);
+    if (uri != NULL) {
+        if (uri->fragment != NULL)
+            xmlFree(uri->fragment);
+	if (uri->cleanup & 2)
+	    uri->fragment = STRNDUP(*str, cur - *str);
+	else
+	    uri->fragment = xmlURIUnescapeString(*str, cur - *str, NULL);
+    }
+    *str = cur;
+    return (0);
+}
+
+/**
+ * xmlParse3986Query:
+ * @uri:  pointer to an URI structure
+ * @str:  pointer to the string to analyze
+ *
+ * Parse the query part of an URI
+ *
+ * query = *uric
+ *
+ * Returns 0 or the error code
+ */
+static int
+xmlParse3986Query(xmlURIPtr uri, const char **str)
+{
+    const char *cur;
+
+    if (str == NULL)
+        return (-1);
+
+    cur = *str;
+
+    while ((ISA_PCHAR(cur)) || (*cur == '/') || (*cur == '?') ||
+           ((uri != NULL) && (uri->cleanup & 1) && (IS_UNWISE(cur))))
+        NEXT(cur);
+    if (uri != NULL) {
+        if (uri->query != NULL)
+            xmlFree(uri->query);
+	if (uri->cleanup & 2)
+	    uri->query = STRNDUP(*str, cur - *str);
+	else
+	    uri->query = xmlURIUnescapeString(*str, cur - *str, NULL);
+
+	/* Save the raw bytes of the query as well.
+	 * See: http://mail.gnome.org/archives/xml/2007-April/thread.html#00114
+	 */
+	if (uri->query_raw != NULL)
+	    xmlFree (uri->query_raw);
+	uri->query_raw = STRNDUP (*str, cur - *str);
+    }
+    *str = cur;
+    return (0);
+}
+
+/**
+ * xmlParse3986Port:
+ * @uri:  pointer to an URI structure
+ * @str:  the string to analyze
+ *
+ * Parse a port  part and fills in the appropriate fields
+ * of the @uri structure
+ *
+ * port          = *DIGIT
+ *
+ * Returns 0 or the error code
+ */
+static int
+xmlParse3986Port(xmlURIPtr uri, const char **str)
+{
+    const char *cur = *str;
+
+    if (ISA_DIGIT(cur)) {
+	if (uri != NULL)
+	    uri->port = 0;
+	while (ISA_DIGIT(cur)) {
+	    if (uri != NULL)
+		uri->port = uri->port * 10 + (*cur - '0');
+	    cur++;
+	}
+	*str = cur;
+	return(0);
+    }
+    return(1);
+}
+
+/**
+ * xmlParse3986Userinfo:
+ * @uri:  pointer to an URI structure
+ * @str:  the string to analyze
+ *
+ * Parse an user informations part and fills in the appropriate fields
+ * of the @uri structure
+ *
+ * userinfo      = *( unreserved / pct-encoded / sub-delims / ":" )
+ *
+ * Returns 0 or the error code
+ */
+static int
+xmlParse3986Userinfo(xmlURIPtr uri, const char **str)
+{
+    const char *cur;
+
+    cur = *str;
+    while (ISA_UNRESERVED(cur) || ISA_PCT_ENCODED(cur) ||
+           ISA_SUB_DELIM(cur) || (*cur == ':'))
+	NEXT(cur);
+    if (*cur == '@') {
+	if (uri != NULL) {
+	    if (uri->user != NULL) xmlFree(uri->user);
+	    if (uri->cleanup & 2)
+		uri->user = STRNDUP(*str, cur - *str);
+	    else
+		uri->user = xmlURIUnescapeString(*str, cur - *str, NULL);
+	}
+	*str = cur;
+	return(0);
+    }
+    return(1);
+}
+
+/**
+ * xmlParse3986DecOctet:
+ * @str:  the string to analyze
+ *
+ *    dec-octet     = DIGIT                 ; 0-9
+ *                  / %x31-39 DIGIT         ; 10-99
+ *                  / "1" 2DIGIT            ; 100-199
+ *                  / "2" %x30-34 DIGIT     ; 200-249
+ *                  / "25" %x30-35          ; 250-255
+ *
+ * Skip a dec-octet.
+ *
+ * Returns 0 if found and skipped, 1 otherwise
+ */
+static int
+xmlParse3986DecOctet(const char **str) {
+    const char *cur = *str;
+
+    if (!(ISA_DIGIT(cur)))
+        return(1);
+    if (!ISA_DIGIT(cur+1))
+	cur++;
+    else if ((*cur != '0') && (ISA_DIGIT(cur + 1)) && (!ISA_DIGIT(cur+2)))
+	cur += 2;
+    else if ((*cur == '1') && (ISA_DIGIT(cur + 1)) && (ISA_DIGIT(cur + 2)))
+	cur += 3;
+    else if ((*cur == '2') && (*(cur + 1) >= '0') &&
+	     (*(cur + 1) <= '4') && (ISA_DIGIT(cur + 2)))
+	cur += 3;
+    else if ((*cur == '2') && (*(cur + 1) == '5') &&
+	     (*(cur + 2) >= '0') && (*(cur + 1) <= '5'))
+	cur += 3;
+    else
+        return(1);
+    *str = cur;
+    return(0);
+}
+/**
+ * xmlParse3986Host:
+ * @uri:  pointer to an URI structure
+ * @str:  the string to analyze
+ *
+ * Parse an host part and fills in the appropriate fields
+ * of the @uri structure
+ *
+ * host          = IP-literal / IPv4address / reg-name
+ * IP-literal    = "[" ( IPv6address / IPvFuture  ) "]"
+ * IPv4address   = dec-octet "." dec-octet "." dec-octet "." dec-octet
+ * reg-name      = *( unreserved / pct-encoded / sub-delims )
+ *
+ * Returns 0 or the error code
+ */
+static int
+xmlParse3986Host(xmlURIPtr uri, const char **str)
+{
+    const char *cur = *str;
+    const char *host;
+
+    host = cur;
+    /*
+     * IPv6 and future adressing scheme are enclosed between brackets
+     */
+    if (*cur == '[') {
+        cur++;
+	while ((*cur != ']') && (*cur != 0))
+	    cur++;
+	if (*cur != ']')
+	    return(1);
+	cur++;
+	goto found;
+    }
+    /*
+     * try to parse an IPv4
+     */
+    if (ISA_DIGIT(cur)) {
+        if (xmlParse3986DecOctet(&cur) != 0)
+	    goto not_ipv4;
+	if (*cur != '.')
+	    goto not_ipv4;
+	cur++;
+        if (xmlParse3986DecOctet(&cur) != 0)
+	    goto not_ipv4;
+	if (*cur != '.')
+	    goto not_ipv4;
+        if (xmlParse3986DecOctet(&cur) != 0)
+	    goto not_ipv4;
+	if (*cur != '.')
+	    goto not_ipv4;
+        if (xmlParse3986DecOctet(&cur) != 0)
+	    goto not_ipv4;
+	goto found;
+not_ipv4:
+        cur = *str;
+    }
+    /*
+     * then this should be a hostname which can be empty
+     */
+    while (ISA_UNRESERVED(cur) || ISA_PCT_ENCODED(cur) || ISA_SUB_DELIM(cur))
+        NEXT(cur);
+found:
+    if (uri != NULL) {
+	if (uri->authority != NULL) xmlFree(uri->authority);
+	uri->authority = NULL;
+	if (uri->server != NULL) xmlFree(uri->server);
+	if (cur != host) {
+	    if (uri->cleanup & 2)
+		uri->server = STRNDUP(host, cur - host);
+	    else
+		uri->server = xmlURIUnescapeString(host, cur - host, NULL);
+	} else
+	    uri->server = NULL;
+    }
+    *str = cur;
+    return(0);
+}
+
+/**
+ * xmlParse3986Authority:
+ * @uri:  pointer to an URI structure
+ * @str:  the string to analyze
+ *
+ * Parse an authority part and fills in the appropriate fields
+ * of the @uri structure
+ *
+ * authority     = [ userinfo "@" ] host [ ":" port ]
+ *
+ * Returns 0 or the error code
+ */
+static int
+xmlParse3986Authority(xmlURIPtr uri, const char **str)
+{
+    const char *cur;
+    int ret;
+
+    cur = *str;
+    /*
+     * try to parse an userinfo and check for the trailing @
+     */
+    ret = xmlParse3986Userinfo(uri, &cur);
+    if ((ret != 0) || (*cur != '@'))
+        cur = *str;
+    else
+        cur++;
+    ret = xmlParse3986Host(uri, &cur);
+    if (ret != 0) return(ret);
+    if (*cur == ':') {
+        cur++;
+        ret = xmlParse3986Port(uri, &cur);
+	if (ret != 0) return(ret);
+    }
+    *str = cur;
+    return(0);
+}
+
+/**
+ * xmlParse3986Segment:
+ * @str:  the string to analyze
+ * @forbid: an optional forbidden character
+ * @empty: allow an empty segment
+ *
+ * Parse a segment and fills in the appropriate fields
+ * of the @uri structure
+ *
+ * segment       = *pchar
+ * segment-nz    = 1*pchar
+ * segment-nz-nc = 1*( unreserved / pct-encoded / sub-delims / "@" )
+ *               ; non-zero-length segment without any colon ":"
+ *
+ * Returns 0 or the error code
+ */
+static int
+xmlParse3986Segment(const char **str, char forbid, int empty)
+{
+    const char *cur;
+
+    cur = *str;
+    if (!ISA_PCHAR(cur)) {
+        if (empty)
+	    return(0);
+	return(1);
+    }
+    while (ISA_PCHAR(cur) && (*cur != forbid))
+        NEXT(cur);
+    *str = cur;
+    return (0);
+}
+
+/**
+ * xmlParse3986PathAbEmpty:
+ * @uri:  pointer to an URI structure
+ * @str:  the string to analyze
+ *
+ * Parse an path absolute or empty and fills in the appropriate fields
+ * of the @uri structure
+ *
+ * path-abempty  = *( "/" segment )
+ *
+ * Returns 0 or the error code
+ */
+static int
+xmlParse3986PathAbEmpty(xmlURIPtr uri, const char **str)
+{
+    const char *cur;
+    int ret;
+
+    cur = *str;
+
+    while (*cur == '/') {
+        cur++;
+	ret = xmlParse3986Segment(&cur, 0, 1);
+	if (ret != 0) return(ret);
+    }
+    if (uri != NULL) {
+	if (uri->path != NULL) xmlFree(uri->path);
+	if (uri->cleanup & 2)
+	    uri->path = STRNDUP(*str, cur - *str);
+	else
+	    uri->path = xmlURIUnescapeString(*str, cur - *str, NULL);
+    }
+    *str = cur;
+    return (0);
+}
+
+/**
+ * xmlParse3986PathAbsolute:
+ * @uri:  pointer to an URI structure
+ * @str:  the string to analyze
+ *
+ * Parse an path absolute and fills in the appropriate fields
+ * of the @uri structure
+ *
+ * path-absolute = "/" [ segment-nz *( "/" segment ) ]
+ *
+ * Returns 0 or the error code
+ */
+static int
+xmlParse3986PathAbsolute(xmlURIPtr uri, const char **str)
+{
+    const char *cur;
+    int ret;
+
+    cur = *str;
+
+    if (*cur != '/')
+        return(1);
+    cur++;
+    ret = xmlParse3986Segment(&cur, 0, 0);
+    if (ret == 0) {
+	while (*cur == '/') {
+	    cur++;
+	    ret = xmlParse3986Segment(&cur, 0, 1);
+	    if (ret != 0) return(ret);
+	}
+    }
+    if (uri != NULL) {
+	if (uri->path != NULL) xmlFree(uri->path);
+	if (uri->cleanup & 2)
+	    uri->path = STRNDUP(*str, cur - *str);
+	else
+	    uri->path = xmlURIUnescapeString(*str, cur - *str, NULL);
+    }
+    *str = cur;
+    return (0);
+}
+
+/**
+ * xmlParse3986PathRootless:
+ * @uri:  pointer to an URI structure
+ * @str:  the string to analyze
+ *
+ * Parse an path without root and fills in the appropriate fields
+ * of the @uri structure
+ *
+ * path-rootless = segment-nz *( "/" segment )
+ *
+ * Returns 0 or the error code
+ */
+static int
+xmlParse3986PathRootless(xmlURIPtr uri, const char **str)
+{
+    const char *cur;
+    int ret;
+
+    cur = *str;
+
+    ret = xmlParse3986Segment(&cur, 0, 0);
+    if (ret != 0) return(ret);
+    while (*cur == '/') {
+        cur++;
+	ret = xmlParse3986Segment(&cur, 0, 1);
+	if (ret != 0) return(ret);
+    }
+    if (uri != NULL) {
+	if (uri->path != NULL) xmlFree(uri->path);
+	if (uri->cleanup & 2)
+	    uri->path = STRNDUP(*str, cur - *str);
+	else
+	    uri->path = xmlURIUnescapeString(*str, cur - *str, NULL);
+    }
+    *str = cur;
+    return (0);
+}
+
+/**
+ * xmlParse3986PathNoScheme:
+ * @uri:  pointer to an URI structure
+ * @str:  the string to analyze
+ *
+ * Parse an path which is not a scheme and fills in the appropriate fields
+ * of the @uri structure
+ *
+ * path-noscheme = segment-nz-nc *( "/" segment )
+ *
+ * Returns 0 or the error code
+ */
+static int
+xmlParse3986PathNoScheme(xmlURIPtr uri, const char **str)
+{
+    const char *cur;
+    int ret;
+
+    cur = *str;
+
+    ret = xmlParse3986Segment(&cur, ':', 0);
+    if (ret != 0) return(ret);
+    while (*cur == '/') {
+        cur++;
+	ret = xmlParse3986Segment(&cur, 0, 1);
+	if (ret != 0) return(ret);
+    }
+    if (uri != NULL) {
+	if (uri->path != NULL) xmlFree(uri->path);
+	if (uri->cleanup & 2)
+	    uri->path = STRNDUP(*str, cur - *str);
+	else
+	    uri->path = xmlURIUnescapeString(*str, cur - *str, NULL);
+    }
+    *str = cur;
+    return (0);
+}
+
+/**
+ * xmlParse3986HierPart:
+ * @uri:  pointer to an URI structure
+ * @str:  the string to analyze
+ *
+ * Parse an hierarchical part and fills in the appropriate fields
+ * of the @uri structure
+ *
+ * hier-part     = "//" authority path-abempty
+ *                / path-absolute
+ *                / path-rootless
+ *                / path-empty
+ *
+ * Returns 0 or the error code
+ */
+static int
+xmlParse3986HierPart(xmlURIPtr uri, const char **str)
+{
+    const char *cur;
+    int ret;
+
+    cur = *str;
+
+    if ((*cur == '/') && (*(cur + 1) == '/')) {
+        cur += 2;
+	ret = xmlParse3986Authority(uri, &cur);
+	if (ret != 0) return(ret);
+	ret = xmlParse3986PathAbEmpty(uri, &cur);
+	if (ret != 0) return(ret);
+	*str = cur;
+	return(0);
+    } else if (*cur == '/') {
+        ret = xmlParse3986PathAbsolute(uri, &cur);
+	if (ret != 0) return(ret);
+    } else if (ISA_PCHAR(cur)) {
+        ret = xmlParse3986PathRootless(uri, &cur);
+	if (ret != 0) return(ret);
+    } else {
+	/* path-empty is effectively empty */
+	if (uri != NULL) {
+	    if (uri->path != NULL) xmlFree(uri->path);
+	    uri->path = NULL;
+	}
+    }
+    *str = cur;
+    return (0);
+}
+
+/**
+ * xmlParse3986RelativeRef:
+ * @uri:  pointer to an URI structure
+ * @str:  the string to analyze
+ *
+ * Parse an URI string and fills in the appropriate fields
+ * of the @uri structure
+ *
+ * relative-ref  = relative-part [ "?" query ] [ "#" fragment ]
+ * relative-part = "//" authority path-abempty
+ *               / path-absolute
+ *               / path-noscheme
+ *               / path-empty
+ *
+ * Returns 0 or the error code
+ */
+static int
+xmlParse3986RelativeRef(xmlURIPtr uri, const char *str) {
+    int ret;
+
+    if ((*str == '/') && (*(str + 1) == '/')) {
+        str += 2;
+	ret = xmlParse3986Authority(uri, &str);
+	if (ret != 0) return(ret);
+	ret = xmlParse3986PathAbEmpty(uri, &str);
+	if (ret != 0) return(ret);
+    } else if (*str == '/') {
+	ret = xmlParse3986PathAbsolute(uri, &str);
+	if (ret != 0) return(ret);
+    } else if (ISA_PCHAR(str)) {
+        ret = xmlParse3986PathNoScheme(uri, &str);
+	if (ret != 0) return(ret);
+    } else {
+	/* path-empty is effectively empty */
+	if (uri != NULL) {
+	    if (uri->path != NULL) xmlFree(uri->path);
+	    uri->path = NULL;
+	}
+    }
+
+    if (*str == '?') {
+	str++;
+	ret = xmlParse3986Query(uri, &str);
+	if (ret != 0) return(ret);
+    }
+    if (*str == '#') {
+	str++;
+	ret = xmlParse3986Fragment(uri, &str);
+	if (ret != 0) return(ret);
+    }
+    if (*str != 0) {
+	xmlCleanURI(uri);
+	return(1);
+    }
+    return(0);
+}
+
+
+/**
+ * xmlParse3986URI:
+ * @uri:  pointer to an URI structure
+ * @str:  the string to analyze
+ *
+ * Parse an URI string and fills in the appropriate fields
+ * of the @uri structure
+ *
+ * scheme ":" hier-part [ "?" query ] [ "#" fragment ]
+ *
+ * Returns 0 or the error code
+ */
+static int
+xmlParse3986URI(xmlURIPtr uri, const char *str) {
+    int ret;
+
+    ret = xmlParse3986Scheme(uri, &str);
+    if (ret != 0) return(ret);
+    if (*str != ':') {
+	return(1);
+    }
+    str++;
+    ret = xmlParse3986HierPart(uri, &str);
+    if (ret != 0) return(ret);
+    if (*str == '?') {
+	str++;
+	ret = xmlParse3986Query(uri, &str);
+	if (ret != 0) return(ret);
+    }
+    if (*str == '#') {
+	str++;
+	ret = xmlParse3986Fragment(uri, &str);
+	if (ret != 0) return(ret);
+    }
+    if (*str != 0) {
+	xmlCleanURI(uri);
+	return(1);
+    }
+    return(0);
+}
+
+/**
+ * xmlParse3986URIReference:
+ * @uri:  pointer to an URI structure
+ * @str:  the string to analyze
+ *
+ * Parse an URI reference string and fills in the appropriate fields
+ * of the @uri structure
+ *
+ * URI-reference = URI / relative-ref
+ *
+ * Returns 0 or the error code
+ */
+static int
+xmlParse3986URIReference(xmlURIPtr uri, const char *str) {
+    int ret;
+
+    if (str == NULL)
+	return(-1);
+    xmlCleanURI(uri);
+
+    /*
+     * Try first to parse absolute refs, then fallback to relative if
+     * it fails.
+     */
+    ret = xmlParse3986URI(uri, str);
+    if (ret != 0) {
+	xmlCleanURI(uri);
+        ret = xmlParse3986RelativeRef(uri, str);
+	if (ret != 0) {
+	    xmlCleanURI(uri);
+	    return(ret);
+	}
+    }
+    return(0);
+}
+
+/**
+ * xmlParseURI:
+ * @str:  the URI string to analyze
+ *
+ * Parse an URI based on RFC 3986
+ *
+ * URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
+ *
+ * Returns a newly built xmlURIPtr or NULL in case of error
+ */
+xmlURIPtr
+xmlParseURI(const char *str) {
+    xmlURIPtr uri;
+    int ret;
+
+    if (str == NULL)
+	return(NULL);
+    uri = xmlCreateURI();
+    if (uri != NULL) {
+	ret = xmlParse3986URIReference(uri, str);
+        if (ret) {
+	    xmlFreeURI(uri);
+	    return(NULL);
+	}
+    }
+    return(uri);
+}
+
+/**
+ * xmlParseURIReference:
+ * @uri:  pointer to an URI structure
+ * @str:  the string to analyze
+ *
+ * Parse an URI reference string based on RFC 3986 and fills in the
+ * appropriate fields of the @uri structure
+ *
+ * URI-reference = URI / relative-ref
+ *
+ * Returns 0 or the error code
+ */
+int
+xmlParseURIReference(xmlURIPtr uri, const char *str) {
+    return(xmlParse3986URIReference(uri, str));
+}
+
+/**
+ * xmlParseURIRaw:
+ * @str:  the URI string to analyze
+ * @raw:  if 1 unescaping of URI pieces are disabled
+ *
+ * Parse an URI but allows to keep intact the original fragments.
+ *
+ * URI-reference = URI / relative-ref
+ *
+ * Returns a newly built xmlURIPtr or NULL in case of error
+ */
+xmlURIPtr
+xmlParseURIRaw(const char *str, int raw) {
+    xmlURIPtr uri;
+    int ret;
+
+    if (str == NULL)
+	return(NULL);
+    uri = xmlCreateURI();
+    if (uri != NULL) {
+        if (raw) {
+	    uri->cleanup |= 2;
+	}
+	ret = xmlParseURIReference(uri, str);
+        if (ret) {
+	    xmlFreeURI(uri);
+	    return(NULL);
+	}
+    }
+    return(uri);
+}
+
+/************************************************************************
+ *									*
  *			Generic URI structure functions			*
  *									*
  ************************************************************************/
@@ -225,6 +983,7 @@
 xmlChar *
 xmlSaveUri(xmlURIPtr uri) {
     xmlChar *ret = NULL;
+    xmlChar *temp;
     const char *p;
     int len;
     int max;
@@ -246,23 +1005,27 @@
 	while (*p != 0) {
 	    if (len >= max) {
 		max *= 2;
-		ret = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar));
-		if (ret == NULL) {
+		temp = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar));
+		if (temp == NULL) {
 		    xmlGenericError(xmlGenericErrorContext,
 			    "xmlSaveUri: out of memory\n");
+		    xmlFree(ret);
 		    return(NULL);
 		}
+		ret = temp;
 	    }
 	    ret[len++] = *p++;
 	}
 	if (len >= max) {
 	    max *= 2;
-	    ret = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar));
-	    if (ret == NULL) {
+	    temp = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar));
+	    if (temp == NULL) {
 		xmlGenericError(xmlGenericErrorContext,
 			"xmlSaveUri: out of memory\n");
+		xmlFree(ret);
 		return(NULL);
 	    }
+	    ret = temp;
 	}
 	ret[len++] = ':';
     }
@@ -271,12 +1034,14 @@
 	while (*p != 0) {
 	    if (len + 3 >= max) {
 		max *= 2;
-		ret = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar));
-		if (ret == NULL) {
+		temp = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar));
+		if (temp == NULL) {
 		    xmlGenericError(xmlGenericErrorContext,
 			    "xmlSaveUri: out of memory\n");
+		    xmlFree(ret);
 		    return(NULL);
 		}
+		ret = temp;
 	    }
 	    if (IS_RESERVED(*(p)) || IS_UNRESERVED(*(p)))
 		ret[len++] = *p++;
@@ -292,12 +1057,14 @@
 	if (uri->server != NULL) {
 	    if (len + 3 >= max) {
 		max *= 2;
-		ret = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar));
-		if (ret == NULL) {
+		temp = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar));
+		if (temp == NULL) {
 		    xmlGenericError(xmlGenericErrorContext,
 			    "xmlSaveUri: out of memory\n");
+                  xmlFree(ret);  
 		    return(NULL);
 		}
+		ret = temp;
 	    }
 	    ret[len++] = '/';
 	    ret[len++] = '/';
@@ -306,13 +1073,15 @@
 		while (*p != 0) {
 		    if (len + 3 >= max) {
 			max *= 2;
-			ret = (xmlChar *) xmlRealloc(ret,
+			temp = (xmlChar *) xmlRealloc(ret,
 				(max + 1) * sizeof(xmlChar));
-			if (ret == NULL) {
+			if (temp == NULL) {
 			    xmlGenericError(xmlGenericErrorContext,
 				    "xmlSaveUri: out of memory\n");
+			    xmlFree(ret);
 			    return(NULL);
 			}
+			ret = temp;
 		    }
 		    if ((IS_UNRESERVED(*(p))) ||
 			((*(p) == ';')) || ((*(p) == ':')) ||
@@ -330,13 +1099,15 @@
 		}
 		if (len + 3 >= max) {
 		    max *= 2;
-		    ret = (xmlChar *) xmlRealloc(ret,
+		    temp = (xmlChar *) xmlRealloc(ret,
 			    (max + 1) * sizeof(xmlChar));
-		    if (ret == NULL) {
+		    if (temp == NULL) {
 			xmlGenericError(xmlGenericErrorContext,
 				"xmlSaveUri: out of memory\n");
+			xmlFree(ret);
 			return(NULL);
 		    }
+		    ret = temp;
 		}
 		ret[len++] = '@';
 	    }
@@ -344,39 +1115,45 @@
 	    while (*p != 0) {
 		if (len >= max) {
 		    max *= 2;
-		    ret = (xmlChar *) xmlRealloc(ret,
+		    temp = (xmlChar *) xmlRealloc(ret,
 			    (max + 1) * sizeof(xmlChar));
-		    if (ret == NULL) {
+		    if (temp == NULL) {
 			xmlGenericError(xmlGenericErrorContext,
 				"xmlSaveUri: out of memory\n");
+			xmlFree(ret);
 			return(NULL);
 		    }
+		    ret = temp;
 		}
 		ret[len++] = *p++;
 	    }
 	    if (uri->port > 0) {
 		if (len + 10 >= max) {
 		    max *= 2;
-		    ret = (xmlChar *) xmlRealloc(ret,
+		    temp = (xmlChar *) xmlRealloc(ret,
 			    (max + 1) * sizeof(xmlChar));
-		    if (ret == NULL) {
+		    if (temp == NULL) {
 			xmlGenericError(xmlGenericErrorContext,
 				"xmlSaveUri: out of memory\n");
+                     xmlFree(ret);
 			return(NULL);
 		    }
+		    ret = temp;
 		}
 		len += snprintf((char *) &ret[len], max - len, ":%d", uri->port);
 	    }
 	} else if (uri->authority != NULL) {
 	    if (len + 3 >= max) {
 		max *= 2;
-		ret = (xmlChar *) xmlRealloc(ret,
+		temp = (xmlChar *) xmlRealloc(ret,
 			(max + 1) * sizeof(xmlChar));
-		if (ret == NULL) {
-		    xmlGenericError(xmlGenericErrorContext,
-			    "xmlSaveUri: out of memory\n");
-		    return(NULL);
-		}
+		if (temp == NULL) {
+			xmlGenericError(xmlGenericErrorContext,
+				"xmlSaveUri: out of memory\n");
+                     xmlFree(ret);
+			return(NULL);
+		    }
+		    ret = temp;
 	    }
 	    ret[len++] = '/';
 	    ret[len++] = '/';
@@ -384,13 +1161,15 @@
 	    while (*p != 0) {
 		if (len + 3 >= max) {
 		    max *= 2;
-		    ret = (xmlChar *) xmlRealloc(ret,
+		    temp = (xmlChar *) xmlRealloc(ret,
 			    (max + 1) * sizeof(xmlChar));
-		    if (ret == NULL) {
+		    if (temp == NULL) {
 			xmlGenericError(xmlGenericErrorContext,
 				"xmlSaveUri: out of memory\n");
+                     xmlFree(ret);
 			return(NULL);
 		    }
+		    ret = temp;
 		}
 		if ((IS_UNRESERVED(*(p))) ||
                     ((*(p) == '$')) || ((*(p) == ',')) || ((*(p) == ';')) ||
@@ -408,20 +1187,31 @@
 	} else if (uri->scheme != NULL) {
 	    if (len + 3 >= max) {
 		max *= 2;
-		ret = (xmlChar *) xmlRealloc(ret,
+		temp = (xmlChar *) xmlRealloc(ret,
 			(max + 1) * sizeof(xmlChar));
-		if (ret == NULL) {
-		    xmlGenericError(xmlGenericErrorContext,
-			    "xmlSaveUri: out of memory\n");
-		    return(NULL);
-		}
+		if (temp == NULL) {
+			xmlGenericError(xmlGenericErrorContext,
+				"xmlSaveUri: out of memory\n");
+                     xmlFree(ret);
+			return(NULL);
+		    }
+		    ret = temp;
 	    }
 	    ret[len++] = '/';
 	    ret[len++] = '/';
 	}
 	if (uri->path != NULL) {
 	    p = uri->path;
-	    while (*p != 0) {
+	    /*
+	     * the colon in file:///d: should not be escaped or
+	     * Windows accesses fail later.
+	     */
+	    if ((uri->scheme != NULL) &&
+		(p[0] == '/') &&
+		(((p[1] >= 'a') && (p[1] <= 'z')) ||
+		 ((p[1] >= 'A') && (p[1] <= 'Z'))) &&
+		(p[2] == ':') &&
+	        (xmlStrEqual(BAD_CAST uri->scheme, BAD_CAST "file"))) {
 		if (len + 3 >= max) {
 		    max *= 2;
 		    ret = (xmlChar *) xmlRealloc(ret,
@@ -432,6 +1222,23 @@
 			return(NULL);
 		    }
 		}
+		ret[len++] = *p++;
+		ret[len++] = *p++;
+		ret[len++] = *p++;
+	    }
+	    while (*p != 0) {
+		if (len + 3 >= max) {
+		    max *= 2;
+		    temp = (xmlChar *) xmlRealloc(ret,
+			    (max + 1) * sizeof(xmlChar));
+		    if (temp == NULL) {
+			xmlGenericError(xmlGenericErrorContext,
+				"xmlSaveUri: out of memory\n");
+                     xmlFree(ret);
+			return(NULL);
+		    }
+		    ret = temp;
+		}
 		if ((IS_UNRESERVED(*(p))) || ((*(p) == '/')) ||
                     ((*(p) == ';')) || ((*(p) == '@')) || ((*(p) == '&')) ||
 	            ((*(p) == '=')) || ((*(p) == '+')) || ((*(p) == '$')) ||
@@ -449,52 +1256,60 @@
 	if (uri->query_raw != NULL) {
 	    if (len + 1 >= max) {
 		max *= 2;
-		ret = (xmlChar *) xmlRealloc(ret,
+		temp = (xmlChar *) xmlRealloc(ret,
 			(max + 1) * sizeof(xmlChar));
-		if (ret == NULL) {
-		    xmlGenericError(xmlGenericErrorContext,
-			    "xmlSaveUri: out of memory\n");
-		    return(NULL);
-		}
+		if (temp == NULL) {
+			xmlGenericError(xmlGenericErrorContext,
+				"xmlSaveUri: out of memory\n");
+                     xmlFree(ret);
+			return(NULL);
+		    }
+		    ret = temp;
 	    }
 	    ret[len++] = '?';
 	    p = uri->query_raw;
 	    while (*p != 0) {
 		if (len + 1 >= max) {
 		    max *= 2;
-		    ret = (xmlChar *) xmlRealloc(ret,
+		    temp = (xmlChar *) xmlRealloc(ret,
 			    (max + 1) * sizeof(xmlChar));
-		    if (ret == NULL) {
+		    if (temp == NULL) {
 			xmlGenericError(xmlGenericErrorContext,
 				"xmlSaveUri: out of memory\n");
+                     xmlFree(ret);
 			return(NULL);
 		    }
+		    ret = temp;
 		}
 		ret[len++] = *p++;
 	    }
 	} else if (uri->query != NULL) {
 	    if (len + 3 >= max) {
 		max *= 2;
-		ret = (xmlChar *) xmlRealloc(ret,
+		temp = (xmlChar *) xmlRealloc(ret,
 			(max + 1) * sizeof(xmlChar));
-		if (ret == NULL) {
-		    xmlGenericError(xmlGenericErrorContext,
-			    "xmlSaveUri: out of memory\n");
-		    return(NULL);
-		}
+		if (temp == NULL) {
+			xmlGenericError(xmlGenericErrorContext,
+				"xmlSaveUri: out of memory\n");
+                     xmlFree(ret);
+			return(NULL);
+		    }
+		    ret = temp;
 	    }
 	    ret[len++] = '?';
 	    p = uri->query;
 	    while (*p != 0) {
 		if (len + 3 >= max) {
 		    max *= 2;
-		    ret = (xmlChar *) xmlRealloc(ret,
+		    temp = (xmlChar *) xmlRealloc(ret,
 			    (max + 1) * sizeof(xmlChar));
-		    if (ret == NULL) {
+		    if (temp == NULL) {
 			xmlGenericError(xmlGenericErrorContext,
 				"xmlSaveUri: out of memory\n");
+                     xmlFree(ret);
 			return(NULL);
 		    }
+		    ret = temp;
 		}
 		if ((IS_UNRESERVED(*(p))) || (IS_RESERVED(*(p)))) 
 		    ret[len++] = *p++;
@@ -511,26 +1326,30 @@
     if (uri->fragment != NULL) {
 	if (len + 3 >= max) {
 	    max *= 2;
-	    ret = (xmlChar *) xmlRealloc(ret,
+	    temp = (xmlChar *) xmlRealloc(ret,
 		    (max + 1) * sizeof(xmlChar));
-	    if (ret == NULL) {
-		xmlGenericError(xmlGenericErrorContext,
-			"xmlSaveUri: out of memory\n");
-		return(NULL);
-	    }
+	    if (temp == NULL) {
+			xmlGenericError(xmlGenericErrorContext,
+				"xmlSaveUri: out of memory\n");
+                     xmlFree(ret);
+			return(NULL);
+		    }
+		    ret = temp;
 	}
 	ret[len++] = '#';
 	p = uri->fragment;
 	while (*p != 0) {
 	    if (len + 3 >= max) {
 		max *= 2;
-		ret = (xmlChar *) xmlRealloc(ret,
+		temp = (xmlChar *) xmlRealloc(ret,
 			(max + 1) * sizeof(xmlChar));
-		if (ret == NULL) {
-		    xmlGenericError(xmlGenericErrorContext,
-			    "xmlSaveUri: out of memory\n");
-		    return(NULL);
-		}
+		if (temp == NULL) {
+			xmlGenericError(xmlGenericErrorContext,
+				"xmlSaveUri: out of memory\n");
+                     xmlFree(ret);
+			return(NULL);
+		    }
+		    ret = temp;
 	    }
 	    if ((IS_UNRESERVED(*(p))) || (IS_RESERVED(*(p)))) 
 		ret[len++] = *p++;
@@ -545,12 +1364,14 @@
     }
     if (len >= max) {
 	max *= 2;
-	ret = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar));
-	if (ret == NULL) {
-	    xmlGenericError(xmlGenericErrorContext,
-		    "xmlSaveUri: out of memory\n");
-	    return(NULL);
-	}
+	temp = (xmlChar *) xmlRealloc(ret, (max + 1) * sizeof(xmlChar));
+	if (temp == NULL) {
+			xmlGenericError(xmlGenericErrorContext,
+				"xmlSaveUri: out of memory\n");
+                     xmlFree(ret);
+			return(NULL);
+		    }
+		    ret = temp;
     }
     ret[len++] = 0;
     return(ret);
@@ -904,6 +1725,7 @@
 xmlChar *
 xmlURIEscapeStr(const xmlChar *str, const xmlChar *list) {
     xmlChar *ret, ch;
+    xmlChar *temp;
     const xmlChar *in;
 
     unsigned int len, out;
@@ -927,12 +1749,14 @@
     while(*in != 0) {
 	if (len - out <= 3) {
 	    len += 20;
-	    ret = (xmlChar *) xmlRealloc(ret, len);
-	    if (ret == NULL) {
+	    temp = (xmlChar *) xmlRealloc(ret, len);
+	    if (temp == NULL) {
 		xmlGenericError(xmlGenericErrorContext,
 			"xmlURIEscapeStr: out of memory\n");
+		xmlFree(ret);
 		return(NULL);
 	    }
+	    ret = temp;
 	}
 
 	ch = *in;
@@ -985,7 +1809,8 @@
 #define NULLCHK(p) if(!p) { \
                    xmlGenericError(xmlGenericErrorContext, \
                         "xmlURIEscape: out of memory\n"); \
-                   return NULL; }
+                        xmlFreeURI(uri); \
+                        return NULL; } \
 
     if (str == NULL)
         return (NULL);
@@ -1038,7 +1863,7 @@
         segment = xmlURIEscapeStr(BAD_CAST uri->server, BAD_CAST "/?;:@");
         NULLCHK(segment)
 		if (uri->user == NULL)
-       		ret = xmlStrcat(ret, BAD_CAST "//");
+		ret = xmlStrcat(ret, BAD_CAST "//");
         ret = xmlStrcat(ret, segment);
         xmlFree(segment);
     }
@@ -1095,787 +1920,6 @@
 
 /************************************************************************
  *									*
- *			Escaped URI parsing				*
- *									*
- ************************************************************************/
-
-/**
- * xmlParseURIFragment:
- * @uri:  pointer to an URI structure
- * @str:  pointer to the string to analyze
- *
- * Parse an URI fragment string and fills in the appropriate fields
- * of the @uri structure.
- * 
- * fragment = *uric
- *
- * Returns 0 or the error code
- */
-static int
-xmlParseURIFragment(xmlURIPtr uri, const char **str)
-{
-    const char *cur;
-    
-    if (str == NULL)
-        return (-1);
-
-    cur = *str;
-
-    while (IS_URIC(cur) || IS_UNWISE(cur))
-        NEXT(cur);
-    if (uri != NULL) {
-        if (uri->fragment != NULL)
-            xmlFree(uri->fragment);
-	if (uri->cleanup & 2)
-	    uri->fragment = STRNDUP(*str, cur - *str);
-	else
-	    uri->fragment = xmlURIUnescapeString(*str, cur - *str, NULL);
-    }
-    *str = cur;
-    return (0);
-}
-
-/**
- * xmlParseURIQuery:
- * @uri:  pointer to an URI structure
- * @str:  pointer to the string to analyze
- *
- * Parse the query part of an URI
- * 
- * query = *uric
- *
- * Returns 0 or the error code
- */
-static int
-xmlParseURIQuery(xmlURIPtr uri, const char **str)
-{
-    const char *cur;
-
-    if (str == NULL)
-        return (-1);
-
-    cur = *str;
-
-    while ((IS_URIC(cur)) ||
-           ((uri != NULL) && (uri->cleanup & 1) && (IS_UNWISE(cur))))
-        NEXT(cur);
-    if (uri != NULL) {
-        if (uri->query != NULL)
-            xmlFree(uri->query);
-	if (uri->cleanup & 2)
-	    uri->query = STRNDUP(*str, cur - *str);
-	else
-	    uri->query = xmlURIUnescapeString(*str, cur - *str, NULL);
-
-	/* Save the raw bytes of the query as well.
-	 * See: http://mail.gnome.org/archives/xml/2007-April/thread.html#00114
-	 */
-	if (uri->query_raw != NULL)
-	    xmlFree (uri->query_raw);
-	uri->query_raw = STRNDUP (*str, cur - *str);
-    }
-    *str = cur;
-    return (0);
-}
-
-/**
- * xmlParseURIScheme:
- * @uri:  pointer to an URI structure
- * @str:  pointer to the string to analyze
- *
- * Parse an URI scheme
- * 
- * scheme = alpha *( alpha | digit | "+" | "-" | "." )
- *
- * Returns 0 or the error code
- */
-static int
-xmlParseURIScheme(xmlURIPtr uri, const char **str) {
-    const char *cur;
-
-    if (str == NULL)
-	return(-1);
-    
-    cur = *str;
-    if (!IS_ALPHA(*cur))
-	return(2);
-    cur++;
-    while (IS_SCHEME(*cur)) cur++;
-    if (uri != NULL) {
-	if (uri->scheme != NULL) xmlFree(uri->scheme);
-	uri->scheme = STRNDUP(*str, cur - *str);
-    }
-    *str = cur;
-    return(0);
-}
-
-/**
- * xmlParseURIOpaquePart:
- * @uri:  pointer to an URI structure
- * @str:  pointer to the string to analyze
- *
- * Parse an URI opaque part
- * 
- * opaque_part = uric_no_slash *uric
- *
- * Returns 0 or the error code
- */
-static int
-xmlParseURIOpaquePart(xmlURIPtr uri, const char **str)
-{
-    const char *cur;
-
-    if (str == NULL)
-        return (-1);
-
-    cur = *str;
-    if (!((IS_URIC_NO_SLASH(cur)) ||
-          ((uri != NULL) && (uri->cleanup & 1) && (IS_UNWISE(cur))))) {
-        return (3);
-    }
-    NEXT(cur);
-    while ((IS_URIC(cur)) ||
-           ((uri != NULL) && (uri->cleanup & 1) && (IS_UNWISE(cur))))
-        NEXT(cur);
-    if (uri != NULL) {
-        if (uri->opaque != NULL)
-            xmlFree(uri->opaque);
-	if (uri->cleanup & 2)
-	    uri->opaque = STRNDUP(*str, cur - *str);
-	else
-	    uri->opaque = xmlURIUnescapeString(*str, cur - *str, NULL);
-    }
-    *str = cur;
-    return (0);
-}
-
-/**
- * xmlParseURIServer:
- * @uri:  pointer to an URI structure
- * @str:  pointer to the string to analyze
- *
- * Parse a server subpart of an URI, it's a finer grain analysis
- * of the authority part.
- * 
- * server        = [ [ userinfo "@" ] hostport ]
- * userinfo      = *( unreserved | escaped |
- *                       ";" | ":" | "&" | "=" | "+" | "$" | "," )
- * hostport      = host [ ":" port ]
- * host          = hostname | IPv4address | IPv6reference
- * hostname      = *( domainlabel "." ) toplabel [ "." ]
- * domainlabel   = alphanum | alphanum *( alphanum | "-" ) alphanum
- * toplabel      = alpha | alpha *( alphanum | "-" ) alphanum
- * IPv6reference = "[" IPv6address "]"
- * IPv6address   = hexpart [ ":" IPv4address ]
- * IPv4address   = 1*3digit "." 1*3digit "." 1*3digit "." 1*3digit
- * hexpart       = hexseq | hexseq "::" [ hexseq ]| "::" [ hexseq ]
- * hexseq        = hex4 *( ":" hex4)
- * hex4          = 1*4hexdig
- * port          = *digit
- *
- * Returns 0 or the error code
- */
-static int
-xmlParseURIServer(xmlURIPtr uri, const char **str) {
-    const char *cur;
-    const char *host, *tmp;
-    const int IPV4max = 4;
-    const int IPV6max = 8;
-    int oct;
-
-    if (str == NULL)
-	return(-1);
-    
-    cur = *str;
-
-    /*
-     * is there a userinfo ?
-     */
-    while (IS_USERINFO(cur)) NEXT(cur);
-    if (*cur == '@') {
-	if (uri != NULL) {
-	    if (uri->user != NULL) xmlFree(uri->user);
-	    if (uri->cleanup & 2)
-		uri->user = STRNDUP(*str, cur - *str);
-	    else
-		uri->user = xmlURIUnescapeString(*str, cur - *str, NULL);
-	}
-	cur++;
-    } else {
-	if (uri != NULL) {
-	    if (uri->user != NULL) xmlFree(uri->user);
-	    uri->user = NULL;
-	}
-        cur = *str;
-    }
-    /*
-     * This can be empty in the case where there is no server
-     */
-    host = cur;
-    if (*cur == '/') {
-	if (uri != NULL) {
-	    if (uri->authority != NULL) xmlFree(uri->authority);
-	    uri->authority = NULL;
-	    if (uri->server != NULL) xmlFree(uri->server);
-	    uri->server = NULL;
-	    uri->port = 0;
-	}
-	return(0);
-    }
-    /*
-     * host part of hostport can denote an IPV4 address, an IPV6 address
-     * or an unresolved name. Check the IP first, its easier to detect
-     * errors if wrong one.
-     * An IPV6 address must start with a '[' and end with a ']'.
-     */
-    if (*cur == '[') {
-	int compress=0;
-	cur++;
-	for (oct = 0; oct < IPV6max; ++oct) {
-	    if (*cur == ':') {
-		if (compress)
-		    return(3);	/* multiple compression attempted */
-		if (!oct) { 	/* initial char is compression */
-		    if (*++cur != ':')
-			return(3);
-		}
-		compress = 1;	/* set compression-encountered flag */
-		cur++;		/* skip over the second ':' */
-		continue;
-	    }
-	    while(IS_HEX(*cur)) cur++;
-	    if (oct == (IPV6max-1))
-		continue;
-	    if (*cur != ':')
-		break;
-	    cur++;
-	}
-	if ((!compress) && (oct != IPV6max))
-	    return(3);
-	if (*cur != ']')
-	    return(3);
-	if (uri != NULL) {
-	    if (uri->server != NULL) xmlFree(uri->server);
-	    uri->server = (char *)xmlStrndup((xmlChar *)host+1,
-			(cur-host)-1);
-	}
-	cur++;
-    } else {
-	/*
-	 * Not IPV6, maybe IPV4
-	 */
-	for (oct = 0; oct < IPV4max; ++oct) {
-            if (*cur == '.') 
-                return(3); /* e.g. http://.xml/ or http://18.29..30/ */
-            while(IS_DIGIT(*cur)) cur++;
-            if (oct == (IPV4max-1))
-                continue;
-            if (*cur != '.')
-	        break;
-            cur++;
-	}
-    }
-    if ((host[0] != '[') && (oct < IPV4max || (*cur == '.' && cur++) ||
-			     IS_ALPHA(*cur))) {
-        /* maybe host_name */
-        if (!IS_ALPHANUM(*cur))
-            return(4); /* e.g. http://xml.$oft */
-        do {
-            do ++cur; while (IS_ALPHANUM(*cur));
-            if (*cur == '-') {
-	        --cur;
-                if (*cur == '.')
-                    return(5); /* e.g. http://xml.-soft */
-	        ++cur;
-		continue;
-            }
-    	    if (*cur == '.') {
-	        --cur;
-                if (*cur == '-')
-                    return(6); /* e.g. http://xml-.soft */
-                if (*cur == '.')
-                    return(7); /* e.g. http://xml..soft */
-	        ++cur;
-		continue;
-            }
-	    break;
-        } while (1);
-        tmp = cur;
-        if (tmp[-1] == '.')
-            --tmp; /* e.g. http://xml.$Oft/ */
-        do --tmp; while (tmp >= host && IS_ALPHANUM(*tmp));
-        if ((++tmp == host || tmp[-1] == '.') && !IS_ALPHA(*tmp))
-            return(8); /* e.g. http://xmlsOft.0rg/ */
-    }
-    if (uri != NULL) {
-	if (uri->authority != NULL) xmlFree(uri->authority);
-	uri->authority = NULL;
-	if (host[0] != '[') {	/* it's not an IPV6 addr */
-	    if (uri->server != NULL) xmlFree(uri->server);
-	    if (uri->cleanup & 2)
-		uri->server = STRNDUP(host, cur - host);
-	    else
-		uri->server = xmlURIUnescapeString(host, cur - host, NULL);
-	}
-    }
-    /*
-     * finish by checking for a port presence.
-     */
-    if (*cur == ':') {
-        cur++;
-	if (IS_DIGIT(*cur)) {
-	    if (uri != NULL)
-	        uri->port = 0;
-	    while (IS_DIGIT(*cur)) {
-	        if (uri != NULL)
-		    uri->port = uri->port * 10 + (*cur - '0');
-		cur++;
-	    }
-	}
-    }
-    *str = cur;
-    return(0);
-}	
-
-/**
- * xmlParseURIRelSegment:
- * @uri:  pointer to an URI structure
- * @str:  pointer to the string to analyze
- *
- * Parse an URI relative segment
- * 
- * rel_segment = 1*( unreserved | escaped | ";" | "@" | "&" | "=" |
- *                          "+" | "$" | "," )
- *
- * Returns 0 or the error code
- */
-static int
-xmlParseURIRelSegment(xmlURIPtr uri, const char **str)
-{
-    const char *cur;
-
-    if (str == NULL)
-        return (-1);
-
-    cur = *str;
-    if (!((IS_SEGMENT(cur)) ||
-          ((uri != NULL) && (uri->cleanup & 1) && (IS_UNWISE(cur))))) {
-        return (3);
-    }
-    NEXT(cur);
-    while ((IS_SEGMENT(cur)) ||
-           ((uri != NULL) && (uri->cleanup & 1) && (IS_UNWISE(cur))))
-        NEXT(cur);
-    if (uri != NULL) {
-        if (uri->path != NULL)
-            xmlFree(uri->path);
-	if (uri->cleanup & 2)
-	    uri->path = STRNDUP(*str, cur - *str);
-	else
-	    uri->path = xmlURIUnescapeString(*str, cur - *str, NULL);
-    }
-    *str = cur;
-    return (0);
-}
-
-/**
- * xmlParseURIPathSegments:
- * @uri:  pointer to an URI structure
- * @str:  pointer to the string to analyze
- * @slash:  should we add a leading slash
- *
- * Parse an URI set of path segments
- * 
- * path_segments = segment *( "/" segment )
- * segment       = *pchar *( ";" param )
- * param         = *pchar
- *
- * Returns 0 or the error code
- */
-static int
-xmlParseURIPathSegments(xmlURIPtr uri, const char **str, int slash)
-{
-    const char *cur;
-
-    if (str == NULL)
-        return (-1);
-
-    cur = *str;
-
-    do {
-        while ((IS_PCHAR(cur)) ||
-	       ((uri != NULL) && (uri->cleanup & 1) && (IS_UNWISE(cur))))
-            NEXT(cur);
-        while (*cur == ';') {
-            cur++;
-            while ((IS_PCHAR(cur)) ||
-	           ((uri != NULL) && (uri->cleanup & 1) && (IS_UNWISE(cur))))
-                NEXT(cur);
-        }
-        if (*cur != '/')
-            break;
-        cur++;
-    } while (1);
-    if (uri != NULL) {
-        int len, len2 = 0;
-        char *path;
-
-        /*
-         * Concat the set of path segments to the current path
-         */
-        len = cur - *str;
-        if (slash)
-            len++;
-
-        if (uri->path != NULL) {
-            len2 = strlen(uri->path);
-            len += len2;
-        }
-        path = (char *) xmlMallocAtomic(len + 1);
-        if (path == NULL) {
-	    xmlGenericError(xmlGenericErrorContext,
-	    		    "xmlParseURIPathSegments: out of memory\n");
-            *str = cur;
-            return (-1);
-        }
-        if (uri->path != NULL)
-            memcpy(path, uri->path, len2);
-        if (slash) {
-            path[len2] = '/';
-            len2++;
-        }
-        path[len2] = 0;
-        if (cur - *str > 0) {
-	    if (uri->cleanup & 2) {
-	        memcpy(&path[len2], *str, cur - *str);
-		path[len2 + (cur - *str)] = 0;
-	    } else
-		xmlURIUnescapeString(*str, cur - *str, &path[len2]);
-	}
-        if (uri->path != NULL)
-            xmlFree(uri->path);
-        uri->path = path;
-    }
-    *str = cur;
-    return (0);
-}
-
-/**
- * xmlParseURIAuthority:
- * @uri:  pointer to an URI structure
- * @str:  pointer to the string to analyze
- *
- * Parse the authority part of an URI.
- * 
- * authority = server | reg_name
- * server    = [ [ userinfo "@" ] hostport ]
- * reg_name  = 1*( unreserved | escaped | "$" | "," | ";" | ":" |
- *                        "@" | "&" | "=" | "+" )
- *
- * Note : this is completely ambiguous since reg_name is allowed to
- *        use the full set of chars in use by server:
- *
- *        3.2.1. Registry-based Naming Authority
- *
- *        The structure of a registry-based naming authority is specific
- *        to the URI scheme, but constrained to the allowed characters
- *        for an authority component.
- *
- * Returns 0 or the error code
- */
-static int
-xmlParseURIAuthority(xmlURIPtr uri, const char **str) {
-    const char *cur;
-    int ret;
-
-    if (str == NULL)
-	return(-1);
-    
-    cur = *str;
-
-    /*
-     * try first to parse it as a server string.
-     */
-    ret = xmlParseURIServer(uri, str);
-    if ((ret == 0) && (*str != NULL) &&
-	((**str == 0) || (**str == '/') || (**str == '?')))
-        return(0);
-    *str = cur;
-
-    /*
-     * failed, fallback to reg_name
-     */
-    if (!IS_REG_NAME(cur)) {
-	return(5);
-    }
-    NEXT(cur);
-    while (IS_REG_NAME(cur)) NEXT(cur);
-    if (uri != NULL) {
-	if (uri->server != NULL) xmlFree(uri->server);
-	uri->server = NULL;
-	if (uri->user != NULL) xmlFree(uri->user);
-	uri->user = NULL;
-	if (uri->authority != NULL) xmlFree(uri->authority);
-	if (uri->cleanup & 2)
-	    uri->authority = STRNDUP(*str, cur - *str);
-	else
-	    uri->authority = xmlURIUnescapeString(*str, cur - *str, NULL);
-    }
-    *str = cur;
-    return(0);
-}
-
-/**
- * xmlParseURIHierPart:
- * @uri:  pointer to an URI structure
- * @str:  pointer to the string to analyze
- *
- * Parse an URI hierarchical part
- * 
- * hier_part = ( net_path | abs_path ) [ "?" query ]
- * abs_path = "/"  path_segments
- * net_path = "//" authority [ abs_path ]
- *
- * Returns 0 or the error code
- */
-static int
-xmlParseURIHierPart(xmlURIPtr uri, const char **str) {
-    int ret;
-    const char *cur;
-
-    if (str == NULL)
-	return(-1);
-    
-    cur = *str;
-
-    if ((cur[0] == '/') && (cur[1] == '/')) {
-	cur += 2;
-	ret = xmlParseURIAuthority(uri, &cur);
-	if (ret != 0)
-	    return(ret);
-	if (cur[0] == '/') {
-	    cur++;
-	    ret = xmlParseURIPathSegments(uri, &cur, 1);
-	}
-    } else if (cur[0] == '/') {
-	cur++;
-	ret = xmlParseURIPathSegments(uri, &cur, 1);
-    } else {
-	return(4);
-    }
-    if (ret != 0)
-	return(ret);
-    if (*cur == '?') {
-	cur++;
-	ret = xmlParseURIQuery(uri, &cur);
-	if (ret != 0)
-	    return(ret);
-    }
-    *str = cur;
-    return(0);
-}
-
-/**
- * xmlParseAbsoluteURI:
- * @uri:  pointer to an URI structure
- * @str:  pointer to the string to analyze
- *
- * Parse an URI reference string and fills in the appropriate fields
- * of the @uri structure
- * 
- * absoluteURI   = scheme ":" ( hier_part | opaque_part )
- *
- * Returns 0 or the error code
- */
-static int
-xmlParseAbsoluteURI(xmlURIPtr uri, const char **str) {
-    int ret;
-    const char *cur;
-
-    if (str == NULL)
-	return(-1);
-    
-    cur = *str;
-
-    ret = xmlParseURIScheme(uri, str);
-    if (ret != 0) return(ret);
-    if (**str != ':') {
-	*str = cur;
-	return(1);
-    }
-    (*str)++;
-    if (**str == '/')
-	return(xmlParseURIHierPart(uri, str));
-    return(xmlParseURIOpaquePart(uri, str));
-}
-
-/**
- * xmlParseRelativeURI:
- * @uri:  pointer to an URI structure
- * @str:  pointer to the string to analyze
- *
- * Parse an relative URI string and fills in the appropriate fields
- * of the @uri structure
- * 
- * relativeURI = ( net_path | abs_path | rel_path ) [ "?" query ]
- * abs_path = "/"  path_segments
- * net_path = "//" authority [ abs_path ]
- * rel_path = rel_segment [ abs_path ]
- *
- * Returns 0 or the error code
- */
-static int
-xmlParseRelativeURI(xmlURIPtr uri, const char **str) {
-    int ret = 0;
-    const char *cur;
-
-    if (str == NULL)
-	return(-1);
-    
-    cur = *str;
-    if ((cur[0] == '/') && (cur[1] == '/')) {
-	cur += 2;
-	ret = xmlParseURIAuthority(uri, &cur);
-	if (ret != 0)
-	    return(ret);
-	if (cur[0] == '/') {
-	    cur++;
-	    ret = xmlParseURIPathSegments(uri, &cur, 1);
-	}
-    } else if (cur[0] == '/') {
-	cur++;
-	ret = xmlParseURIPathSegments(uri, &cur, 1);
-    } else if (cur[0] != '#' && cur[0] != '?') {
-	ret = xmlParseURIRelSegment(uri, &cur);
-	if (ret != 0)
-	    return(ret);
-	if (cur[0] == '/') {
-	    cur++;
-	    ret = xmlParseURIPathSegments(uri, &cur, 1);
-	}
-    }
-    if (ret != 0)
-	return(ret);
-    if (*cur == '?') {
-	cur++;
-	ret = xmlParseURIQuery(uri, &cur);
-	if (ret != 0)
-	    return(ret);
-    }
-    *str = cur;
-    return(ret);
-}
-
-/**
- * xmlParseURIReference:
- * @uri:  pointer to an URI structure
- * @str:  the string to analyze
- *
- * Parse an URI reference string and fills in the appropriate fields
- * of the @uri structure
- * 
- * URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
- *
- * Returns 0 or the error code
- */
-int
-xmlParseURIReference(xmlURIPtr uri, const char *str) {
-    int ret;
-    const char *tmp = str;
-
-    if (str == NULL)
-	return(-1);
-    xmlCleanURI(uri);
-
-    /*
-     * Try first to parse absolute refs, then fallback to relative if
-     * it fails.
-     */
-    ret = xmlParseAbsoluteURI(uri, &str);
-    if (ret != 0) {
-	xmlCleanURI(uri);
-	str = tmp;
-        ret = xmlParseRelativeURI(uri, &str);
-    }
-    if (ret != 0) {
-	xmlCleanURI(uri);
-	return(ret);
-    }
-
-    if (*str == '#') {
-	str++;
-	ret = xmlParseURIFragment(uri, &str);
-	if (ret != 0) return(ret);
-    }
-    if (*str != 0) {
-	xmlCleanURI(uri);
-	return(1);
-    }
-    return(0);
-}
-
-/**
- * xmlParseURI:
- * @str:  the URI string to analyze
- *
- * Parse an URI 
- * 
- * URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
- *
- * Returns a newly built xmlURIPtr or NULL in case of error
- */
-xmlURIPtr
-xmlParseURI(const char *str) {
-    xmlURIPtr uri;
-    int ret;
-
-    if (str == NULL)
-	return(NULL);
-    uri = xmlCreateURI();
-    if (uri != NULL) {
-	ret = xmlParseURIReference(uri, str);
-        if (ret) {
-	    xmlFreeURI(uri);
-	    return(NULL);
-	}
-    }
-    return(uri);
-}
-
-/**
- * xmlParseURIRaw:
- * @str:  the URI string to analyze
- * @raw:  if 1 unescaping of URI pieces are disabled
- *
- * Parse an URI but allows to keep intact the original fragments.
- * 
- * URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ]
- *
- * Returns a newly built xmlURIPtr or NULL in case of error
- */
-xmlURIPtr
-xmlParseURIRaw(const char *str, int raw) {
-    xmlURIPtr uri;
-    int ret;
-
-    if (str == NULL)
-	return(NULL);
-    uri = xmlCreateURI();
-    if (uri != NULL) {
-        if (raw) {
-	    uri->cleanup |= 2;
-	}
-	ret = xmlParseURIReference(uri, str);
-        if (ret) {
-	    xmlFreeURI(uri);
-	    return(NULL);
-	}
-    }
-    return(uri);
-}
-
-/************************************************************************
- *									*
  *			Public functions				*
  *									*
  ************************************************************************/
@@ -2418,6 +2462,11 @@
 
     if (path == NULL)
 	return(NULL);
+
+    /* sanitize filename starting with // so it can be used as URI */
+    if ((path[0] == '/') && (path[1] == '/') && (path[2] != '/'))
+        path++;
+
     if ((uri = xmlParseURI((const char *) path)) != NULL) {
 	xmlFreeURI(uri);
 	return xmlStrdup(path);
diff --git a/valid.c b/valid.c
index 2510b8d..9baba3b 100644
--- a/valid.c
+++ b/valid.c
@@ -36,6 +36,11 @@
 	    "Unimplemented block at %s:%d\n",				\
             __FILE__, __LINE__);
 
+#ifdef LIBXML_VALID_ENABLED
+static int
+xmlValidateAttributeValueInternal(xmlDocPtr doc, xmlAttributeType type,
+                                  const xmlChar *value);
+#endif
 /************************************************************************
  *									*
  *			Error handling routines				*
@@ -2024,7 +2029,7 @@
 	    return(NULL);
     }
     if ((defaultValue != NULL) && 
-        (!xmlValidateAttributeValue(type, defaultValue))) {
+        (!xmlValidateAttributeValueInternal(dtd->doc, type, defaultValue))) {
 	xmlErrValidNode(ctxt, (xmlNodePtr) dtd, XML_DTD_ATTRIBUTE_DEFAULT,
 	                "Attribute %s of %s: invalid default value\n",
 	                elem, name, defaultValue);
@@ -2042,8 +2047,10 @@
 	(dtd->doc->intSubset != NULL) &&
 	(dtd->doc->intSubset->attributes != NULL)) {
         ret = xmlHashLookup3(dtd->doc->intSubset->attributes, name, ns, elem);
-	if (ret != NULL)
+	if (ret != NULL) {
+	    xmlFreeEnumeration(tree);
 	    return(NULL);
+	}
     }
 
     /*
@@ -2057,6 +2064,7 @@
     if (table == NULL) {
 	xmlVErrMemory(ctxt,
             "xmlAddAttributeDecl: Table creation failed!\n");
+	xmlFreeEnumeration(tree);
         return(NULL);
     }
 
@@ -2064,6 +2072,7 @@
     ret = (xmlAttributePtr) xmlMalloc(sizeof(xmlAttribute));
     if (ret == NULL) {
 	xmlVErrMemory(ctxt, "malloc failed");
+	xmlFreeEnumeration(tree);
 	return(NULL);
     }
     memset(ret, 0, sizeof(xmlAttribute));
@@ -3445,6 +3454,109 @@
 }
 
 #ifdef LIBXML_VALID_ENABLED
+
+static int
+xmlIsDocNameStartChar(xmlDocPtr doc, int c) {
+    if ((doc == NULL) || (doc->properties & XML_DOC_OLD10) == 0) {
+        /*
+	 * Use the new checks of production [4] [4a] amd [5] of the
+	 * Update 5 of XML-1.0
+	 */
+	if (((c >= 'a') && (c <= 'z')) ||
+	    ((c >= 'A') && (c <= 'Z')) ||
+	    (c == '_') || (c == ':') ||
+	    ((c >= 0xC0) && (c <= 0xD6)) ||
+	    ((c >= 0xD8) && (c <= 0xF6)) ||
+	    ((c >= 0xF8) && (c <= 0x2FF)) ||
+	    ((c >= 0x370) && (c <= 0x37D)) ||
+	    ((c >= 0x37F) && (c <= 0x1FFF)) ||
+	    ((c >= 0x200C) && (c <= 0x200D)) ||
+	    ((c >= 0x2070) && (c <= 0x218F)) ||
+	    ((c >= 0x2C00) && (c <= 0x2FEF)) ||
+	    ((c >= 0x3001) && (c <= 0xD7FF)) ||
+	    ((c >= 0xF900) && (c <= 0xFDCF)) ||
+	    ((c >= 0xFDF0) && (c <= 0xFFFD)) ||
+	    ((c >= 0x10000) && (c <= 0xEFFFF)))
+	    return(1);
+    } else {
+        if (IS_LETTER(c) || (c == '_') || (c == ':'))
+	    return(1);
+    }
+    return(0);
+}
+
+static int
+xmlIsDocNameChar(xmlDocPtr doc, int c) {
+    if ((doc == NULL) || (doc->properties & XML_DOC_OLD10) == 0) {
+        /*
+	 * Use the new checks of production [4] [4a] amd [5] of the
+	 * Update 5 of XML-1.0
+	 */
+	if (((c >= 'a') && (c <= 'z')) ||
+	    ((c >= 'A') && (c <= 'Z')) ||
+	    ((c >= '0') && (c <= '9')) || /* !start */
+	    (c == '_') || (c == ':') ||
+	    (c == '-') || (c == '.') || (c == 0xB7) || /* !start */
+	    ((c >= 0xC0) && (c <= 0xD6)) ||
+	    ((c >= 0xD8) && (c <= 0xF6)) ||
+	    ((c >= 0xF8) && (c <= 0x2FF)) ||
+	    ((c >= 0x300) && (c <= 0x36F)) || /* !start */
+	    ((c >= 0x370) && (c <= 0x37D)) ||
+	    ((c >= 0x37F) && (c <= 0x1FFF)) ||
+	    ((c >= 0x200C) && (c <= 0x200D)) ||
+	    ((c >= 0x203F) && (c <= 0x2040)) || /* !start */
+	    ((c >= 0x2070) && (c <= 0x218F)) ||
+	    ((c >= 0x2C00) && (c <= 0x2FEF)) ||
+	    ((c >= 0x3001) && (c <= 0xD7FF)) ||
+	    ((c >= 0xF900) && (c <= 0xFDCF)) ||
+	    ((c >= 0xFDF0) && (c <= 0xFFFD)) ||
+	    ((c >= 0x10000) && (c <= 0xEFFFF)))
+	     return(1);
+    } else {
+        if ((IS_LETTER(c)) || (IS_DIGIT(c)) ||
+            (c == '.') || (c == '-') ||
+	    (c == '_') || (c == ':') ||
+	    (IS_COMBINING(c)) ||
+	    (IS_EXTENDER(c)))
+	    return(1);
+    }
+    return(0);
+}
+
+/**
+ * xmlValidateNameValue:
+ * @doc:  pointer to the document or NULL
+ * @value:  an Name value
+ *
+ * Validate that the given value match Name production
+ *
+ * returns 1 if valid or 0 otherwise
+ */
+
+static int
+xmlValidateNameValueInternal(xmlDocPtr doc, const xmlChar *value) {
+    const xmlChar *cur;
+    int val, len;
+
+    if (value == NULL) return(0);
+    cur = value;
+    val = xmlStringCurrentChar(NULL, cur, &len);
+    cur += len;
+    if (!xmlIsDocNameStartChar(doc, val))
+	return(0);
+
+    val = xmlStringCurrentChar(NULL, cur, &len);
+    cur += len;
+    while (xmlIsDocNameChar(doc, val)) {
+	val = xmlStringCurrentChar(NULL, cur, &len);
+	cur += len;
+    }
+
+    if (val != 0) return(0);
+
+    return(1);
+}
+
 /**
  * xmlValidateNameValue:
  * @value:  an Name value
@@ -3456,6 +3568,21 @@
 
 int
 xmlValidateNameValue(const xmlChar *value) {
+    return(xmlValidateNameValueInternal(NULL, value));
+}
+
+/**
+ * xmlValidateNamesValueInternal:
+ * @doc:  pointer to the document or NULL
+ * @value:  an Names value
+ *
+ * Validate that the given value match Names production
+ *
+ * returns 1 if valid or 0 otherwise
+ */
+
+static int
+xmlValidateNamesValueInternal(xmlDocPtr doc, const xmlChar *value) {
     const xmlChar *cur;
     int val, len;
 
@@ -3463,22 +3590,36 @@
     cur = value;
     val = xmlStringCurrentChar(NULL, cur, &len);
     cur += len;
-    if (!IS_LETTER(val) && (val != '_') &&
-        (val != ':')) {
+
+    if (!xmlIsDocNameStartChar(doc, val))
 	return(0);
-    }
 
     val = xmlStringCurrentChar(NULL, cur, &len);
     cur += len;
-    while ((IS_LETTER(val)) || (IS_DIGIT(val)) ||
-           (val == '.') || (val == '-') ||
-	   (val == '_') || (val == ':') || 
-	   (IS_COMBINING(val)) ||
-	   (IS_EXTENDER(val))) {
+    while (xmlIsDocNameChar(doc, val)) {
 	val = xmlStringCurrentChar(NULL, cur, &len);
 	cur += len;
     }
 
+    /* Should not test IS_BLANK(val) here -- see erratum E20*/
+    while (val == 0x20) {
+	while (val == 0x20) {
+	    val = xmlStringCurrentChar(NULL, cur, &len);
+	    cur += len;
+	}
+
+	if (!xmlIsDocNameStartChar(doc, val))
+	    return(0);
+
+	val = xmlStringCurrentChar(NULL, cur, &len);
+	cur += len;
+
+	while (xmlIsDocNameChar(doc, val)) {
+	    val = xmlStringCurrentChar(NULL, cur, &len);
+	    cur += len;
+	}
+    }
+
     if (val != 0) return(0);
 
     return(1);
@@ -3495,6 +3636,23 @@
 
 int
 xmlValidateNamesValue(const xmlChar *value) {
+    return(xmlValidateNamesValueInternal(NULL, value));
+}
+
+/**
+ * xmlValidateNmtokenValueInternal:
+ * @doc:  pointer to the document or NULL
+ * @value:  an Nmtoken value
+ *
+ * Validate that the given value match Nmtoken production
+ *
+ * [ VC: Name Token ]
+ *
+ * returns 1 if valid or 0 otherwise
+ */
+
+static int
+xmlValidateNmtokenValueInternal(xmlDocPtr doc, const xmlChar *value) {
     const xmlChar *cur;
     int val, len;
 
@@ -3502,47 +3660,17 @@
     cur = value;
     val = xmlStringCurrentChar(NULL, cur, &len);
     cur += len;
-    
-    if (!IS_LETTER(val) && (val != '_') &&
-        (val != ':')) {
+
+    if (!xmlIsDocNameChar(doc, val))
 	return(0);
-    }
 
     val = xmlStringCurrentChar(NULL, cur, &len);
     cur += len;
-    while ((IS_LETTER(val)) || (IS_DIGIT(val)) ||
-           (val == '.') || (val == '-') ||
-	   (val == '_') || (val == ':') || 
-	   (IS_COMBINING(val)) ||
-	   (IS_EXTENDER(val))) {
+    while (xmlIsDocNameChar(doc, val)) {
 	val = xmlStringCurrentChar(NULL, cur, &len);
 	cur += len;
     }
 
-    /* Should not test IS_BLANK(val) here -- see erratum E20*/
-    while (val == 0x20) {
-	while (val == 0x20) {
-	    val = xmlStringCurrentChar(NULL, cur, &len);
-	    cur += len;
-	}
-
-	if (!IS_LETTER(val) && (val != '_') &&
-	    (val != ':')) {
-	    return(0);
-	}
-	val = xmlStringCurrentChar(NULL, cur, &len);
-	cur += len;
-
-	while ((IS_LETTER(val)) || (IS_DIGIT(val)) ||
-	       (val == '.') || (val == '-') ||
-	       (val == '_') || (val == ':') || 
-	       (IS_COMBINING(val)) ||
-	       (IS_EXTENDER(val))) {
-	    val = xmlStringCurrentChar(NULL, cur, &len);
-	    cur += len;
-	}
-    }
-
     if (val != 0) return(0);
 
     return(1);
@@ -3555,12 +3683,29 @@
  * Validate that the given value match Nmtoken production
  *
  * [ VC: Name Token ]
- * 
+ *
  * returns 1 if valid or 0 otherwise
  */
 
 int
 xmlValidateNmtokenValue(const xmlChar *value) {
+    return(xmlValidateNmtokenValueInternal(NULL, value));
+}
+
+/**
+ * xmlValidateNmtokensValueInternal:
+ * @doc:  pointer to the document or NULL
+ * @value:  an Nmtokens value
+ *
+ * Validate that the given value match Nmtokens production
+ *
+ * [ VC: Name Token ]
+ *
+ * returns 1 if valid or 0 otherwise
+ */
+
+static int
+xmlValidateNmtokensValueInternal(xmlDocPtr doc, const xmlChar *value) {
     const xmlChar *cur;
     int val, len;
 
@@ -3568,23 +3713,40 @@
     cur = value;
     val = xmlStringCurrentChar(NULL, cur, &len);
     cur += len;
-    
-    if (!IS_LETTER(val) && !IS_DIGIT(val) &&
-        (val != '.') && (val != '-') &&
-        (val != '_') && (val != ':') && 
-        (!IS_COMBINING(val)) &&
-        (!IS_EXTENDER(val)))
-	return(0);
 
-    while ((IS_LETTER(val)) || (IS_DIGIT(val)) ||
-           (val == '.') || (val == '-') ||
-	   (val == '_') || (val == ':') || 
-	   (IS_COMBINING(val)) ||
-	   (IS_EXTENDER(val))) {
+    while (IS_BLANK(val)) {
 	val = xmlStringCurrentChar(NULL, cur, &len);
 	cur += len;
     }
 
+    if (!xmlIsDocNameChar(doc, val))
+	return(0);
+
+    while (xmlIsDocNameChar(doc, val)) {
+	val = xmlStringCurrentChar(NULL, cur, &len);
+	cur += len;
+    }
+
+    /* Should not test IS_BLANK(val) here -- see erratum E20*/
+    while (val == 0x20) {
+	while (val == 0x20) {
+	    val = xmlStringCurrentChar(NULL, cur, &len);
+	    cur += len;
+	}
+	if (val == 0) return(1);
+
+	if (!xmlIsDocNameChar(doc, val))
+	    return(0);
+
+	val = xmlStringCurrentChar(NULL, cur, &len);
+	cur += len;
+
+	while (xmlIsDocNameChar(doc, val)) {
+	    val = xmlStringCurrentChar(NULL, cur, &len);
+	    cur += len;
+	}
+    }
+
     if (val != 0) return(0);
 
     return(1);
@@ -3597,69 +3759,13 @@
  * Validate that the given value match Nmtokens production
  *
  * [ VC: Name Token ]
- * 
+ *
  * returns 1 if valid or 0 otherwise
  */
 
 int
 xmlValidateNmtokensValue(const xmlChar *value) {
-    const xmlChar *cur;
-    int val, len;
-
-    if (value == NULL) return(0);
-    cur = value;
-    val = xmlStringCurrentChar(NULL, cur, &len);
-    cur += len;
-    
-    while (IS_BLANK(val)) {
-	val = xmlStringCurrentChar(NULL, cur, &len);
-	cur += len;
-    }
-
-    if (!IS_LETTER(val) && !IS_DIGIT(val) &&
-        (val != '.') && (val != '-') &&
-        (val != '_') && (val != ':') && 
-        (!IS_COMBINING(val)) &&
-        (!IS_EXTENDER(val)))
-	return(0);
-
-    while ((IS_LETTER(val)) || (IS_DIGIT(val)) ||
-           (val == '.') || (val == '-') ||
-	   (val == '_') || (val == ':') || 
-	   (IS_COMBINING(val)) ||
-	   (IS_EXTENDER(val))) {
-	val = xmlStringCurrentChar(NULL, cur, &len);
-	cur += len;
-    }
-
-    /* Should not test IS_BLANK(val) here -- see erratum E20*/
-    while (val == 0x20) {
-	while (val == 0x20) {
-	    val = xmlStringCurrentChar(NULL, cur, &len);
-	    cur += len;
-	}
-	if (val == 0) return(1);
-
-	if (!IS_LETTER(val) && !IS_DIGIT(val) &&
-	    (val != '.') && (val != '-') &&
-	    (val != '_') && (val != ':') && 
-	    (!IS_COMBINING(val)) &&
-	    (!IS_EXTENDER(val)))
-	    return(0);
-
-	while ((IS_LETTER(val)) || (IS_DIGIT(val)) ||
-	       (val == '.') || (val == '-') ||
-	       (val == '_') || (val == ':') || 
-	       (IS_COMBINING(val)) ||
-	       (IS_EXTENDER(val))) {
-	    val = xmlStringCurrentChar(NULL, cur, &len);
-	    cur += len;
-	}
-    }
-
-    if (val != 0) return(0);
-
-    return(1);
+    return(xmlValidateNmtokensValueInternal(NULL, value));
 }
 
 /**
@@ -3686,6 +3792,40 @@
 }
 
 /**
+ * xmlValidateAttributeValueInternal:
+ * @doc: the document
+ * @type:  an attribute type
+ * @value:  an attribute value
+ *
+ * Validate that the given attribute value match  the proper production
+ *
+ * returns 1 if valid or 0 otherwise
+ */
+
+static int
+xmlValidateAttributeValueInternal(xmlDocPtr doc, xmlAttributeType type,
+                                  const xmlChar *value) {
+    switch (type) {
+	case XML_ATTRIBUTE_ENTITIES:
+	case XML_ATTRIBUTE_IDREFS:
+	    return(xmlValidateNamesValueInternal(doc, value));
+	case XML_ATTRIBUTE_ENTITY:
+	case XML_ATTRIBUTE_IDREF:
+	case XML_ATTRIBUTE_ID:
+	case XML_ATTRIBUTE_NOTATION:
+	    return(xmlValidateNameValueInternal(doc, value));
+	case XML_ATTRIBUTE_NMTOKENS:
+	case XML_ATTRIBUTE_ENUMERATION:
+	    return(xmlValidateNmtokensValueInternal(doc, value));
+	case XML_ATTRIBUTE_NMTOKEN:
+	    return(xmlValidateNmtokenValueInternal(doc, value));
+        case XML_ATTRIBUTE_CDATA:
+	    break;
+    }
+    return(1);
+}
+
+/**
  * xmlValidateAttributeValue:
  * @type:  an attribute type
  * @value:  an attribute value
@@ -3709,27 +3849,9 @@
  *
  * returns 1 if valid or 0 otherwise
  */
-
 int
 xmlValidateAttributeValue(xmlAttributeType type, const xmlChar *value) {
-    switch (type) {
-	case XML_ATTRIBUTE_ENTITIES:
-	case XML_ATTRIBUTE_IDREFS:
-	    return(xmlValidateNamesValue(value));
-	case XML_ATTRIBUTE_ENTITY:
-	case XML_ATTRIBUTE_IDREF:
-	case XML_ATTRIBUTE_ID:
-	case XML_ATTRIBUTE_NOTATION:
-	    return(xmlValidateNameValue(value));
-	case XML_ATTRIBUTE_NMTOKENS:
-	case XML_ATTRIBUTE_ENUMERATION:
-	    return(xmlValidateNmtokensValue(value));
-	case XML_ATTRIBUTE_NMTOKEN:
-	    return(xmlValidateNmtokenValue(value));
-        case XML_ATTRIBUTE_CDATA:
-	    break;
-    }
-    return(1);
+    return(xmlValidateAttributeValueInternal(NULL, type, value));
 }
 
 /**
@@ -4047,11 +4169,12 @@
     int val;
     CHECK_DTD;
     if(attr == NULL) return(1);
-    
+
     /* Attribute Default Legal */
     /* Enumeration */
     if (attr->defaultValue != NULL) {
-	val = xmlValidateAttributeValue(attr->atype, attr->defaultValue);
+	val = xmlValidateAttributeValueInternal(doc, attr->atype,
+	                                        attr->defaultValue);
 	if (val == 0) {
 	    xmlErrValidNode(ctxt, (xmlNodePtr) attr, XML_DTD_ATTRIBUTE_DEFAULT,
 	       "Syntax of default value for attribute %s of %s is not valid\n",
@@ -4332,7 +4455,7 @@
     }
     attr->atype = attrDecl->atype;
 
-    val = xmlValidateAttributeValue(attrDecl->atype, value);
+    val = xmlValidateAttributeValueInternal(doc, attrDecl->atype, value);
     if (val == 0) {
 	    xmlErrValidNode(ctxt, elem, XML_DTD_ATTRIBUTE_VALUE,
 	   "Syntax of value for attribute %s of %s is not valid\n",
@@ -4517,7 +4640,7 @@
 	return(0);
     }
 
-    val = xmlValidateAttributeValue(attrDecl->atype, value);
+    val = xmlValidateAttributeValueInternal(doc, attrDecl->atype, value);
     if (val == 0) {
 	if (ns->prefix != NULL) {
 	    xmlErrValidNode(ctxt, elem, XML_DTD_INVALID_DEFAULT,
@@ -6673,7 +6796,7 @@
     xmlAttributeTablePtr table;
     xmlEntitiesTablePtr entities;
 
-    if (doc == NULL) return(0);
+    if ((doc == NULL) || (ctxt == NULL)) return(0);
     if ((doc->intSubset == NULL) && (doc->extSubset == NULL))
 	return(0);
     ctxt->doc = doc;
diff --git a/xinclude.c b/xinclude.c
index 31ea026..ae449f8 100644
--- a/xinclude.c
+++ b/xinclude.c
@@ -419,7 +419,6 @@
 xmlXIncludeParseFile(xmlXIncludeCtxtPtr ctxt, const char *URL) {
     xmlDocPtr ret;
     xmlParserCtxtPtr pctxt;
-    char *directory = NULL;
     xmlParserInputPtr inputStream;
 
     xmlInitParser();
@@ -456,10 +455,8 @@
 
     inputPush(pctxt, inputStream);
 
-    if ((pctxt->directory == NULL) && (directory == NULL))
-        directory = xmlParserGetDirectory(URL);
-    if ((pctxt->directory == NULL) && (directory != NULL))
-        pctxt->directory = (char *) xmlStrdup((xmlChar *) directory);
+    if (pctxt->directory == NULL)
+        pctxt->directory = xmlParserGetDirectory(URL);
 
     pctxt->loadsubset |= XML_DETECT_IDS;
 
@@ -516,9 +513,8 @@
 	href = xmlStrdup(BAD_CAST ""); /* @@@@ href is now optional */
 	if (href == NULL) 
 	    return(-1);
-	local = 1;
     }
-    if (href[0] == '#')
+    if ((href[0] == '#') || (href[0] == 0))
 	local = 1;
     parse = xmlXIncludeGetProp(ctxt, cur, XINCLUDE_PARSE);
     if (parse != NULL) {
@@ -617,6 +613,19 @@
     }
 
     /*
+     * If local and xml then we need a fragment
+     */
+    if ((local == 1) && (xml == 1) &&
+        ((fragment == NULL) || (fragment[0] == 0))) {
+	xmlXIncludeErr(ctxt, cur, XML_XINCLUDE_RECURSION,
+	               "detected a local recursion with no xpointer in %s\n",
+		       URL);
+	if (fragment != NULL)
+	    xmlFree(fragment);
+	return(-1);
+    }
+
+    /*
      * Check the URL against the stack for recursions
      */
     if ((!local) && (xml == 1)) {
@@ -1669,7 +1678,9 @@
     /*
      * Do the xml:base fixup if needed
      */
-    if ((doc != NULL) && (URL != NULL) && (xmlStrchr(URL, (xmlChar) '/'))) {
+    if ((doc != NULL) && (URL != NULL) && (xmlStrchr(URL, (xmlChar) '/')) &&
+        (!(ctxt->parseFlags & XML_PARSE_NOBASEFIX)) &&
+	(!(doc->parseFlags & XML_PARSE_NOBASEFIX))) {
 	xmlNodePtr node;
 	xmlChar *base;
 	xmlChar *curBase;
diff --git a/xmlIO.c b/xmlIO.c
index 7782776..d4dc364 100644
--- a/xmlIO.c
+++ b/xmlIO.c
@@ -135,6 +135,9 @@
 static xmlOutputCallback xmlOutputCallbackTable[MAX_OUTPUT_CALLBACK];
 static int xmlOutputCallbackNr = 0;
 static int xmlOutputCallbackInitialized = 0;
+
+xmlOutputBufferPtr
+xmlAllocOutputBufferInternal(xmlCharEncodingHandlerPtr encoder);
 #endif /* LIBXML_OUTPUT_ENABLED */
 
 /************************************************************************
@@ -1720,7 +1723,7 @@
     {
         /*  Any character conversions should have been done before this  */
 
-        ctxt->doc_buff = xmlAllocOutputBuffer(NULL);
+        ctxt->doc_buff = xmlAllocOutputBufferInternal(NULL);
     }
 
     if (ctxt->doc_buff == NULL) {
@@ -1731,7 +1734,7 @@
     return (ctxt);
 }
 #endif /* LIBXML_OUTPUT_ENABLED */
-				
+
 #ifdef LIBXML_OUTPUT_ENABLED
 /**
  * xmlIOHTTPDfltOpenW
@@ -2274,10 +2277,15 @@
         xmlFree(ret);
 	return(NULL);
     }
-    ret->buffer->alloc = XML_BUFFER_ALLOC_DOUBLEIT;
+
     ret->encoder = encoder;
     if (encoder != NULL) {
         ret->conv = xmlBufferCreateSize(4000);
+	if (ret->conv == NULL) {
+	    xmlFree(ret);
+	    return(NULL);
+	}
+
 	/*
 	 * This call is designed to initiate the encoder state
 	 */
@@ -2291,6 +2299,62 @@
 
     return(ret);
 }
+
+/**
+ * xmlAllocOutputBufferInternal:
+ * @encoder:  the encoding converter or NULL
+ *
+ * Create a buffered parser output
+ *
+ * Returns the new parser output or NULL
+ */
+xmlOutputBufferPtr
+xmlAllocOutputBufferInternal(xmlCharEncodingHandlerPtr encoder) {
+    xmlOutputBufferPtr ret;
+
+    ret = (xmlOutputBufferPtr) xmlMalloc(sizeof(xmlOutputBuffer));
+    if (ret == NULL) {
+	xmlIOErrMemory("creating output buffer");
+	return(NULL);
+    }
+    memset(ret, 0, (size_t) sizeof(xmlOutputBuffer));
+    ret->buffer = xmlBufferCreate();
+    if (ret->buffer == NULL) {
+        xmlFree(ret);
+	return(NULL);
+    }
+
+
+    /*
+     * For conversion buffers we use the special IO handling
+     * We don't do that from the exported API to avoid confusing
+     * user's code.
+     */
+    ret->buffer->alloc = XML_BUFFER_ALLOC_IO;
+    ret->buffer->contentIO = ret->buffer->content;
+
+    ret->encoder = encoder;
+    if (encoder != NULL) {
+        ret->conv = xmlBufferCreateSize(4000);
+	if (ret->conv == NULL) {
+	    xmlFree(ret);
+	    return(NULL);
+	}
+
+	/*
+	 * This call is designed to initiate the encoder state
+	 */
+	xmlCharEncOutFunc(encoder, ret->conv, NULL); 
+    } else
+        ret->conv = NULL;
+    ret->writecallback = NULL;
+    ret->closecallback = NULL;
+    ret->context = NULL;
+    ret->written = 0;
+
+    return(ret);
+}
+
 #endif /* LIBXML_OUTPUT_ENABLED */
 
 /**
@@ -2491,7 +2555,7 @@
 	if ((compression > 0) && (compression <= 9) && (is_file_uri == 1)) {
 	    context = xmlGzfileOpenW(unescaped, compression);
 	    if (context != NULL) {
-		ret = xmlAllocOutputBuffer(encoder);
+		ret = xmlAllocOutputBufferInternal(encoder);
 		if (ret != NULL) {
 		    ret->context = context;
 		    ret->writecallback = xmlGzfileWrite;
@@ -2528,7 +2592,7 @@
 	if ((compression > 0) && (compression <= 9) && (is_file_uri == 1)) {
 	    context = xmlGzfileOpenW(URI, compression);
 	    if (context != NULL) {
-		ret = xmlAllocOutputBuffer(encoder);
+		ret = xmlAllocOutputBufferInternal(encoder);
 		if (ret != NULL) {
 		    ret->context = context;
 		    ret->writecallback = xmlGzfileWrite;
@@ -2561,7 +2625,7 @@
     /*
      * Allocate the Output buffer front-end.
      */
-    ret = xmlAllocOutputBuffer(encoder);
+    ret = xmlAllocOutputBufferInternal(encoder);
     if (ret != NULL) {
 	ret->context = context;
 	ret->writecallback = xmlOutputCallbackTable[i].writecallback;
@@ -2645,7 +2709,7 @@
 
     if (file == NULL) return(NULL);
 
-    ret = xmlAllocOutputBuffer(encoder);
+    ret = xmlAllocOutputBufferInternal(encoder);
     if (ret != NULL) {
         ret->context = file;
 	ret->writecallback = xmlFileWrite;
@@ -2803,7 +2867,7 @@
 
     if (fd < 0) return(NULL);
 
-    ret = xmlAllocOutputBuffer(encoder);
+    ret = xmlAllocOutputBufferInternal(encoder);
     if (ret != NULL) {
         ret->context = (void *) (long) fd;
 	ret->writecallback = xmlFdWrite;
@@ -2864,7 +2928,7 @@
 
     if (iowrite == NULL) return(NULL);
 
-    ret = xmlAllocOutputBuffer(encoder);
+    ret = xmlAllocOutputBufferInternal(encoder);
     if (ret != NULL) {
         ret->context = (void *) ioctx;
 	ret->writecallback = iowrite;
@@ -3315,6 +3379,17 @@
 	cons = len;
 	chunk = (out->buffer->size - out->buffer->use) - 1;
 
+        /*
+	 * make sure we have enough room to save first, if this is
+	 * not the case force a flush, but make sure we stay in the loop
+	 */
+	if (chunk < 40) {
+	    if (xmlBufferGrow(out->buffer, out->buffer->size + 100) < 0)
+	        return(-1);
+            oldwritten = -1;
+	    continue;
+	}
+
 	/*
 	 * first handle encoding stuff.
 	 */
diff --git a/xmllint.c b/xmllint.c
index ee41697..77c1e62 100644
--- a/xmllint.c
+++ b/xmllint.c
@@ -202,6 +202,7 @@
 #endif
 static int options = XML_PARSE_COMPACT;
 static int sax = 0;
+static int oldxml10 = 0;
 
 /************************************************************************
  *									*
@@ -2752,9 +2753,11 @@
 #endif
 
 #ifdef LIBXML_DEBUG_ENABLED
+#if defined(LIBXML_HTML_ENABLED) || defined(LIBXML_VALID_ENABLED)
     if ((debugent) && (!html))
 	xmlDebugDumpEntities(stderr, doc);
 #endif
+#endif
 
     /*
      * free it.
@@ -2832,6 +2835,7 @@
     printf("\t--copy : used to test the internal copy implementation\n");
 #endif /* LIBXML_TREE_ENABLED */
     printf("\t--recover : output what was parsable on broken XML documents\n");
+    printf("\t--huge : remove any internal arbitrary parser limits\n");
     printf("\t--noent : substitute entity references by their value\n");
     printf("\t--noout : don't output the result tree\n");
     printf("\t--path 'paths': provide a set of paths for resources\n");
@@ -2890,6 +2894,7 @@
 #ifdef LIBXML_XINCLUDE_ENABLED
     printf("\t--xinclude : do XInclude processing\n");
     printf("\t--noxincludenode : same but do not generate XInclude nodes\n");
+    printf("\t--nofixup-base-uris : do not fixup xml:base uris\n");
 #endif
     printf("\t--loaddtd : fetch external DTD\n");
     printf("\t--dtdattr : loaddtd + populate the tree with inherited attributes \n");
@@ -2912,6 +2917,7 @@
     printf("\t--sax1: use the old SAX1 interfaces for processing\n");
 #endif
     printf("\t--sax: do not build a tree but work just at the SAX level\n");
+    printf("\t--oldxml10: use XML-1.0 parsing rules before the 5th edition\n");
 
     printf("\nLibxml project home page: http://xmlsoft.org/\n");
     printf("To report bugs or get some help check: http://xmlsoft.org/bugs.html\n");
@@ -2969,6 +2975,9 @@
 	         (!strcmp(argv[i], "--recover"))) {
 	    recovery++;
 	    options |= XML_PARSE_RECOVER;
+	} else if ((!strcmp(argv[i], "-huge")) ||
+	         (!strcmp(argv[i], "--huge"))) {
+	    options |= XML_PARSE_HUGE;
 	} else if ((!strcmp(argv[i], "-noent")) ||
 	         (!strcmp(argv[i], "--noent"))) {
 	    noent++;
@@ -3091,6 +3100,12 @@
 	    options |= XML_PARSE_XINCLUDE;
 	    options |= XML_PARSE_NOXINCNODE;
 	}
+	else if ((!strcmp(argv[i], "-nofixup-base-uris")) ||
+	         (!strcmp(argv[i], "--nofixup-base-uris"))) {
+	    xinclude++;
+	    options |= XML_PARSE_XINCLUDE;
+	    options |= XML_PARSE_NOBASEFIX;
+	}
 #endif
 #ifdef LIBXML_OUTPUT_ENABLED
 #ifdef HAVE_ZLIB_H
@@ -3237,6 +3252,10 @@
 	    i++;
 	    pattern = argv[i];
 #endif
+	} else if ((!strcmp(argv[i], "-oldxml10")) ||
+	           (!strcmp(argv[i], "--oldxml10"))) {
+	    oldxml10++;
+	    options |= XML_PARSE_OLD10;
 	} else {
 	    fprintf(stderr, "Unknown option %s\n", argv[i]);
 	    usage(argv[0]);
diff --git a/xmlmemory.c b/xmlmemory.c
index f9019a4..433abb8 100644
--- a/xmlmemory.c
+++ b/xmlmemory.c
@@ -34,7 +34,7 @@
 /**
  * MEM_LIST:
  *
- * keep track of all allocated blocks for error reporting 
+ * keep track of all allocated blocks for error reporting
  * Always build the memory list !
  */
 #ifdef DEBUG_MEMORY_LOCATION
@@ -162,7 +162,7 @@
 {
     MEMHDR *p;
     void *ret;
-    
+
     if (!xmlMemInitialized) xmlInitMemory();
 #ifdef DEBUG_MEMORY
     xmlGenericError(xmlGenericErrorContext,
@@ -170,7 +170,7 @@
 #endif
 
     TEST_POINT
-    
+
     p = (MEMHDR *) malloc(RESERVE_SIZE+size);
 
     if (!p) {
@@ -178,7 +178,7 @@
 		"xmlMallocLoc : Out of free space\n");
 	xmlMemoryDump();
 	return(NULL);
-    }   
+    }
     p->mh_tag = MEMTAG;
     p->mh_size = size;
     p->mh_type = MALLOC_TYPE;
@@ -193,19 +193,19 @@
     debugmem_list_add(p);
 #endif
     xmlMutexUnlock(xmlMemMutex);
-    
+
 #ifdef DEBUG_MEMORY
     xmlGenericError(xmlGenericErrorContext,
 	    "Malloc(%d) Ok\n",size);
 #endif
-    
+
     if (xmlMemStopAtBlock == p->mh_number) xmlMallocBreakpoint();
 
     ret = HDR_2_CLIENT(p);
 
     if (xmlMemTraceBlockAt == ret) {
 	xmlGenericError(xmlGenericErrorContext,
-			"%p : Malloc(%d) Ok\n", xmlMemTraceBlockAt, size);
+			"%p : Malloc(%ld) Ok\n", xmlMemTraceBlockAt, size);
 	xmlMallocBreakpoint();
     }
 
@@ -230,7 +230,7 @@
 {
     MEMHDR *p;
     void *ret;
-    
+
     if (!xmlMemInitialized) xmlInitMemory();
 #ifdef DEBUG_MEMORY
     xmlGenericError(xmlGenericErrorContext,
@@ -238,7 +238,7 @@
 #endif
 
     TEST_POINT
-    
+
     p = (MEMHDR *) malloc(RESERVE_SIZE+size);
 
     if (!p) {
@@ -246,7 +246,7 @@
 		"xmlMallocLoc : Out of free space\n");
 	xmlMemoryDump();
 	return(NULL);
-    }   
+    }
     p->mh_tag = MEMTAG;
     p->mh_size = size;
     p->mh_type = MALLOC_ATOMIC_TYPE;
@@ -266,14 +266,14 @@
     xmlGenericError(xmlGenericErrorContext,
 	    "Malloc(%d) Ok\n",size);
 #endif
-    
+
     if (xmlMemStopAtBlock == p->mh_number) xmlMallocBreakpoint();
 
     ret = HDR_2_CLIENT(p);
 
     if (xmlMemTraceBlockAt == ret) {
 	xmlGenericError(xmlGenericErrorContext,
-			"%p : Malloc(%d) Ok\n", xmlMemTraceBlockAt, size);
+			"%p : Malloc(%ld) Ok\n", xmlMemTraceBlockAt, size);
 	xmlMallocBreakpoint();
     }
 
@@ -341,14 +341,14 @@
     debugmem_list_delete(p);
 #endif
     xmlMutexUnlock(xmlMemMutex);
-    
+
     p = (MEMHDR *) realloc(p,RESERVE_SIZE+size);
     if (!p) {
 	 goto error;
     }
     if (xmlMemTraceBlockAt == ptr) {
 	xmlGenericError(xmlGenericErrorContext,
-			"%p : Realloced(%d -> %d) Ok\n",
+			"%p : Realloced(%ld -> %ld) Ok\n",
 			xmlMemTraceBlockAt, p->mh_size, size);
 	xmlMallocBreakpoint();
     }
@@ -374,8 +374,8 @@
 	    "Realloced(%d to %d) Ok\n", oldsize, size);
 #endif
     return(HDR_2_CLIENT(p));
-    
-error:    
+
+error:
     return(NULL);
 }
 
@@ -455,10 +455,10 @@
     xmlGenericError(xmlGenericErrorContext,
 	    "Freed(%d) Ok\n", size);
 #endif
-    
+
     return;
-    
-error:    
+
+error:
     xmlGenericError(xmlGenericErrorContext,
 	    "xmlMemFree(%lX) error\n", (unsigned long) ptr);
     xmlMallocBreakpoint();
@@ -504,16 +504,16 @@
     debugmem_list_add(p);
 #endif
     xmlMutexUnlock(xmlMemMutex);
-    
+
     s = (char *) HDR_2_CLIENT(p);
-    
+
     if (xmlMemStopAtBlock == p->mh_number) xmlMallocBreakpoint();
 
     if (s != NULL)
       strcpy(s,str);
     else
       goto error;
-    
+
     TEST_POINT
 
     if (xmlMemTraceBlockAt == s) {
@@ -617,7 +617,7 @@
     } else if ((i == 0) && (buf[i] == 0)) {
         fprintf(fp," null");
     } else {
-        if (buf[i] == 0) fprintf(fp," \"%.25s\"", buf); 
+        if (buf[i] == 0) fprintf(fp," \"%.25s\"", buf);
 	else {
             fprintf(fp," [");
 	    for (j = 0;j < i;j++)
@@ -629,6 +629,79 @@
 #endif
 
 /**
+ * xmlMemDisplayLast:
+ * @fp:  a FILE descriptor used as the output file, if NULL, the result is
+ *       written to the file .memorylist
+ * @nbBytes: the amount of memory to dump
+ *
+ * the last nbBytes of memory allocated and not freed, useful for dumping
+ * the memory left allocated between two places at runtime.
+ */
+
+void
+xmlMemDisplayLast(FILE *fp, long nbBytes)
+{
+#ifdef MEM_LIST
+    MEMHDR *p;
+    unsigned idx;
+    int     nb = 0;
+#endif
+    FILE *old_fp = fp;
+
+    if (nbBytes <= 0)
+        return;
+
+    if (fp == NULL) {
+	fp = fopen(".memorylist", "w");
+	if (fp == NULL)
+	    return;
+    }
+
+#ifdef MEM_LIST
+    fprintf(fp,"   Last %li MEMORY ALLOCATED : %lu, MAX was %lu\n",
+            nbBytes, debugMemSize, debugMaxMemSize);
+    fprintf(fp,"BLOCK  NUMBER   SIZE  TYPE\n");
+    idx = 0;
+    xmlMutexLock(xmlMemMutex);
+    p = memlist;
+    while ((p) && (nbBytes > 0)) {
+	  fprintf(fp,"%-5u  %6lu %6lu ",idx++,p->mh_number,
+		  (unsigned long)p->mh_size);
+        switch (p->mh_type) {
+           case STRDUP_TYPE:fprintf(fp,"strdup()  in ");break;
+           case MALLOC_TYPE:fprintf(fp,"malloc()  in ");break;
+           case REALLOC_TYPE:fprintf(fp,"realloc() in ");break;
+           case MALLOC_ATOMIC_TYPE:fprintf(fp,"atomicmalloc()  in ");break;
+           case REALLOC_ATOMIC_TYPE:fprintf(fp,"atomicrealloc() in ");break;
+           default:
+	        fprintf(fp,"Unknown memory block, may be corrupted");
+		xmlMutexUnlock(xmlMemMutex);
+		if (old_fp == NULL)
+		    fclose(fp);
+		return;
+        }
+	if (p->mh_file != NULL) fprintf(fp,"%s(%u)", p->mh_file, p->mh_line);
+        if (p->mh_tag != MEMTAG)
+	      fprintf(fp,"  INVALID");
+        nb++;
+	if (nb < 100)
+	    xmlMemContentShow(fp, p);
+	else
+	    fprintf(fp," skip");
+
+        fprintf(fp,"\n");
+	nbBytes -= (unsigned long)p->mh_size;
+        p = p->mh_next;
+    }
+    xmlMutexUnlock(xmlMemMutex);
+#else
+    fprintf(fp,"Memory list not compiled (MEM_LIST not defined !)\n");
+#endif
+    if (old_fp == NULL)
+	fclose(fp);
+}
+
+/**
  * xmlMemDisplay:
  * @fp:  a FILE descriptor used as the output file, if NULL, the result is
  *       written to the file .memorylist
@@ -665,7 +738,7 @@
     fprintf(fp,"      %s\n\n", buf);
 #endif
 
-    
+
     fprintf(fp,"      MEMORY ALLOCATED : %lu, MAX was %lu\n",
             debugMemSize, debugMaxMemSize);
     fprintf(fp,"BLOCK  NUMBER   SIZE  TYPE\n");
@@ -742,7 +815,7 @@
  *
  * internal error function.
  */
- 
+
 static void debugmem_tag_error(void *p)
 {
      xmlGenericError(xmlGenericErrorContext,
@@ -802,7 +875,7 @@
 	}
     }
     xmlMutexUnlock(xmlMemMutex);
-#endif /* MEM_LIST */    
+#endif /* MEM_LIST */
 }
 
 /**
@@ -849,11 +922,11 @@
 {
 #ifdef HAVE_STDLIB_H
      char *breakpoint;
-#endif     
+#endif
 #ifdef DEBUG_MEMORY
      xmlGenericError(xmlGenericErrorContext,
 	     "xmlInitMemory()\n");
-#endif     
+#endif
     /*
      This is really not good code (see Bug 130419).  Suggestions for
      improvement will be welcome!
@@ -867,18 +940,18 @@
      if (breakpoint != NULL) {
          sscanf(breakpoint, "%ud", &xmlMemStopAtBlock);
      }
-#endif     
+#endif
 #ifdef HAVE_STDLIB_H
      breakpoint = getenv("XML_MEM_TRACE");
      if (breakpoint != NULL) {
          sscanf(breakpoint, "%p", &xmlMemTraceBlockAt);
      }
-#endif     
-    
+#endif
+
 #ifdef DEBUG_MEMORY
      xmlGenericError(xmlGenericErrorContext,
 	     "xmlInitMemory() Ok\n");
-#endif     
+#endif
      return(0);
 }
 
@@ -893,7 +966,7 @@
 #ifdef DEBUG_MEMORY
      xmlGenericError(xmlGenericErrorContext,
 	     "xmlCleanupMemory()\n");
-#endif     
+#endif
     if (xmlMemInitialized == 0)
         return;
 
@@ -903,7 +976,7 @@
 #ifdef DEBUG_MEMORY
      xmlGenericError(xmlGenericErrorContext,
 	     "xmlCleanupMemory() Ok\n");
-#endif     
+#endif
 }
 
 /**
@@ -927,7 +1000,7 @@
 #ifdef DEBUG_MEMORY
      xmlGenericError(xmlGenericErrorContext,
 	     "xmlMemSetup()\n");
-#endif     
+#endif
     if (freeFunc == NULL)
 	return(-1);
     if (mallocFunc == NULL)
@@ -944,7 +1017,7 @@
 #ifdef DEBUG_MEMORY
      xmlGenericError(xmlGenericErrorContext,
 	     "xmlMemSetup() Ok\n");
-#endif     
+#endif
     return(0);
 }
 
@@ -994,7 +1067,7 @@
 #ifdef DEBUG_MEMORY
      xmlGenericError(xmlGenericErrorContext,
 	     "xmlGcMemSetup()\n");
-#endif     
+#endif
     if (freeFunc == NULL)
 	return(-1);
     if (mallocFunc == NULL)
@@ -1013,7 +1086,7 @@
 #ifdef DEBUG_MEMORY
      xmlGenericError(xmlGenericErrorContext,
 	     "xmlGcMemSetup() Ok\n");
-#endif     
+#endif
     return(0);
 }
 
diff --git a/xmlmodule.c b/xmlmodule.c
index 15bcf07..9ffd610 100644
--- a/xmlmodule.c
+++ b/xmlmodule.c
@@ -190,7 +190,7 @@
     return (0);
 }
 
-#ifdef HAVE_DLOPEN
+#if defined(HAVE_DLOPEN) && !defined(_WIN32)
 #ifdef HAVE_DLFCN_H
 #include <dlfcn.h>
 #endif
diff --git a/xmlreader.c b/xmlreader.c
index d7bddec..d42b1a0 100644
--- a/xmlreader.c
+++ b/xmlreader.c
@@ -44,6 +44,27 @@
 #include <libxml/pattern.h>
 #endif
 
+#define MAX_ERR_MSG_SIZE 64000
+
+/*
+ * The following VA_COPY was coded following an example in
+ * the Samba project.  It may not be sufficient for some
+ * esoteric implementations of va_list (i.e. it may need
+ * something involving a memcpy) but (hopefully) will be
+ * sufficient for libxml2.
+ */
+#ifndef VA_COPY
+  #ifdef HAVE_VA_COPY
+    #define VA_COPY(dest, src) va_copy(dest, src)
+  #else
+    #ifdef HAVE___VA_COPY
+      #define VA_COPY(dest,src) __va_copy(dest, src)
+    #else
+      #define VA_COPY(dest,src) (dest) = (src)
+    #endif
+  #endif
+#endif
+
 /* #define DEBUG_CALLBACKS */
 /* #define DEBUG_READER */
 
@@ -234,8 +255,6 @@
     if (table == NULL) 
         return(-1);
 
-    if (attr == NULL)
-	return(-1);
     ID = xmlNodeListGetString(doc, attr->children, 1);
     if (ID == NULL)
 	return(-1);
@@ -1849,17 +1868,22 @@
     }
 
     if (reader->state != XML_TEXTREADER_BACKTRACK) {
-        if (reader->node->children != 0) {
-            reader->node = reader->node->children;
-            reader->depth++;
+	/* Here removed traversal to child, because we want to skip the subtree,
+	replace with traversal to sibling to skip subtree */
+        if (reader->node->next != 0) {
+	    /* Move to sibling if present,skipping sub-tree */
+            reader->node = reader->node->next;
             reader->state = XML_TEXTREADER_START;
             return(1);
         }
 
+	/* if reader->node->next is NULL mean no subtree for current node,
+	so need to move to sibling of parent node if present */
         if ((reader->node->type == XML_ELEMENT_NODE) ||
             (reader->node->type == XML_ATTRIBUTE_NODE)) {
             reader->state = XML_TEXTREADER_BACKTRACK;
-            return(1);
+	    /* This will move to parent if present */
+            xmlTextReaderRead(reader);
         }
     }
 
@@ -1878,7 +1902,8 @@
         reader->node = reader->node->parent;
         reader->depth--;
         reader->state = XML_TEXTREADER_BACKTRACK;
-        return(1);
+	/* Repeat process to move to sibling of parent node if present */
+        xmlTextReaderNextTree(reader);
     }
 
     reader->state = XML_TEXTREADER_END;
@@ -2936,7 +2961,7 @@
  *
  * Get the node type of the current node
  * Reference:
- * http://dotgnu.org/pnetlib-doc/System/Xml/XmlNodeType.html
+ * http://www.gnu.org/software/dotgnu/pnetlib-doc/System/Xml/XmlNodeType.html
  *
  * Returns the xmlNodeType of the current node or -1 in case of error
  */
@@ -3960,8 +3985,7 @@
 	return(NULL);
     if (reader->doc != NULL)
         return(reader->doc);
-    if ((reader == NULL) || (reader->ctxt == NULL) ||
-        (reader->ctxt->myDoc == NULL))
+    if ((reader->ctxt == NULL) || (reader->ctxt->myDoc == NULL))
 	return(NULL);
     
     reader->preserve = 1;
@@ -4497,30 +4521,32 @@
 /* helper to build a xmlMalloc'ed string from a format and va_list */
 static char *
 xmlTextReaderBuildMessage(const char *msg, va_list ap) {
-    int size;
+    int size = 0;
     int chars;
     char *larger;
-    char *str;
-
-    str = (char *) xmlMallocAtomic(150);
-    if (str == NULL) {
-	xmlGenericError(xmlGenericErrorContext, "xmlMalloc failed !\n");
-        return NULL;
-    }
-
-    size = 150;
+    char *str = NULL;
+    va_list aq;
 
     while (1) {
-        chars = vsnprintf(str, size, msg, ap);
-        if ((chars > -1) && (chars < size))
+        VA_COPY(aq, ap);
+        chars = vsnprintf(str, size, msg, aq);
+        va_end(aq);
+        if (chars < 0) {
+	    xmlGenericError(xmlGenericErrorContext, "vsnprintf failed !\n");
+	    if (str) 
+	    	xmlFree(str);
+	    return NULL;  
+	}
+	if ((chars < size) || (size == MAX_ERR_MSG_SIZE))
             break;
-        if (chars > -1)
-            size += chars + 1;
-        else
-            size += 100;
+        if (chars < MAX_ERR_MSG_SIZE)
+        	size = chars + 1;
+	else
+		size = MAX_ERR_MSG_SIZE;
         if ((larger = (char *) xmlRealloc(str, size)) == NULL) {
 	    xmlGenericError(xmlGenericErrorContext, "xmlRealloc failed !\n");
-            xmlFree(str);
+	    if (str)
+            	xmlFree(str);
             return NULL;
         }
         str = larger;
diff --git a/xmlregexp.c b/xmlregexp.c
index a3e16c5..73598a5 100644
--- a/xmlregexp.c
+++ b/xmlregexp.c
@@ -1532,6 +1532,8 @@
 static int
 xmlFAGenerateTransitions(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr from,
 	                 xmlRegStatePtr to, xmlRegAtomPtr atom) {
+    xmlRegStatePtr end;
+
     if (atom == NULL) {
 	ERROR("genrate transition: atom == NULL");
 	return(-1);
@@ -1689,12 +1691,31 @@
 	else {
 	    return(-1);
 	}
+    } 
+    end = to;
+    if ((atom->quant == XML_REGEXP_QUANT_MULT) || 
+        (atom->quant == XML_REGEXP_QUANT_PLUS)) {
+	/*
+	 * Do not pollute the target state by adding transitions from
+	 * it as it is likely to be the shared target of multiple branches.
+	 * So isolate with an epsilon transition.
+	 */
+        xmlRegStatePtr tmp;
+	
+	tmp = xmlRegNewState(ctxt);
+	if (tmp != NULL)
+	    xmlRegStatePush(ctxt, tmp);
+	else {
+	    return(-1);
+	}
+	xmlFAGenerateEpsilonTransition(ctxt, tmp, to);
+	to = tmp;
     }
     if (xmlRegAtomPush(ctxt, atom) < 0) {
 	return(-1);
     }
     xmlRegStateAddTrans(ctxt, from, atom, to, -1, -1);
-    ctxt->state = to;
+    ctxt->state = end;
     switch (atom->quant) {
 	case XML_REGEXP_QUANT_OPT:
 	    atom->quant = XML_REGEXP_QUANT_ONCE;
@@ -3141,7 +3162,8 @@
 	exec->counts = NULL;
     while ((exec->status == 0) &&
 	   ((exec->inputString[exec->index] != 0) ||
-	    (exec->state->type != XML_REGEXP_FINAL_STATE))) {
+	    ((exec->state != NULL) &&
+	     (exec->state->type != XML_REGEXP_FINAL_STATE)))) {
 	xmlRegTransPtr trans;
 	xmlRegAtomPtr atom;
 
@@ -4885,64 +4907,6 @@
 }
 
 /**
- * xmlFAParseCharRef:
- * @ctxt:  a regexp parser context
- *
- * [19]   XmlCharRef   ::=   ( '&#' [0-9]+ ';' ) | (' &#x' [0-9a-fA-F]+ ';' )
- */
-static int
-xmlFAParseCharRef(xmlRegParserCtxtPtr ctxt) {
-    int ret = 0, cur;
-
-    if ((CUR != '&') || (NXT(1) != '#'))
-	return(-1);
-    NEXT;
-    NEXT;
-    cur = CUR;
-    if (cur == 'x') {
-	NEXT;
-	cur = CUR;
-	if (((cur >= '0') && (cur <= '9')) ||
-	    ((cur >= 'a') && (cur <= 'f')) ||
-	    ((cur >= 'A') && (cur <= 'F'))) {
-	    while (((cur >= '0') && (cur <= '9')) ||
-	           ((cur >= 'a') && (cur <= 'f')) ||
-		   ((cur >= 'A') && (cur <= 'F'))) {
-		if ((cur >= '0') && (cur <= '9'))
-		    ret = ret * 16 + cur - '0';
-		else if ((cur >= 'a') && (cur <= 'f'))
-		    ret = ret * 16 + 10 + (cur - 'a');
-		else
-		    ret = ret * 16 + 10 + (cur - 'A');
-		NEXT;
-		cur = CUR;
-	    }
-	} else {
-	    ERROR("Char ref: expecting [0-9A-F]");
-	    return(-1);
-	}
-    } else {
-	if ((cur >= '0') && (cur <= '9')) {
-	    while ((cur >= '0') && (cur <= '9')) {
-		ret = ret * 10 + cur - '0';
-		NEXT;
-		cur = CUR;
-	    }
-	} else {
-	    ERROR("Char ref: expecting [0-9]");
-	    return(-1);
-	}
-    }
-    if (cur != ';') {
-	ERROR("Char ref: expecting ';'");
-	return(-1);
-    } else {
-	NEXT;
-    }
-    return(ret);
-}
-
-/**
  * xmlFAParseCharRange:
  * @ctxt:  a regexp parser context
  *
@@ -4963,12 +4927,6 @@
 	return;
     }
 
-    if ((CUR == '&') && (NXT(1) == '#')) {
-	end = start = xmlFAParseCharRef(ctxt);
-        xmlRegAtomAddRange(ctxt, ctxt->atom, ctxt->neg,
-	                   XML_REGEXP_CHARVAL, start, end, NULL);
-	return;
-    }
     cur = CUR;
     if (cur == '\\') {
 	NEXT;
@@ -5052,7 +5010,7 @@
 static void
 xmlFAParsePosCharGroup(xmlRegParserCtxtPtr ctxt) {
     do {
-	if ((CUR == '\\') || (CUR == '.')) {
+	if (CUR == '\\') {
 	    xmlFAParseCharClassEsc(ctxt);
 	} else {
 	    xmlFAParseCharRange(ctxt);
diff --git a/xmlsave.c b/xmlsave.c
index cbabd78..53b23e6 100644
--- a/xmlsave.c
+++ b/xmlsave.c
@@ -457,6 +457,40 @@
  *									*
  ************************************************************************/
 
+static int xmlSaveSwitchEncoding(xmlSaveCtxtPtr ctxt, const char *encoding) {
+    xmlOutputBufferPtr buf = ctxt->buf;
+
+    if ((encoding != NULL) && (buf->encoder == NULL) && (buf->conv == NULL)) {
+	buf->encoder = xmlFindCharEncodingHandler((const char *)encoding);
+	if (buf->encoder == NULL) {
+	    xmlSaveErr(XML_SAVE_UNKNOWN_ENCODING, NULL,
+		       (const char *)encoding);
+	    return(-1);
+	}
+	buf->conv = xmlBufferCreate();
+	if (buf->conv == NULL) {
+	    xmlCharEncCloseFunc(buf->encoder);
+	    xmlSaveErrMemory("creating encoding buffer");
+	    return(-1);
+	}
+	/*
+	 * initialize the state, e.g. if outputting a BOM
+	 */
+	xmlCharEncOutFunc(buf->encoder, buf->conv, NULL);
+    }
+    return(0);
+}
+
+static int xmlSaveClearEncoding(xmlSaveCtxtPtr ctxt) {
+    xmlOutputBufferPtr buf = ctxt->buf;
+    xmlOutputBufferFlush(buf);
+    xmlCharEncCloseFunc(buf->encoder);
+    xmlBufferFree(buf->conv);
+    buf->encoder = NULL;
+    buf->conv = NULL;
+    return(0);
+}
+
 #ifdef LIBXML_HTML_ENABLED
 static void
 xhtmlNodeDumpOutput(xmlSaveCtxtPtr ctxt, xmlNodePtr cur);
@@ -638,6 +672,66 @@
     }
 }
 
+#ifdef LIBXML_HTML_ENABLED
+/**
+ * xmlNodeDumpOutputInternal:
+ * @cur:  the current node
+ *
+ * Dump an HTML node, recursive behaviour, children are printed too.
+ */
+static int
+htmlNodeDumpOutputInternal(xmlSaveCtxtPtr ctxt, xmlNodePtr cur) {
+    const xmlChar *oldenc = NULL;
+    const xmlChar *oldctxtenc = ctxt->encoding;
+    const xmlChar *encoding = ctxt->encoding;
+    xmlOutputBufferPtr buf = ctxt->buf;
+    int switched_encoding = 0;
+    xmlDocPtr doc;
+
+    xmlInitParser();
+
+    doc = cur->doc; {
+    if (doc != NULL)
+        oldenc = doc->encoding;
+	if (ctxt->encoding != NULL) {
+	    doc->encoding = BAD_CAST ctxt->encoding;
+	} else if (doc->encoding != NULL) {
+	    encoding = doc->encoding;
+	}
+    }
+
+    if ((encoding != NULL) && (doc != NULL))
+	htmlSetMetaEncoding(doc, (const xmlChar *) encoding);
+    if ((encoding == NULL) && (doc != NULL))
+	encoding = htmlGetMetaEncoding(doc);
+    if (encoding == NULL)
+	encoding = BAD_CAST "HTML";
+    if ((encoding != NULL) && (oldctxtenc == NULL) &&
+	(buf->encoder == NULL) && (buf->conv == NULL)) {
+	if (xmlSaveSwitchEncoding(ctxt, (const char*) encoding) < 0) {
+	    doc->encoding = oldenc;
+	    return(-1);
+	}
+	switched_encoding = 1;
+    }
+    if (ctxt->options & XML_SAVE_FORMAT)
+	htmlNodeDumpFormatOutput(buf, doc, cur,
+				       (const char *)encoding, 1);
+    else
+	htmlNodeDumpFormatOutput(buf, doc, cur,
+				       (const char *)encoding, 0);
+    /*
+     * Restore the state of the saving context at the end of the document
+     */
+    if ((switched_encoding) && (oldctxtenc == NULL)) {
+	xmlSaveClearEncoding(ctxt);
+    }
+    if (doc != NULL)
+	doc->encoding = oldenc;
+    return(0);
+}
+#endif
+
 /**
  * xmlNodeDumpOutputInternal:
  * @cur:  the current node
@@ -662,6 +756,19 @@
 	xmlDocContentDumpOutput(ctxt, (xmlDocPtr) cur);
 	return;
     }
+#ifdef LIBXML_HTML_ENABLED
+    if (ctxt->options & XML_SAVE_XHTML) {
+        xhtmlNodeDumpOutput(ctxt, cur);
+        return;
+    }
+    if (((cur->type != XML_NAMESPACE_DECL) && (cur->doc != NULL) &&
+         (cur->doc->type == XML_HTML_DOCUMENT_NODE) &&
+         ((ctxt->options & XML_SAVE_AS_XML) == 0)) ||
+        (ctxt->options & XML_SAVE_AS_HTML)) {
+	htmlNodeDumpOutputInternal(ctxt, cur);
+	return;
+    }
+#endif
     if (cur->type == XML_DTD_NODE) {
         xmlDtdDumpOutput(ctxt, (xmlDtdPtr) cur);
 	return;
@@ -727,8 +834,8 @@
 	return;
     }
     if (cur->type == XML_CDATA_SECTION_NODE) {
-	if (cur->content == NULL) {
-		xmlOutputBufferWrite(buf, 12, "<![CDATA[]]>");
+	if (cur->content == NULL || *cur->content == '\0') {
+	    xmlOutputBufferWrite(buf, 12, "<![CDATA[]]>");
 	} else {
 	    start = end = cur->content;
 	    while (*end != '\0') {
@@ -835,9 +942,14 @@
     xmlCharEncodingOutputFunc oldescapeAttr = ctxt->escapeAttr;
     xmlOutputBufferPtr buf = ctxt->buf;
     xmlCharEncoding enc;
+    int switched_encoding = 0;
 
     xmlInitParser();
 
+    if ((cur->type != XML_HTML_DOCUMENT_NODE) &&
+        (cur->type != XML_DOCUMENT_NODE))
+	 return(-1);
+
     if (ctxt->encoding != NULL) {
         cur->encoding = BAD_CAST ctxt->encoding;
     } else if (cur->encoding != NULL) {
@@ -847,110 +959,126 @@
 		     xmlGetCharEncodingName((xmlCharEncoding) cur->charset);
     }
 
-    enc = xmlParseCharEncoding((const char*) encoding);
-    if ((encoding != NULL) && (oldctxtenc == NULL) &&
-        (buf->encoder == NULL) && (buf->conv == NULL) &&
-	((ctxt->options & XML_SAVE_NO_DECL) == 0)) {
-	if ((enc != XML_CHAR_ENCODING_UTF8) &&
-	    (enc != XML_CHAR_ENCODING_NONE) &&
-	    (enc != XML_CHAR_ENCODING_ASCII)) {
-	    /*
-	     * we need to switch to this encoding but just for this document
-	     * since we output the XMLDecl the conversion must be done to not
-	     * generate not well formed documents.
-	     */
-	    buf->encoder = xmlFindCharEncodingHandler((const char *)encoding);
-	    if (buf->encoder == NULL) {
-		xmlSaveErr(XML_SAVE_UNKNOWN_ENCODING, NULL,
-		           (const char *)encoding);
+    if (((cur->type == XML_HTML_DOCUMENT_NODE) &&
+         ((ctxt->options & XML_SAVE_AS_XML) == 0) &&
+         ((ctxt->options & XML_SAVE_XHTML) == 0)) ||
+        (ctxt->options & XML_SAVE_AS_HTML)) {
+#ifdef LIBXML_HTML_ENABLED
+        if (encoding != NULL)
+	    htmlSetMetaEncoding(cur, (const xmlChar *) encoding);
+        if (encoding == NULL)
+	    encoding = htmlGetMetaEncoding(cur);
+        if (encoding == NULL)
+	    encoding = BAD_CAST "HTML";
+	if ((encoding != NULL) && (oldctxtenc == NULL) &&
+	    (buf->encoder == NULL) && (buf->conv == NULL)) {
+	    if (xmlSaveSwitchEncoding(ctxt, (const char*) encoding) < 0) {
+		cur->encoding = oldenc;
 		return(-1);
 	    }
-	    buf->conv = xmlBufferCreate();
-	    if (buf->conv == NULL) {
-		xmlCharEncCloseFunc(buf->encoder);
-		xmlSaveErrMemory("creating encoding buffer");
-		return(-1);
-	    }
-	    /*
-	     * initialize the state, e.g. if outputting a BOM
-	     */
-	    xmlCharEncOutFunc(buf->encoder, buf->conv, NULL);
+	    switched_encoding = 1;
 	}
-	if (ctxt->escape == xmlEscapeEntities)
-	    ctxt->escape = NULL;
-	if (ctxt->escapeAttr == xmlEscapeEntities)
-	    ctxt->escapeAttr = NULL;
-    }
-
-
-    /*
-     * Save the XML declaration
-     */
-    if ((ctxt->options & XML_SAVE_NO_DECL) == 0) {
-	xmlOutputBufferWrite(buf, 14, "<?xml version=");
-	if (cur->version != NULL) 
-	    xmlBufferWriteQuotedString(buf->buffer, cur->version);
+        if (ctxt->options & XML_SAVE_FORMAT)
+	    htmlDocContentDumpFormatOutput(buf, cur,
+	                                   (const char *)encoding, 1);
 	else
-	    xmlOutputBufferWrite(buf, 5, "\"1.0\"");
-	if (encoding != NULL) {
-	    xmlOutputBufferWrite(buf, 10, " encoding=");
-	    xmlBufferWriteQuotedString(buf->buffer, (xmlChar *) encoding);
-	}
-	switch (cur->standalone) {
-	    case 0:
-		xmlOutputBufferWrite(buf, 16, " standalone=\"no\"");
-		break;
-	    case 1:
-		xmlOutputBufferWrite(buf, 17, " standalone=\"yes\"");
-		break;
-	}
-	xmlOutputBufferWrite(buf, 3, "?>\n");
-    }
-
-#ifdef LIBXML_HTML_ENABLED
-    if ((ctxt->options & XML_SAVE_NO_XHTML) == 0) {
-	dtd = xmlGetIntSubset(cur);
-	if (dtd != NULL) {
-	    is_xhtml = xmlIsXHTML(dtd->SystemID, dtd->ExternalID);
-	    if (is_xhtml < 0) is_xhtml = 0;
-	}
-    }
+	    htmlDocContentDumpFormatOutput(buf, cur,
+	                                   (const char *)encoding, 0);
+	if (ctxt->encoding != NULL)
+	    cur->encoding = oldenc;
+	return(0);
+#else
+        return(-1);
 #endif
-    if (cur->children != NULL) {
-        xmlNodePtr child = cur->children;
+    } else if ((cur->type == XML_DOCUMENT_NODE) ||
+               (ctxt->options & XML_SAVE_AS_XML) ||
+               (ctxt->options & XML_SAVE_XHTML)) {
+	enc = xmlParseCharEncoding((const char*) encoding);
+	if ((encoding != NULL) && (oldctxtenc == NULL) &&
+	    (buf->encoder == NULL) && (buf->conv == NULL) &&
+	    ((ctxt->options & XML_SAVE_NO_DECL) == 0)) {
+	    if ((enc != XML_CHAR_ENCODING_UTF8) &&
+		(enc != XML_CHAR_ENCODING_NONE) &&
+		(enc != XML_CHAR_ENCODING_ASCII)) {
+		/*
+		 * we need to switch to this encoding but just for this
+		 * document since we output the XMLDecl the conversion
+		 * must be done to not generate not well formed documents.
+		 */
+		if (xmlSaveSwitchEncoding(ctxt, (const char*) encoding) < 0) {
+		    cur->encoding = oldenc;
+		    return(-1);
+		}
+		switched_encoding = 1;
+	    }
+	    if (ctxt->escape == xmlEscapeEntities)
+		ctxt->escape = NULL;
+	    if (ctxt->escapeAttr == xmlEscapeEntities)
+		ctxt->escapeAttr = NULL;
+	}
 
-	while (child != NULL) {
-	    ctxt->level = 0;
-#ifdef LIBXML_HTML_ENABLED
-	    if (is_xhtml)
-		xhtmlNodeDumpOutput(ctxt, child);
+
+	/*
+	 * Save the XML declaration
+	 */
+	if ((ctxt->options & XML_SAVE_NO_DECL) == 0) {
+	    xmlOutputBufferWrite(buf, 14, "<?xml version=");
+	    if (cur->version != NULL) 
+		xmlBufferWriteQuotedString(buf->buffer, cur->version);
 	    else
+		xmlOutputBufferWrite(buf, 5, "\"1.0\"");
+	    if (encoding != NULL) {
+		xmlOutputBufferWrite(buf, 10, " encoding=");
+		xmlBufferWriteQuotedString(buf->buffer, (xmlChar *) encoding);
+	    }
+	    switch (cur->standalone) {
+		case 0:
+		    xmlOutputBufferWrite(buf, 16, " standalone=\"no\"");
+		    break;
+		case 1:
+		    xmlOutputBufferWrite(buf, 17, " standalone=\"yes\"");
+		    break;
+	    }
+	    xmlOutputBufferWrite(buf, 3, "?>\n");
+	}
+
+#ifdef LIBXML_HTML_ENABLED
+        if (ctxt->options & XML_SAVE_XHTML)
+            is_xhtml = 1;
+	if ((ctxt->options & XML_SAVE_NO_XHTML) == 0) {
+	    dtd = xmlGetIntSubset(cur);
+	    if (dtd != NULL) {
+		is_xhtml = xmlIsXHTML(dtd->SystemID, dtd->ExternalID);
+		if (is_xhtml < 0) is_xhtml = 0;
+	    }
+	}
 #endif
-		xmlNodeDumpOutputInternal(ctxt, child);
-	    xmlOutputBufferWrite(buf, 1, "\n");
-	    child = child->next;
+	if (cur->children != NULL) {
+	    xmlNodePtr child = cur->children;
+
+	    while (child != NULL) {
+		ctxt->level = 0;
+#ifdef LIBXML_HTML_ENABLED
+		if (is_xhtml)
+		    xhtmlNodeDumpOutput(ctxt, child);
+		else
+#endif
+		    xmlNodeDumpOutputInternal(ctxt, child);
+		xmlOutputBufferWrite(buf, 1, "\n");
+		child = child->next;
+	    }
 	}
     }
-    if (ctxt->encoding != NULL)
-        cur->encoding = oldenc;
-    
+
     /*
      * Restore the state of the saving context at the end of the document
      */
-    if ((encoding != NULL) && (oldctxtenc == NULL) &&
-	((ctxt->options & XML_SAVE_NO_DECL) == 0)) {
-	if ((enc != XML_CHAR_ENCODING_UTF8) &&
-	    (enc != XML_CHAR_ENCODING_NONE) &&
-	    (enc != XML_CHAR_ENCODING_ASCII)) {
-	    xmlOutputBufferFlush(buf);
-	    xmlCharEncCloseFunc(buf->encoder);
-	    xmlBufferFree(buf->conv);
-	    buf->encoder = NULL;
-	    buf->conv = NULL;
-	}
+    if ((switched_encoding) && (oldctxtenc == NULL)) {
+	xmlSaveClearEncoding(ctxt);
 	ctxt->escape = oldescape;
 	ctxt->escapeAttr = oldescapeAttr;
     }
+    cur->encoding = oldenc;
     return(0);
 }
 
@@ -1236,21 +1364,25 @@
 	return;
     }
     if (cur->type == XML_CDATA_SECTION_NODE) {
-	start = end = cur->content;
-	while (*end != '\0') {
-	    if (*end == ']' && *(end + 1) == ']' && *(end + 2) == '>') {
-		end = end + 2;
-		xmlOutputBufferWrite(buf, 9, "<![CDATA[");
-		xmlOutputBufferWrite(buf, end - start, (const char *)start);
-		xmlOutputBufferWrite(buf, 3, "]]>");
-		start = end;
+	if (cur->content == NULL || *cur->content == '\0') {
+	    xmlOutputBufferWrite(buf, 12, "<![CDATA[]]>");
+	} else {
+	    start = end = cur->content;
+	    while (*end != '\0') {
+		if (*end == ']' && *(end + 1) == ']' && *(end + 2) == '>') {
+		    end = end + 2;
+		    xmlOutputBufferWrite(buf, 9, "<![CDATA[");
+		    xmlOutputBufferWrite(buf, end - start, (const char *)start);
+		    xmlOutputBufferWrite(buf, 3, "]]>");
+		    start = end;
+		}
+		end++;
 	    }
-	    end++;
-	}
-	if (start != end) {
-	    xmlOutputBufferWrite(buf, 9, "<![CDATA[");
-	    xmlOutputBufferWriteString(buf, (const char *)start);
-	    xmlOutputBufferWrite(buf, 3, "]]>");
+	    if (start != end) {
+		xmlOutputBufferWrite(buf, 9, "<![CDATA[");
+		xmlOutputBufferWriteString(buf, (const char *)start);
+		xmlOutputBufferWrite(buf, 3, "]]>");
+	    }
 	}
 	return;
     }
@@ -2004,6 +2136,7 @@
     ctxt.format = format;
     ctxt.encoding = (const xmlChar *) encoding;
     xmlSaveCtxtInit(&ctxt);
+    ctxt.options |= XML_SAVE_AS_XML;
 
 #ifdef LIBXML_HTML_ENABLED
     dtd = xmlGetIntSubset(doc);
@@ -2089,6 +2222,7 @@
     ctxt.format = format;
     ctxt.encoding = (const xmlChar *) txt_encoding;
     xmlSaveCtxtInit(&ctxt);
+    ctxt.options |= XML_SAVE_AS_XML;
     xmlDocContentDumpOutput(&ctxt, out_doc);
     xmlOutputBufferFlush(out_buff);
     if (out_buff->conv != NULL) {
@@ -2207,6 +2341,7 @@
     ctxt.format = format;
     ctxt.encoding = (const xmlChar *) encoding;
     xmlSaveCtxtInit(&ctxt);
+    ctxt.options |= XML_SAVE_AS_XML;
     xmlDocContentDumpOutput(&ctxt, cur);
 
     ret = xmlOutputBufferClose(buf);
@@ -2256,6 +2391,7 @@
     ctxt.format = 0;
     ctxt.encoding = (const xmlChar *) encoding;
     xmlSaveCtxtInit(&ctxt);
+    ctxt.options |= XML_SAVE_AS_XML;
     xmlDocContentDumpOutput(&ctxt, cur);
     ret = xmlOutputBufferClose(buf);
     return(ret);
@@ -2295,6 +2431,7 @@
     ctxt.format = format;
     ctxt.encoding = (const xmlChar *) encoding;
     xmlSaveCtxtInit(&ctxt);
+    ctxt.options |= XML_SAVE_AS_XML;
     xmlDocContentDumpOutput(&ctxt, cur);
     ret = xmlOutputBufferClose(buf);
     return (ret);
@@ -2349,6 +2486,7 @@
     ctxt.format = format;
     ctxt.encoding = (const xmlChar *) encoding;
     xmlSaveCtxtInit(&ctxt);
+    ctxt.options |= XML_SAVE_AS_XML;
 
     xmlDocContentDumpOutput(&ctxt, cur);
 
diff --git a/xmlschemas.c b/xmlschemas.c
index f6b86dd..c90b171 100644
--- a/xmlschemas.c
+++ b/xmlschemas.c
@@ -90,7 +90,7 @@
  #ifndef DEBUG_IDC_NODE_TABLE
   #define DEBUG_IDC_NODE_TABLE
  #endif
-#endif   
+#endif
 
 /* #define ENABLE_PARTICLE_RESTRICTION 1 */
 
@@ -374,7 +374,7 @@
 #define XML_SCHEMA_SCHEMA_REDEFINE 3
 
 /**
- * xmlSchemaSchemaRelation: 
+ * xmlSchemaSchemaRelation:
  *
  * Used to create a graph of schema relationships.
  */
@@ -402,12 +402,12 @@
     int parsed;
     int imported;
     int preserveDoc;
-    xmlSchemaItemListPtr globals; /* Global components. */ 
+    xmlSchemaItemListPtr globals; /* Global components. */
     xmlSchemaItemListPtr locals; /* Local components. */
 };
 
 /**
- * xmlSchemaImport: 
+ * xmlSchemaImport:
  * (extends xmlSchemaBucket)
  *
  * Reflects a schema. Holds some information
@@ -422,9 +422,9 @@
     const xmlChar *schemaLocation; /* The URI of the schema document. */
     /* For chameleon includes, @origTargetNamespace will be NULL */
     const xmlChar *origTargetNamespace;
-    /* 
+    /*
     * For chameleon includes, @targetNamespace will be the
-    * targetNamespace of the including schema. 
+    * targetNamespace of the including schema.
     */
     const xmlChar *targetNamespace;
     xmlDocPtr doc; /* The schema node-tree. */
@@ -457,7 +457,7 @@
     int parsed;
     int imported;
     int preserveDoc;
-    xmlSchemaItemListPtr globals; /* Global components. */ 
+    xmlSchemaItemListPtr globals; /* Global components. */
     xmlSchemaItemListPtr locals; /* Local components. */
 
     /* The owning main or import schema bucket. */
@@ -517,7 +517,7 @@
     xmlSchemaTypeType type;
     xmlSchemaAnnotPtr annot;
     xmlSchemaAttributeUsePtr next; /* The next attr. use. */
-    /* 
+    /*
     * The attr. decl. OR a QName-ref. to an attr. decl. OR
     * a QName-ref. to an attribute group definition.
     */
@@ -573,7 +573,7 @@
     xmlDictPtr dict;
     xmlSchemaItemListPtr buckets; /* List of schema buckets. */
     /* xmlSchemaItemListPtr relations; */ /* List of schema relations. */
-    xmlSchemaBucketPtr bucket; /* The current schema bucket */    
+    xmlSchemaBucketPtr bucket; /* The current schema bucket */
     xmlSchemaItemListPtr pending; /* All Components of all schemas that
                                      need to be fixed. */
     xmlHashTablePtr substGroups;
@@ -629,7 +629,7 @@
     xmlSchemaBucketPtr redefined; /* The schema to be redefined. */
 
     xmlSchemaRedefPtr redef; /* Used for redefinitions. */
-    int redefCounter; /* Used for redefinitions. */ 
+    int redefCounter; /* Used for redefinitions. */
     xmlSchemaItemListPtr attrProhibs;
 };
 
@@ -783,7 +783,7 @@
     xmlNodePtr node;
     xmlSchemaPSVIIDCKeyPtr *keys;
     int nodeLine;
-    int nodeQNameID;    
+    int nodeQNameID;
 
 };
 
@@ -879,7 +879,7 @@
 struct _xmlSchemaNodeInfo {
     int nodeType;
     xmlNodePtr node;
-    int nodeLine;    
+    int nodeLine;
     const xmlChar *localName;
     const xmlChar *nsName;
     const xmlChar *value;
@@ -901,7 +901,7 @@
 
     const xmlChar **nsBindings; /* Namespace bindings on this element */
     int nbNsBindings;
-    int sizeNsBindings;    
+    int sizeNsBindings;
 
     int hasKeyrefs;
     int appliedXPath; /* Indicates that an XPath has been applied. */
@@ -938,7 +938,7 @@
 struct _xmlSchemaAttrInfo {
     int nodeType;
     xmlNodePtr node;
-    int nodeLine;    
+    int nodeLine;
     const xmlChar *localName;
     const xmlChar *nsName;
     const xmlChar *value;
@@ -1172,7 +1172,7 @@
 	    if (WXS_IS_COMPLEX(WXS_TYPE_CAST item))
 		return(BAD_CAST "complex type definition");
 	    else
-		return(BAD_CAST "simple type definition");	
+		return(BAD_CAST "simple type definition");
 	default:
 	    return(xmlSchemaItemTypeToStr(item->type));
     }
@@ -1300,11 +1300,11 @@
 	*buf = xmlStrcat(*buf, localName);
     } else {
 	*buf = xmlStrcat(*buf, BAD_CAST "(NULL)");
-    }    
+    }
     return ((const xmlChar *) *buf);
 }
 
-static const xmlChar*   
+static const xmlChar*
 xmlSchemaFormatQNameNs(xmlChar **buf, xmlNsPtr ns, const xmlChar *localName)
 {
     if (ns != NULL)
@@ -1480,16 +1480,16 @@
     int list;
     xmlSchemaValType valType;
     const xmlChar *value, *value2 = NULL;
-    
+
 
     if ((retValue == NULL) || (val == NULL))
 	return (-1);
     list = xmlSchemaValueGetNext(val) ? 1 : 0;
     *retValue = NULL;
     do {
-	value = NULL;	
-	valType = xmlSchemaGetValType(val);    
-	switch (valType) {	    
+	value = NULL;
+	valType = xmlSchemaGetValType(val);
+	switch (valType) {
 	    case XML_SCHEMAS_STRING:
 	    case XML_SCHEMAS_NORMSTRING:
 	    case XML_SCHEMAS_ANYSIMPLETYPE:
@@ -1502,7 +1502,7 @@
 		    if (value2 != NULL)
 			value = value2;
 		}
-		break;	   
+		break;
 	    default:
 		if (xmlSchemaGetCanonValue(val, &value2) == -1) {
 		    if (value2 != NULL)
@@ -1540,29 +1540,29 @@
  * @buf: the string buffer
  * @itemDes: the designation of the item
  * @itemName: the name of the item
- * @item: the item as an object 
+ * @item: the item as an object
  * @itemNode: the node of the item
  * @local: the local name
  * @parsing: if the function is used during the parse
  *
  * Returns a representation of the given item used
- * for error reports. 
+ * for error reports.
  *
- * The following order is used to build the resulting 
+ * The following order is used to build the resulting
  * designation if the arguments are not NULL:
  * 1a. If itemDes not NULL -> itemDes
  * 1b. If (itemDes not NULL) and (itemName not NULL)
  *     -> itemDes + itemName
  * 2. If the preceding was NULL and (item not NULL) -> item
  * 3. If the preceding was NULL and (itemNode not NULL) -> itemNode
- * 
+ *
  * If the itemNode is an attribute node, the name of the attribute
  * will be appended to the result.
  *
  * Returns the formatted string and sets @buf to the resulting value.
- */  
-static xmlChar*   
-xmlSchemaFormatItemForReport(xmlChar **buf,		     
+ */
+static xmlChar*
+xmlSchemaFormatItemForReport(xmlChar **buf,
 		     const xmlChar *itemDes,
 		     xmlSchemaBasicItemPtr item,
 		     xmlNodePtr itemNode)
@@ -1574,9 +1574,9 @@
 	xmlFree(*buf);
 	*buf = NULL;
     }
-            
+
     if (itemDes != NULL) {
-	*buf = xmlStrdup(itemDes);	
+	*buf = xmlStrdup(itemDes);
     } else if (item != NULL) {
 	switch (item->type) {
 	case XML_SCHEMA_TYPE_BASIC: {
@@ -1634,7 +1634,7 @@
 	    break;
 	case XML_SCHEMA_TYPE_ATTRIBUTE_USE: {
 		xmlSchemaAttributeUsePtr ause;
-	    
+
 		ause = WXS_ATTR_USE_CAST item;
 		*buf = xmlStrdup(BAD_CAST "attribute use ");
 		if (WXS_ATTRUSE_DECL(ause) != NULL) {
@@ -1650,7 +1650,7 @@
 	    break;
 	case XML_SCHEMA_TYPE_ATTRIBUTE: {
 		xmlSchemaAttributePtr attr;
-	    
+
 		attr = (xmlSchemaAttributePtr) item;
 		*buf = xmlStrdup(BAD_CAST "attribute decl.");
 		*buf = xmlStrcat(*buf, BAD_CAST " '");
@@ -1666,7 +1666,7 @@
 	case XML_SCHEMA_TYPE_ELEMENT: {
 		xmlSchemaElementPtr elem;
 
-		elem = (xmlSchemaElementPtr) item;	    
+		elem = (xmlSchemaElementPtr) item;
 		*buf = xmlStrdup(BAD_CAST "element decl.");
 		*buf = xmlStrcat(*buf, BAD_CAST " '");
 		*buf = xmlStrcat(*buf, xmlSchemaFormatQName(&str,
@@ -1676,7 +1676,7 @@
 	    break;
 	case XML_SCHEMA_TYPE_IDC_UNIQUE:
 	case XML_SCHEMA_TYPE_IDC_KEY:
-	case XML_SCHEMA_TYPE_IDC_KEYREF:		
+	case XML_SCHEMA_TYPE_IDC_KEYREF:
 	    if (item->type == XML_SCHEMA_TYPE_IDC_UNIQUE)
 		*buf = xmlStrdup(BAD_CAST "unique '");
 	    else if (item->type == XML_SCHEMA_TYPE_IDC_KEY)
@@ -1732,7 +1732,7 @@
 	default:
 	    named = 0;
 	}
-    } else 
+    } else
 	named = 0;
 
     if ((named == 0) && (itemNode != NULL)) {
@@ -1740,7 +1740,7 @@
 
 	if (itemNode->type == XML_ATTRIBUTE_NODE)
 	    elem = itemNode->parent;
-	else 
+	else
 	    elem = itemNode;
 	*buf = xmlStrdup(BAD_CAST "Element '");
 	if (elem->ns != NULL) {
@@ -1750,7 +1750,7 @@
 	} else
 	    *buf = xmlStrcat(*buf, elem->name);
 	*buf = xmlStrcat(*buf, BAD_CAST "'");
-	
+
     }
     if ((itemNode != NULL) && (itemNode->type == XML_ATTRIBUTE_NODE)) {
 	*buf = xmlStrcat(*buf, BAD_CAST ", attribute '");
@@ -1763,7 +1763,7 @@
 	*buf = xmlStrcat(*buf, BAD_CAST "'");
     }
     FREE_AND_NULL(str)
-    
+
     return (*buf);
 }
 
@@ -1786,13 +1786,13 @@
     int res, found = 0;
 
     if (*buf != NULL)
-	xmlFree(*buf);    
+	xmlFree(*buf);
     *buf = NULL;
 
     do {
 	/*
 	* Use the whitespace type of the base type.
-	*/	
+	*/
 	ws = xmlSchemaGetWhiteSpaceFacetValue(type->baseType);
 	for (facet = type->facets; facet != NULL; facet = facet->next) {
 	    if (facet->type != XML_SCHEMA_FACET_ENUMERATION)
@@ -1881,7 +1881,7 @@
  * @msg: the error message
  * @str1: extra data
  * @str2: extra data
- * 
+ *
  * Handle a parser error
  */
 static void
@@ -1914,7 +1914,7 @@
  * @msg: the error message
  * @str1: extra data
  * @str2: extra data
- * 
+ *
  * Handle a parser error
  */
 static void
@@ -1933,7 +1933,7 @@
  * xmlSchemaPErrExt:
  * @ctxt: the parsing context
  * @node: the context node
- * @error: the error code 
+ * @error: the error code
  * @strData1: extra data
  * @strData2: extra data
  * @strData3: extra data
@@ -1943,13 +1943,13 @@
  * @str3:  extra parameter for the message display
  * @str4:  extra parameter for the message display
  * @str5:  extra parameter for the message display
- * 
+ *
  * Handle a parser error
  */
 static void
 xmlSchemaPErrExt(xmlSchemaParserCtxtPtr ctxt, xmlNodePtr node, int error,
-		const xmlChar * strData1, const xmlChar * strData2, 
-		const xmlChar * strData3, const char *msg, const xmlChar * str1, 
+		const xmlChar * strData1, const xmlChar * strData2,
+		const xmlChar * strData3, const char *msg, const xmlChar * str1,
 		const xmlChar * str2, const xmlChar * str3, const xmlChar * str4,
 		const xmlChar * str5)
 {
@@ -1967,8 +1967,8 @@
     }
     __xmlRaiseError(schannel, channel, data, ctxt, node, XML_FROM_SCHEMASP,
                     error, XML_ERR_ERROR, NULL, 0,
-                    (const char *) strData1, (const char *) strData2, 
-		    (const char *) strData3, 0, 0, msg, str1, str2, 
+                    (const char *) strData1, (const char *) strData2,
+		    (const char *) strData3, 0, 0, msg, str1, str2,
 		    str3, str4, str5);
 }
 
@@ -2016,7 +2016,7 @@
  * @str1: extra data
  * @str2: extra data
  * @str3: extra data
- * 
+ *
  * Handle a validation error
  */
 static void
@@ -2028,8 +2028,8 @@
 {
     xmlStructuredErrorFunc schannel = NULL;
     xmlGenericErrorFunc channel = NULL;
-    void *data = NULL;    
-    
+    void *data = NULL;
+
     if (ctxt != NULL) {
 	if (ctxt->type == XML_SCHEMA_CTXT_VALIDATOR) {
 	    xmlSchemaValidCtxtPtr vctxt = (xmlSchemaValidCtxtPtr) ctxt;
@@ -2037,7 +2037,7 @@
 	    if (errorLevel != XML_ERR_WARNING) {
 		vctxt->nberrors++;
 		vctxt->err = error;
-		channel = vctxt->error;		
+		channel = vctxt->error;
 	    } else {
 		channel = vctxt->warning;
 	    }
@@ -2077,7 +2077,7 @@
 		else if ((vctxt->parserCtxt != NULL) &&
 		    (vctxt->parserCtxt->input != NULL))
 		    file = vctxt->parserCtxt->input->filename;
-	    }	       
+	    }
 	    __xmlRaiseError(schannel, channel, data, ctxt,
 		node, XML_FROM_SCHEMASV,
 		error, errorLevel, file, line,
@@ -2089,7 +2089,7 @@
 	    if (errorLevel != XML_ERR_WARNING) {
 		pctxt->nberrors++;
 		pctxt->err = error;
-		channel = pctxt->error;		
+		channel = pctxt->error;
 	    } else {
 		channel = pctxt->warning;
 	    }
@@ -2115,11 +2115,11 @@
  * @str1: extra data
  * @str2: extra data
  * @str3: extra data
- * 
+ *
  * Handle a validation error
  */
 static void
-xmlSchemaErr3(xmlSchemaAbstractCtxtPtr actxt,  
+xmlSchemaErr3(xmlSchemaAbstractCtxtPtr actxt,
 	      int error, xmlNodePtr node, const char *msg,
 	      const xmlChar *str1, const xmlChar *str2, const xmlChar *str3)
 {
@@ -2128,7 +2128,7 @@
 }
 
 static void
-xmlSchemaErr4(xmlSchemaAbstractCtxtPtr actxt,  
+xmlSchemaErr4(xmlSchemaAbstractCtxtPtr actxt,
 	      int error, xmlNodePtr node, const char *msg,
 	      const xmlChar *str1, const xmlChar *str2,
 	      const xmlChar *str3, const xmlChar *str4)
@@ -2157,7 +2157,7 @@
 	(node->type != XML_ELEMENT_NODE) &&
 	(node->type != XML_ATTRIBUTE_NODE))
     {
-	/* 
+	/*
 	* Don't try to format other nodes than element and
 	* attribute nodes.
 	* Play save and return an empty string.
@@ -2171,7 +2171,7 @@
 	*/
 	if (node->type == XML_ATTRIBUTE_NODE) {
 	    xmlNodePtr elem = node->parent;
-	    
+
 	    *msg = xmlStrdup(BAD_CAST "Element '");
 	    if (elem->ns != NULL)
 		*msg = xmlStrcat(*msg, xmlSchemaFormatQName(&str,
@@ -2181,7 +2181,7 @@
 		    NULL, elem->name));
 	    FREE_AND_NULL(str);
 	    *msg = xmlStrcat(*msg, BAD_CAST "', ");
-	    *msg = xmlStrcat(*msg, BAD_CAST "attribute '");	    
+	    *msg = xmlStrcat(*msg, BAD_CAST "attribute '");
 	} else {
 	    *msg = xmlStrdup(BAD_CAST "Element '");
 	}
@@ -2197,7 +2197,7 @@
 	xmlSchemaValidCtxtPtr vctxt = (xmlSchemaValidCtxtPtr) actxt;
 	/*
 	* Work on node infos.
-	*/	
+	*/
 	if (vctxt->inode->nodeType == XML_ATTRIBUTE_NODE) {
 	    xmlSchemaNodeInfoPtr ielem =
 		vctxt->elemInfos[vctxt->depth];
@@ -2207,7 +2207,7 @@
 		ielem->nsName, ielem->localName));
 	    FREE_AND_NULL(str);
 	    *msg = xmlStrcat(*msg, BAD_CAST "', ");
-	    *msg = xmlStrcat(*msg, BAD_CAST "attribute '");	    
+	    *msg = xmlStrcat(*msg, BAD_CAST "attribute '");
 	} else {
 	    *msg = xmlStrdup(BAD_CAST "Element '");
 	}
@@ -2216,7 +2216,7 @@
 	FREE_AND_NULL(str);
 	*msg = xmlStrcat(*msg, BAD_CAST "': ");
     } else if (actxt->type == XML_SCHEMA_CTXT_PARSER) {
-	/* 
+	/*
 	* Hmm, no node while parsing?
 	* Return an empty string, in case NULL will break something.
 	*/
@@ -2254,7 +2254,7 @@
         return;
     msg = xmlStrdup(BAD_CAST "Internal error: ");
     msg = xmlStrcat(msg, BAD_CAST funcName);
-    msg = xmlStrcat(msg, BAD_CAST ", ");    
+    msg = xmlStrcat(msg, BAD_CAST ", ");
     msg = xmlStrcat(msg, BAD_CAST message);
     msg = xmlStrcat(msg, BAD_CAST ".\n");
 
@@ -2262,7 +2262,7 @@
 	xmlSchemaErr(actxt, XML_SCHEMAV_INTERNAL, NULL,
 	    (const char *) msg, str1, str2);
 
-    else if (actxt->type == XML_SCHEMA_CTXT_PARSER)	
+    else if (actxt->type == XML_SCHEMA_CTXT_PARSER)
 	xmlSchemaErr(actxt, XML_SCHEMAP_INTERNAL, NULL,
 	    (const char *) msg, str1, str2);
 
@@ -2309,7 +2309,7 @@
     } else
 	xmlSchemaFormatNodeForError(&msg, actxt, node);
     msg = xmlStrcat(msg, (const xmlChar *) message);
-    msg = xmlStrcat(msg, BAD_CAST ".\n");   
+    msg = xmlStrcat(msg, BAD_CAST ".\n");
     xmlSchemaErr4(actxt, error, node,
 	(const char *) msg, str1, str2, str3, str4);
     FREE_AND_NULL(msg)
@@ -2325,7 +2325,7 @@
 		   const xmlChar *str2)
 {
     xmlSchemaCustomErr4(actxt, error, node, item,
-	message, str1, str2, NULL, NULL);    
+	message, str1, str2, NULL, NULL);
 }
 
 
@@ -2344,8 +2344,8 @@
 
     xmlSchemaFormatNodeForError(&msg, actxt, node);
     msg = xmlStrcat(msg, (const xmlChar *) message);
-    msg = xmlStrcat(msg, BAD_CAST ".\n"); 
-    
+    msg = xmlStrcat(msg, BAD_CAST ".\n");
+
     /* URGENT TODO: Set the error code to something sane. */
     xmlSchemaErr4Line(actxt, XML_ERR_WARNING, error, node, 0,
 	(const char *) msg, str1, str2, str3, NULL);
@@ -2365,15 +2365,15 @@
 		   const xmlChar *str2)
 {
     xmlChar *msg = NULL, *qname = NULL;
-    
-    msg = xmlStrdup(BAD_CAST "Element '%s': ");        
+
+    msg = xmlStrdup(BAD_CAST "Element '%s': ");
     msg = xmlStrcat(msg, (const xmlChar *) message);
     msg = xmlStrcat(msg, BAD_CAST ".\n");
     xmlSchemaErr4Line(ACTXT_CAST vctxt, XML_ERR_ERROR,
 	error, NULL, idcNode->nodeLine, (const char *) msg,
 	xmlSchemaFormatQName(&qname,
 	    vctxt->nodeQNames->items[idcNode->nodeQNameID +1],
-	    vctxt->nodeQNames->items[idcNode->nodeQNameID]), 
+	    vctxt->nodeQNames->items[idcNode->nodeQNameID]),
 	str1, str2, NULL);
     FREE_AND_NULL(qname);
     FREE_AND_NULL(msg);
@@ -2456,7 +2456,7 @@
 	if (type->builtInType != 0) {
 	    msg = xmlStrcat(msg, BAD_CAST "xs:");
 	    msg = xmlStrcat(msg, type->name);
-	} else 
+	} else
 	    msg = xmlStrcat(msg,
 		xmlSchemaFormatQName(&str,
 		    type->targetNamespace, type->name));
@@ -2494,12 +2494,12 @@
 			xmlNodePtr node)
 {
     xmlChar *msg = NULL, *str = NULL;
-    
+
     xmlSchemaFormatNodeForError(&msg, actxt, node);
     msg = xmlStrcat(msg, BAD_CAST "The attribute '%s' is not allowed.\n");
     xmlSchemaErr(actxt, error, node, (const char *) msg,
 	xmlSchemaFormatErrorNodeQName(&str, (xmlSchemaNodeInfoPtr) ni, node),
-	NULL);        
+	NULL);
     FREE_AND_NULL(str)
     FREE_AND_NULL(msg)
 }
@@ -2518,7 +2518,7 @@
     xmlChar *localName, *nsName;
     const xmlChar *cur, *end;
     int i;
-    
+
     xmlSchemaFormatNodeForError(&msg, actxt, node);
     msg = xmlStrcat(msg, (const xmlChar *) message);
     msg = xmlStrcat(msg, BAD_CAST ".");
@@ -2533,7 +2533,7 @@
 	} else
 	    str = xmlStrdup(BAD_CAST " Expected is ( ");
 	nsName = NULL;
-    	    
+
 	for (i = 0; i < nbval + nbneg; i++) {
 	    cur = values[i];
 	    if (cur == NULL)
@@ -2547,7 +2547,7 @@
 	    * Get the local name.
 	    */
 	    localName = NULL;
-	    
+
 	    end = cur;
 	    if (*end == '*') {
 		localName = xmlStrdup(BAD_CAST "*");
@@ -2556,8 +2556,8 @@
 		while ((*end != 0) && (*end != '|'))
 		    end++;
 		localName = xmlStrncat(localName, BAD_CAST cur, end - cur);
-	    }		
-	    if (*end != 0) {		    
+	    }
+	    if (*end != 0) {
 		end++;
 		/*
 		* Skip "*|*" if they come with negated expressions, since
@@ -2573,12 +2573,12 @@
 		    } else {
 			while (*end != 0)
 			    end++;
-			
+
 			if (i >= nbval)
 			    nsName = xmlStrdup(BAD_CAST "{##other:");
 			else
 			    nsName = xmlStrdup(BAD_CAST "{");
-			
+
 			nsName = xmlStrncat(nsName, BAD_CAST cur, end - cur);
 			nsName = xmlStrcat(nsName, BAD_CAST "}");
 		    }
@@ -2588,13 +2588,13 @@
 		    FREE_AND_NULL(localName);
 		    continue;
 		}
-	    }	        
+	    }
 	    str = xmlStrcat(str, BAD_CAST localName);
 	    FREE_AND_NULL(localName);
-		
+
 	    if (i < nbval + nbneg -1)
 		str = xmlStrcat(str, BAD_CAST ", ");
-	}	
+	}
 	str = xmlStrcat(str, BAD_CAST " ).\n");
 	msg = xmlStrcat(msg, BAD_CAST str);
 	FREE_AND_NULL(str)
@@ -2626,8 +2626,8 @@
 	/*
 	* If enumerations are validated, one must not expect the
 	* facet to be given.
-	*/	
-    } else	
+	*/
+    } else
 	facetType = facet->type;
     msg = xmlStrcat(msg, BAD_CAST "[");
     msg = xmlStrcat(msg, BAD_CAST "facet '");
@@ -2655,31 +2655,31 @@
 	    snprintf(actLen, 24, "%lu", length);
 
 	    if (facetType == XML_SCHEMA_FACET_LENGTH)
-		msg = xmlStrcat(msg, 
-		BAD_CAST "this differs from the allowed length of '%s'.\n");     
+		msg = xmlStrcat(msg,
+		BAD_CAST "this differs from the allowed length of '%s'.\n");
 	    else if (facetType == XML_SCHEMA_FACET_MAXLENGTH)
-		msg = xmlStrcat(msg, 
+		msg = xmlStrcat(msg,
 		BAD_CAST "this exceeds the allowed maximum length of '%s'.\n");
 	    else if (facetType == XML_SCHEMA_FACET_MINLENGTH)
-		msg = xmlStrcat(msg, 
+		msg = xmlStrcat(msg,
 		BAD_CAST "this underruns the allowed minimum length of '%s'.\n");
-	    
+
 	    if (nodeType == XML_ATTRIBUTE_NODE)
 		xmlSchemaErr3(actxt, error, node, (const char *) msg,
 		    value, (const xmlChar *) actLen, (const xmlChar *) len);
-	    else 
+	    else
 		xmlSchemaErr(actxt, error, node, (const char *) msg,
 		    (const xmlChar *) actLen, (const xmlChar *) len);
-	
+
 	} else if (facetType == XML_SCHEMA_FACET_ENUMERATION) {
 	    msg = xmlStrcat(msg, BAD_CAST "The value '%s' is not an element "
 		"of the set {%s}.\n");
-	    xmlSchemaErr(actxt, error, node, (const char *) msg, value, 
+	    xmlSchemaErr(actxt, error, node, (const char *) msg, value,
 		xmlSchemaFormatFacetEnumSet(actxt, &str, type));
 	} else if (facetType == XML_SCHEMA_FACET_PATTERN) {
 	    msg = xmlStrcat(msg, BAD_CAST "The value '%s' is not accepted "
 		"by the pattern '%s'.\n");
-	    xmlSchemaErr(actxt, error, node, (const char *) msg, value, 
+	    xmlSchemaErr(actxt, error, node, (const char *) msg, value,
 		facet->value);
 	} else if (facetType == XML_SCHEMA_FACET_MININCLUSIVE) {
 	    msg = xmlStrcat(msg, BAD_CAST "The value '%s' is less than the "
@@ -2711,10 +2711,10 @@
 		"digits than are allowed ('%s').\n");
 	    xmlSchemaErr(actxt, error, node, (const char*) msg, value,
 		facet->value);
-	} else if (nodeType == XML_ATTRIBUTE_NODE) {		
+	} else if (nodeType == XML_ATTRIBUTE_NODE) {
 	    msg = xmlStrcat(msg, BAD_CAST "The value '%s' is not facet-valid.\n");
-	    xmlSchemaErr(actxt, error, node, (const char *) msg, value, NULL);	
-	} else {	    
+	    xmlSchemaErr(actxt, error, node, (const char *) msg, value, NULL);
+	} else {
 	    msg = xmlStrcat(msg, BAD_CAST "The value is not facet-valid.\n");
 	    xmlSchemaErr(actxt, error, node, (const char *) msg, NULL, NULL);
 	}
@@ -2722,7 +2722,7 @@
 	msg = xmlStrcat(msg, (const xmlChar *) message);
 	msg = xmlStrcat(msg, BAD_CAST ".\n");
 	xmlSchemaErr(actxt, error, node, (const char *) msg, str1, str2);
-    }        
+    }
     FREE_AND_NULL(str)
     xmlFree(msg);
 }
@@ -2967,9 +2967,9 @@
 		    const xmlChar *str3,const xmlChar *str4)
 {
     xmlChar *str = NULL, *msg = NULL;
-    
+
     xmlSchemaFormatItemForReport(&msg, NULL, ownerItem, NULL);
-    msg = xmlStrcat(msg, BAD_CAST ", ");    
+    msg = xmlStrcat(msg, BAD_CAST ", ");
     msg = xmlStrcat(msg,
 	BAD_CAST xmlSchemaFormatItemForReport(&str, NULL,
 	WXS_BASIC_CAST attruse, NULL));
@@ -2977,7 +2977,7 @@
     msg = xmlStrcat(msg, BAD_CAST ": ");
     msg = xmlStrcat(msg, (const xmlChar *) message);
     msg = xmlStrcat(msg, BAD_CAST ".\n");
-    xmlSchemaErr4(ACTXT_CAST ctxt, error, node, 
+    xmlSchemaErr4(ACTXT_CAST ctxt, error, node,
 	(const char *) msg, str1, str2, str3, str4);
     xmlFree(msg);
 }
@@ -3071,7 +3071,7 @@
  * @error: the error code
  * @type: the type specifier
  * @ownerDes: the designation of the owner
- * @ownerItem: the schema object if existent 
+ * @ownerItem: the schema object if existent
  * @node: the validated node
  * @value: the validated value
  *
@@ -3079,7 +3079,7 @@
  * TODO: Should this report the value of an element as well?
  */
 static void
-xmlSchemaPSimpleTypeErr(xmlSchemaParserCtxtPtr ctxt, 
+xmlSchemaPSimpleTypeErr(xmlSchemaParserCtxtPtr ctxt,
 			xmlParserErrors error,
 			xmlSchemaBasicItemPtr ownerItem ATTRIBUTE_UNUSED,
 			xmlNodePtr node,
@@ -3091,37 +3091,37 @@
 			const xmlChar *str2)
 {
     xmlChar *msg = NULL;
-    
+
     xmlSchemaFormatNodeForError(&msg, ACTXT_CAST ctxt, node);
     if (message == NULL) {
 	/*
 	* Use default messages.
-	*/	
+	*/
 	if (type != NULL) {
 	    if (node->type == XML_ATTRIBUTE_NODE)
 		msg = xmlStrcat(msg, BAD_CAST "'%s' is not a valid value of ");
 	    else
 		msg = xmlStrcat(msg, BAD_CAST "The character content is not a "
-		"valid value of ");	
+		"valid value of ");
 	    if (! xmlSchemaIsGlobalItem(type))
 		msg = xmlStrcat(msg, BAD_CAST "the local ");
 	    else
 		msg = xmlStrcat(msg, BAD_CAST "the ");
-	    
+
 	    if (WXS_IS_ATOMIC(type))
 		msg = xmlStrcat(msg, BAD_CAST "atomic type");
 	    else if (WXS_IS_LIST(type))
 		msg = xmlStrcat(msg, BAD_CAST "list type");
 	    else if (WXS_IS_UNION(type))
 		msg = xmlStrcat(msg, BAD_CAST "union type");
-	    
+
 	    if (xmlSchemaIsGlobalItem(type)) {
 		xmlChar *str = NULL;
 		msg = xmlStrcat(msg, BAD_CAST " '");
 		if (type->builtInType != 0) {
 		    msg = xmlStrcat(msg, BAD_CAST "xs:");
 		    msg = xmlStrcat(msg, type->name);
-		} else 
+		} else
 		    msg = xmlStrcat(msg,
 			xmlSchemaFormatQName(&str,
 			    type->targetNamespace, type->name));
@@ -3134,7 +3134,7 @@
 	    else
 		msg = xmlStrcat(msg, BAD_CAST "The character content is not "
 		"valid.");
-	}	
+	}
 	if (expected) {
 	    msg = xmlStrcat(msg, BAD_CAST " Expected is '");
 	    msg = xmlStrcat(msg, BAD_CAST expected);
@@ -3151,7 +3151,7 @@
 	xmlSchemaPErrExt(ctxt, node, error, NULL, NULL, NULL,
 	     (const char*) msg, str1, str2, NULL, NULL, NULL);
     }
-    /* Cleanup. */    
+    /* Cleanup. */
     FREE_AND_NULL(msg)
 }
 
@@ -3372,7 +3372,7 @@
 
 static int
 xmlSchemaItemListInsert(xmlSchemaItemListPtr list, void *item, int idx)
-{    
+{
     if (list->items == NULL) {
 	list->items = (void **) xmlMalloc(
 	    20 * sizeof(void *));
@@ -3412,7 +3412,7 @@
 			    int initialSize,
 			    void *item,
 			    int idx)
-{    
+{
     if (list->items == NULL) {
 	if (initialSize <= 0)
 	    initialSize = 1;
@@ -3467,7 +3467,7 @@
 	list->sizeItems = 0;
     } else if (list->nbItems -1 == idx) {
 	list->nbItems--;
-    } else {	
+    } else {
 	for (i = idx; i < list->nbItems -1; i++)
 	    list->items[i] = list->items[i+1];
 	list->nbItems--;
@@ -3502,19 +3502,19 @@
     }
     if (bucket->locals != NULL) {
 	xmlSchemaComponentListFree(bucket->locals);
-	xmlSchemaItemListFree(bucket->locals);	
+	xmlSchemaItemListFree(bucket->locals);
     }
     if (bucket->relations != NULL) {
 	xmlSchemaSchemaRelationPtr prev, cur = bucket->relations;
 	do {
-	    prev = cur;	    
+	    prev = cur;
 	    cur = cur->next;
 	    xmlFree(prev);
 	} while (cur != NULL);
     }
     if ((! bucket->preserveDoc) && (bucket->doc != NULL)) {
 	xmlFreeDoc(bucket->doc);
-    } 
+    }
     if (bucket->type == XML_SCHEMA_SCHEMA_IMPORT) {
 	if (WXS_IMPBUCKET(bucket)->schema != NULL)
 	    xmlSchemaFree(WXS_IMPBUCKET(bucket)->schema);
@@ -3559,7 +3559,7 @@
 	xmlFree(ret);
 	return(NULL);
     }
-    /* 
+    /*
     * The following will assure that only the first bucket is marked as
     * XML_SCHEMA_SCHEMA_MAIN and it points to the *main* schema.
     * For each following import buckets an xmlSchema will be created.
@@ -3573,7 +3573,7 @@
 	    xmlSchemaBucketFree(ret);
 	    return(NULL);
 	}
-	/* Force the type to be XML_SCHEMA_SCHEMA_MAIN. */ 
+	/* Force the type to be XML_SCHEMA_SCHEMA_MAIN. */
 	ret->type = XML_SCHEMA_SCHEMA_MAIN;
 	/* Point to the *main* schema. */
 	WXS_CONSTRUCTOR(pctxt)->mainBucket = ret;
@@ -3583,12 +3583,12 @@
 	*/
 	mainSchema->targetNamespace = targetNamespace;
     } else {
-	if (type == XML_SCHEMA_SCHEMA_MAIN) {	    
+	if (type == XML_SCHEMA_SCHEMA_MAIN) {
 	    PERROR_INT("xmlSchemaBucketCreate",
 		"main bucket but it's not the first one");
 	    xmlSchemaBucketFree(ret);
 	    return(NULL);
-	} else if (type == XML_SCHEMA_SCHEMA_IMPORT) {	    
+	} else if (type == XML_SCHEMA_SCHEMA_IMPORT) {
 	    /*
 	    * Create a schema for imports and assign the
 	    * targetNamespace.
@@ -3600,7 +3600,7 @@
 	    }
 	    WXS_IMPBUCKET(ret)->schema->targetNamespace = targetNamespace;
 	}
-    }    
+    }
     if (WXS_IS_BUCKET_IMPMAIN(type)) {
 	int res;
 	/*
@@ -3643,11 +3643,11 @@
 	    if (mainSchema->includes == NULL) {
 		xmlSchemaBucketFree(ret);
 		return(NULL);
-	    }	    
+	    }
 	}
 	xmlSchemaItemListAdd(mainSchema->includes, ret);
     }
-    /* 
+    /*
     * Add to list of all buckets; this is used for lookup
     * during schema construction time only.
     */
@@ -4015,7 +4015,7 @@
 	for (i = 0; i < list->nbItems; i++) {
 	    item = items[i];
 	    if (item == NULL)
-		continue;	    
+		continue;
 	    switch (item->type) {
 		case XML_SCHEMA_TYPE_SIMPLE:
 		case XML_SCHEMA_TYPE_COMPLEX:
@@ -4122,7 +4122,7 @@
 	xmlSchemaItemListPtr list = (xmlSchemaItemListPtr) schema->includes;
 	int i;
 	for (i = 0; i < list->nbItems; i++) {
-	    xmlSchemaBucketFree((xmlSchemaBucketPtr) list->items[i]);	
+	    xmlSchemaBucketFree((xmlSchemaBucketPtr) list->items[i]);
 	}
 	xmlSchemaItemListFree(list);
     }
@@ -4330,7 +4330,7 @@
 /**
  * xmlSchemaAttrUsesDump:
  * @uses:  attribute uses list
- * @output:  the file output 
+ * @output:  the file output
  *
  * Dumps a list of attribute use components.
  */
@@ -4347,7 +4347,7 @@
     if ((uses == NULL) || (uses->nbItems == 0))
         return;
 
-    fprintf(output, "  attributes:\n");    
+    fprintf(output, "  attributes:\n");
     for (i = 0; i < uses->nbItems; i++) {
 	use = uses->items[i];
 	if (use->type == XML_SCHEMA_EXTRA_ATTR_USE_PROHIB) {
@@ -4533,7 +4533,7 @@
 	return;
     do {
 	fprintf(output, "IDC:   BINDING '%s' (%d)\n",
-	    xmlSchemaGetComponentQName(&str, 
+	    xmlSchemaGetComponentQName(&str,
 		bind->definition), bind->nbNodes);
 	FREE_AND_NULL(str)
 	for (i = 0; i < bind->nbNodes; i++) {
@@ -4634,7 +4634,7 @@
     xmlAttrPtr prop;
 
     if ((node == NULL) || (name == NULL))
-	return(NULL);    
+	return(NULL);
     prop = node->properties;
     while (prop != NULL) {
 	if ((prop->ns != NULL) &&
@@ -4729,12 +4729,12 @@
                  const xmlChar * nsName)
 {
     xmlSchemaElementPtr ret = NULL;
-    
+
     if ((name == NULL) || (schema == NULL))
         return(NULL);
     if (schema != NULL) {
 	WXS_FIND_GLOBAL_ITEM(elemDecl)
-    }   
+    }
 exit:
 #ifdef DEBUG
     if (ret == NULL) {
@@ -4765,9 +4765,9 @@
     xmlSchemaTypePtr ret = NULL;
 
     if (name == NULL)
-        return (NULL);    
+        return (NULL);
     /* First try the built-in types. */
-    if ((nsName != NULL) && xmlStrEqual(nsName, xmlSchemaNs)) {	
+    if ((nsName != NULL) && xmlStrEqual(nsName, xmlSchemaNs)) {
 	ret = xmlSchemaGetPredefinedType(name, nsName);
 	if (ret != NULL)
 	    goto exit;
@@ -4780,7 +4780,7 @@
     }
     if (schema != NULL) {
 	WXS_FIND_GLOBAL_ITEM(typeDecl)
-    } 
+    }
 exit:
 
 #ifdef DEBUG
@@ -4891,7 +4891,7 @@
 	WXS_FIND_GLOBAL_ITEM(groupDecl)
     }
 exit:
-    
+
 #ifdef DEBUG
     if (ret == NULL) {
         if (nsName == NULL)
@@ -5000,7 +5000,7 @@
 	str++;
 	len--;
     }
-    
+
     return (1);
 }
 
@@ -5061,7 +5061,7 @@
 		default:
 		    /* Should not be hit. */
 		    return(NULL);
-	    }		
+	    }
 	}
     }
 subschemas:
@@ -5209,7 +5209,7 @@
 * resolve references to the redefined components and to check constraints.
 */
 static xmlSchemaRedefPtr
-xmlSchemaAddRedef(xmlSchemaParserCtxtPtr pctxt,		  
+xmlSchemaAddRedef(xmlSchemaParserCtxtPtr pctxt,
 		  xmlSchemaBucketPtr targetBucket,
 		  void *item,
 		  const xmlChar *refName,
@@ -5272,7 +5272,7 @@
     ret->type = XML_SCHEMA_TYPE_ATTRIBUTEGROUP;
     ret->name = name;
     ret->targetNamespace = nsName;
-    ret->node = node;   
+    ret->node = node;
 
     /* TODO: Remove the flag. */
     ret->flags |= XML_SCHEMAS_ATTRGROUP_GLOBAL;
@@ -5282,7 +5282,7 @@
 	if (pctxt->redef == NULL) {
 	    xmlFree(ret);
 	    return(NULL);
-	}	    
+	}
 	pctxt->redefCounter = 0;
     }
     WXS_ADD_GLOBAL(pctxt, ret);
@@ -5371,13 +5371,13 @@
 	    if (ctxt->redef == NULL) {
 		xmlFree(ret);
 		return(NULL);
-	    }	    
+	    }
 	    ctxt->redefCounter = 0;
 	}
 	WXS_ADD_GLOBAL(ctxt, ret);
     } else
 	WXS_ADD_LOCAL(ctxt, ret);
-    WXS_ADD_PENDING(ctxt, ret);    
+    WXS_ADD_PENDING(ctxt, ret);
     return (ret);
 }
 
@@ -5509,7 +5509,7 @@
     ret->children = NULL;
 
     WXS_ADD_LOCAL(ctxt, ret);
-    /* 
+    /*
     * Note that addition to pending components will be done locally
     * to the specific parsing function, since the most particles
     * need not to be fixed up (i.e. the reference to be resolved).
@@ -5558,7 +5558,7 @@
 	if (ctxt->redef == NULL) {
 	    xmlFree(ret);
 	    return(NULL);
-	}	    
+	}
 	ctxt->redefCounter = 0;
     }
     WXS_ADD_GLOBAL(ctxt, ret);
@@ -5595,7 +5595,7 @@
                   const xmlChar *name, const xmlChar *nsName,
 		  int category, xmlNodePtr node)
 {
-    xmlSchemaIDCPtr ret = NULL;    
+    xmlSchemaIDCPtr ret = NULL;
 
     if ((ctxt == NULL) || (schema == NULL) || (name == NULL))
         return (NULL);
@@ -5611,8 +5611,8 @@
     ret->targetNamespace = nsName;
     ret->name = name;
     ret->type = category;
-    ret->node = node;        
-    
+    ret->node = node;
+
     WXS_ADD_GLOBAL(ctxt, ret);
     /*
     * Only keyrefs need to be fixup up.
@@ -5648,7 +5648,7 @@
     }
     memset(ret, 0, sizeof(xmlSchemaWildcard));
     ret->type = type;
-    ret->node = node;    
+    ret->node = node;
     WXS_ADD_LOCAL(ctxt, ret);
     return (ret);
 }
@@ -5704,7 +5704,7 @@
 static xmlSchemaSubstGroupPtr
 xmlSchemaSubstGroupGet(xmlSchemaParserCtxtPtr pctxt,
 		       xmlSchemaElementPtr head)
-{   
+{
     if (WXS_SUBST_GROUPS(pctxt) == NULL)
 	return(NULL);
     return(xmlHashLookup2(WXS_SUBST_GROUPS(pctxt),
@@ -6120,7 +6120,7 @@
     value = xmlNodeGetContent(node);
     /*
     * 3.2.2.1 Lexical representation
-    * An instance of a datatype that is defined as ·boolean·
+    * An instance of a datatype that is defined as �boolean�
     * can have the following legal literals {true, false, 1, 0}.
     */
     if (xmlStrEqual(BAD_CAST value, BAD_CAST "true"))
@@ -6168,7 +6168,7 @@
         return (def);
     /*
     * 3.2.2.1 Lexical representation
-    * An instance of a datatype that is defined as ·boolean·
+    * An instance of a datatype that is defined as �boolean�
     * can have the following legal literals {true, false, 1, 0}.
     */
     if (xmlStrEqual(val, BAD_CAST "true"))
@@ -6288,7 +6288,7 @@
 	    ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_2;
 	else
 	    ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_1;
-	xmlSchemaPSimpleTypeErr(pctxt, 
+	xmlSchemaPSimpleTypeErr(pctxt,
 	    ret, ownerItem, (xmlNodePtr) attr,
 	    type, NULL, value, NULL, NULL, NULL);
     }
@@ -6352,7 +6352,7 @@
  * number otherwise and -1 in case of an internal or API error.
  */
 static int
-xmlSchemaPValAttr(xmlSchemaParserCtxtPtr ctxt,		       
+xmlSchemaPValAttr(xmlSchemaParserCtxtPtr ctxt,
 		       xmlSchemaBasicItemPtr ownerItem,
 		       xmlNodePtr ownerElem,
 		       const char *name,
@@ -6442,7 +6442,7 @@
  * @type:  the hosting type where the attributes will be anchored
  *
  * Parses attribute uses and attribute declarations and
- * attribute group references. 
+ * attribute group references.
  */
 static int
 xmlSchemaParseLocalAttributes(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema,
@@ -7085,7 +7085,7 @@
 			     int parentType)
 {
     const xmlChar *attrValue, *name = NULL, *ns = NULL;
-    xmlSchemaAttributeUsePtr use = NULL;    
+    xmlSchemaAttributeUsePtr use = NULL;
     xmlNodePtr child = NULL;
     xmlAttrPtr attr;
     const xmlChar *tmpNs = NULL, *tmpName = NULL, *defValue = NULL;
@@ -7139,7 +7139,7 @@
 		    /*
 		    * Evaluate the target namespace
 		    */
-		    hasForm = 1;		    
+		    hasForm = 1;
 		    attrValue = xmlSchemaGetNodeContent(pctxt,
 			(xmlNodePtr) attr);
 		    if (xmlStrEqual(attrValue, BAD_CAST "qualified")) {
@@ -7210,7 +7210,7 @@
 
 attr_next:
 	attr = attr->next;
-    }        
+    }
     /*
     * 3.2.3 : 2
     * If default and use are both present, use must have
@@ -7236,7 +7236,7 @@
 
 	/* TODO: move XML_SCHEMAS_QUALIF_ATTR to the parser. */
 	if ((! hasForm) && (schema->flags & XML_SCHEMAS_QUALIF_ATTR))
-	    ns = pctxt->targetNamespace;		
+	    ns = pctxt->targetNamespace;
 	/*
 	* 3.2.6 Schema Component Constraint: xsi: Not Allowed
 	* TODO: Move this to the component layer.
@@ -7293,7 +7293,7 @@
 	use->attrDecl = attrDecl;
 	/*
 	* Value constraint.
-	*/	
+	*/
 	if (defValue != NULL) {
 	    attrDecl->defValue = defValue;
 	    if (defValueType == WXS_ATTR_DEF_VAL_FIXED)
@@ -7333,14 +7333,14 @@
 	    if (defValueType == WXS_ATTR_DEF_VAL_FIXED)
 		use->flags |= XML_SCHEMA_ATTR_USE_FIXED;
     }
-    
+
 check_children:
     /*
     * And now for the children...
     */
     child = node->children;
     if (occurs == XML_SCHEMAS_ATTR_USE_PROHIBITED) {
-	xmlSchemaAttributeUseProhibPtr prohib;	
+	xmlSchemaAttributeUseProhibPtr prohib;
 
 	if (IS_SCHEMA(child, "annotation")) {
 	    xmlSchemaParseAnnotation(pctxt, child, 0);
@@ -7355,7 +7355,7 @@
 	/*
 	* Check for pointlessness of attribute prohibitions.
 	*/
-	if (parentType == XML_SCHEMA_TYPE_ATTRIBUTEGROUP) {		
+	if (parentType == XML_SCHEMA_TYPE_ATTRIBUTEGROUP) {
 	    xmlSchemaCustomWarning(ACTXT_CAST pctxt,
 		XML_SCHEMAP_WARN_ATTR_POINTLESS_PROH,
 		node, NULL,
@@ -7373,7 +7373,7 @@
 	    return(NULL);
 	}
 	if (! isRef) {
-	    tmpName = name; 
+	    tmpName = name;
 	    tmpNs = ns;
 	}
 	/*
@@ -7381,7 +7381,7 @@
 	*/
 	if (uses) {
 	    int i;
-	    
+
 	    for (i = 0; i < uses->nbItems; i++) {
 		use = uses->items[i];
 		if ((use->type == XML_SCHEMA_EXTRA_ATTR_USE_PROHIB) &&
@@ -7389,16 +7389,16 @@
 		    (tmpNs == (WXS_ATTR_PROHIB_CAST use)->targetNamespace))
 		{
 		    xmlChar *str = NULL;
-		    
+
 		    xmlSchemaCustomWarning(ACTXT_CAST pctxt,
 			XML_SCHEMAP_WARN_ATTR_POINTLESS_PROH,
 			node, NULL,
 			"Skipping duplicate attribute use prohibition '%s'",
 			xmlSchemaFormatQName(&str, tmpNs, tmpName),
 			NULL, NULL);
-		    FREE_AND_NULL(str)			
+		    FREE_AND_NULL(str)
 		    return(NULL);
-		}	
+		}
 	    }
 	}
 	/*
@@ -7417,7 +7417,7 @@
 	    WXS_ADD_PENDING(pctxt, prohib);
 	}
 	return(WXS_BASIC_CAST prohib);
-    } else {        
+    } else {
 	if (IS_SCHEMA(child, "annotation")) {
 	    /*
 	    * TODO: Should this go into the attr decl?
@@ -7464,7 +7464,7 @@
 		NULL, node, child, NULL,
 		"(annotation?, simpleType?)");
 	}
-    }   
+    }
     return (WXS_BASIC_CAST use);
 }
 
@@ -7486,7 +7486,7 @@
      * 3.2.3 Constraints on XML Representations of Attribute Declarations
      */
     if ((pctxt == NULL) || (schema == NULL) || (node == NULL))
-        return (NULL);        
+        return (NULL);
     /*
     * 3.2.3 : 3.1
     * One of ref or name must be present, but not both
@@ -7532,7 +7532,7 @@
     if (ret == NULL)
 	return (NULL);
     ret->flags |= XML_SCHEMAS_ATTR_GLOBAL;
-	
+
     /*
     * Check for illegal attributes.
     */
@@ -7546,7 +7546,7 @@
 		(!xmlStrEqual(attr->name, BAD_CAST "type")))
 	    {
 		xmlSchemaPIllegalAttrErr(pctxt,
-		    XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr);		
+		    XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr);
 	    }
 	} else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) {
 	    xmlSchemaPIllegalAttrErr(pctxt,
@@ -7556,7 +7556,7 @@
     }
     xmlSchemaPValAttrQName(pctxt, schema, NULL,
 	node, "type", &ret->typeNs, &ret->typeName);
-    
+
     xmlSchemaPValAttrID(pctxt, node, BAD_CAST "id");
     /*
     * Attribute "fixed".
@@ -7641,12 +7641,12 @@
 	    XML_SCHEMAP_S4S_ATTR_MISSING,
 	    NULL, node, "ref", NULL);
 	return (NULL);
-    }	
+    }
     xmlSchemaPValAttrNodeQName(pctxt, schema,
 	NULL, attr, &refNs, &ref);
     if (xmlSchemaCheckReference(pctxt, schema, node, attr, refNs) != 0)
 	return(NULL);
-   
+
     /*
     * Check for illegal attributes.
     */
@@ -7698,13 +7698,13 @@
 	/*
 	* SPEC src-redefine:
 	* (7.1) "If it has an <attributeGroup> among its contents
-	* the ·actual value· of whose ref [attribute] is the same
-	* as the ·actual value· of its own name attribute plus
+	* the �actual value� of whose ref [attribute] is the same
+	* as the �actual value� of its own name attribute plus
 	* target namespace, then it must have exactly one such group."
 	*/
 	if (pctxt->redefCounter != 0) {
 	    xmlChar *str = NULL;
-	    
+
 	    xmlSchemaCustomErr(ACTXT_CAST pctxt,
 		XML_SCHEMAP_SRC_REDEFINE, node, NULL,
 		"The redefining attribute group definition "
@@ -7738,7 +7738,7 @@
 	ret->node = node;
 	/* Add to pending items, to be able to resolve the reference. */
 	WXS_ADD_PENDING(pctxt, ret);
-    }    
+    }
     return (ret);
 }
 
@@ -7785,7 +7785,7 @@
     ret = xmlSchemaAddAttributeGroupDefinition(pctxt, schema,
 	name, pctxt->targetNamespace, node);
     if (ret == NULL)
-	return (NULL);	
+	return (NULL);
     /*
     * Check for illegal attributes.
     */
@@ -8185,7 +8185,7 @@
  * Returns the parsed identity-constraint definition.
  */
 static xmlSchemaIDCSelectPtr
-xmlSchemaParseIDCSelectorAndField(xmlSchemaParserCtxtPtr ctxt,			  
+xmlSchemaParseIDCSelectorAndField(xmlSchemaParserCtxtPtr ctxt,
 			  xmlSchemaIDCPtr idc,
 			  xmlNodePtr node,
 			  int isField)
@@ -8848,7 +8848,7 @@
     type->flags |= XML_SCHEMAS_TYPE_VARIETY_UNION;
     /*
     * SPEC (Base type) (2) "If the <list> or <union> alternative is chosen,
-    * then the ·simple ur-type definition·."
+    * then the �simple ur-type definition�."
     */
     type->baseType = xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYSIMPLETYPE);
     /*
@@ -9016,7 +9016,7 @@
     type->flags |= XML_SCHEMAS_TYPE_VARIETY_LIST;
     /*
     * SPEC (Base type) (2) "If the <list> or <union> alternative is chosen,
-    * then the ·simple ur-type definition·."
+    * then the �simple ur-type definition�."
     */
     type->baseType = xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYSIMPLETYPE);
     /*
@@ -9161,9 +9161,9 @@
     }
     /*
     * TargetNamespace:
-    * SPEC "The ·actual value· of the targetNamespace [attribute]
+    * SPEC "The �actual value� of the targetNamespace [attribute]
     * of the <schema> ancestor element information item if present,
-    * otherwise ·absent·.
+    * otherwise �absent�.
     */
     if (topLevel == 0) {
 #ifdef ENABLE_NAMED_LOCALS
@@ -9195,7 +9195,7 @@
 	    if (attr->ns == NULL) {
 		if (!xmlStrEqual(attr->name, BAD_CAST "id")) {
 		    xmlSchemaPIllegalAttrErr(ctxt,
-			XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr); 
+			XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr);
 		}
 	    } else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) {
 		    xmlSchemaPIllegalAttrErr(ctxt,
@@ -9266,9 +9266,9 @@
     * And now for the children...
     */
     oldCtxtType = ctxt->ctxtType;
-    
+
     ctxt->ctxtType = type;
-    
+
     child = node->children;
     if (IS_SCHEMA(child, "annotation")) {
         type->annot = xmlSchemaParseAnnotation(ctxt, child, 1);
@@ -9278,10 +9278,10 @@
 	xmlSchemaPContentErr(ctxt, XML_SCHEMAP_S4S_ELEM_MISSING,
 	    NULL, node, child, NULL,
 	    "(annotation?, (restriction | list | union))");
-    } else if (IS_SCHEMA(child, "restriction")) {	
+    } else if (IS_SCHEMA(child, "restriction")) {
         xmlSchemaParseRestriction(ctxt, schema, child,
-	    XML_SCHEMA_TYPE_SIMPLE);	
-	hasRestriction = 1;	
+	    XML_SCHEMA_TYPE_SIMPLE);
+	hasRestriction = 1;
         child = child->next;
     } else if (IS_SCHEMA(child, "list")) {
         xmlSchemaParseList(ctxt, schema, child);
@@ -9298,8 +9298,8 @@
     /*
     * REDEFINE: SPEC src-redefine (5)
     * "Within the [children], each <simpleType> must have a
-    * <restriction> among its [children] ... the ·actual value· of whose
-    * base [attribute] must be the same as the ·actual value· of its own
+    * <restriction> among its [children] ... the �actual value� of whose
+    * base [attribute] must be the same as the �actual value� of its own
     * name attribute plus target namespace;"
     */
     if (topLevel && ctxt->isRedefine && (! hasRestriction)) {
@@ -9307,7 +9307,7 @@
 	    NULL, node, "This is a redefinition, thus the "
 	    "<simpleType> must have a <restriction> child", NULL);
     }
-    
+
     ctxt->ctxtType = oldCtxtType;
     return (type);
 }
@@ -9373,13 +9373,13 @@
     xmlSchemaPValAttrID(ctxt, node, BAD_CAST "id");
     item = xmlSchemaAddParticle(ctxt, node, min, max);
     if (item == NULL)
-	return (NULL);    
+	return (NULL);
     /*
     * Create a qname-reference and set as the term; it will be substituted
     * for the model group after the reference has been resolved.
     */
     item->children = (xmlSchemaTreeItemPtr)
-	xmlSchemaNewQNameRef(ctxt, XML_SCHEMA_TYPE_GROUP, ref, refNs);    
+	xmlSchemaNewQNameRef(ctxt, XML_SCHEMA_TYPE_GROUP, ref, refNs);
     xmlSchemaPCheckParticleCorrect_2(ctxt, item, node, min, max);
     /*
     * And now for the children...
@@ -9419,7 +9419,7 @@
  * Note that the contraint src-redefine (6.2) can't be applied until
  * references have been resolved. So we will do this at the
  * component fixup level.
- *    
+ *
  * *WARNING* this interface is highly subject to change
  *
  * Returns -1 in case of error, 0 if the declaration is improper and
@@ -9493,7 +9493,7 @@
 	child = child->next;
     }
 
-   
+
 
     if (child != NULL) {
 	xmlSchemaPContentErr(ctxt,
@@ -9631,7 +9631,7 @@
     attr = xmlSchemaGetPropNode(node, "version");
     if (attr != NULL) {
 	res = xmlSchemaPValAttrNode(ctxt, NULL, NULL, attr,
-	    xmlSchemaGetBuiltInType(XML_SCHEMAS_TOKEN), &val);    
+	    xmlSchemaGetBuiltInType(XML_SCHEMAS_TOKEN), &val);
 	HFAILURE;
     }
     */
@@ -9691,7 +9691,7 @@
     }
     attr = xmlSchemaGetPropNode(node, "blockDefault");
     if (attr != NULL) {
-	val = xmlSchemaGetNodeContent(ctxt, (xmlNodePtr) attr);	
+	val = xmlSchemaGetNodeContent(ctxt, (xmlNodePtr) attr);
 	res = xmlSchemaPValAttrBlockFinal(val, &(schema->flags), -1,
 	    XML_SCHEMAS_BLOCK_DEFAULT_EXTENSION,
 	    XML_SCHEMAS_BLOCK_DEFAULT_RESTRICTION,
@@ -9752,14 +9752,14 @@
 	    HFAILURE;
 	    HSTOP(ctxt);
 	    if (tmpOldErrs != ctxt->nberrors)
-		goto exit;	    
+		goto exit;
 	} else if (IS_SCHEMA(child, "include")) {
 	    tmpOldErrs = ctxt->nberrors;
 	    res = xmlSchemaParseInclude(ctxt, schema, child);
 	    HFAILURE;
 	    HSTOP(ctxt);
 	    if (tmpOldErrs != ctxt->nberrors)
-		goto exit;	    
+		goto exit;
 	} else if (IS_SCHEMA(child, "redefine")) {
 	    tmpOldErrs = ctxt->nberrors;
 	    res = xmlSchemaParseRedefine(ctxt, schema, child);
@@ -9884,7 +9884,7 @@
     xmlFree(con);
 }
 
-static xmlSchemaConstructionCtxtPtr 
+static xmlSchemaConstructionCtxtPtr
 xmlSchemaConstructionCtxtCreate(xmlDictPtr dict)
 {
     xmlSchemaConstructionCtxtPtr ret;
@@ -9954,10 +9954,10 @@
     xmlSchemaParserCtxtPtr ret;
 
     ret = xmlSchemaParserCtxtCreate();
-    if (ret == NULL)        
+    if (ret == NULL)
         return (NULL);
     ret->dict = dict;
-    xmlDictReference(dict);    
+    xmlDictReference(dict);
     if (URL != NULL)
 	ret->URL = xmlDictLookup(dict, (const xmlChar *) URL, -1);
     return (ret);
@@ -10082,8 +10082,8 @@
     xmlNodePtr node;
     int ret, oldErrs;
     xmlSchemaBucketPtr oldbucket = pctxt->constructor->bucket;
-    
-    /* 
+
+    /*
     * Save old values; reset the *main* schema.
     * URGENT TODO: This is not good; move the per-document information
     * to the parser. Get rid of passing the main schema to the
@@ -10093,9 +10093,9 @@
     oldDoc = schema->doc;
     if (schema->flags != 0)
 	xmlSchemaClearSchemaDefaults(schema);
-    schema->doc = bucket->doc;    
+    schema->doc = bucket->doc;
     pctxt->schema = schema;
-    /* 
+    /*
     * Keep the current target namespace on the parser *not* on the
     * main schema.
     */
@@ -10108,7 +10108,7 @@
 	* We are parsing the schema for schemas!
 	*/
 	pctxt->isS4S = 1;
-    }    
+    }
     /* Mark it as parsed, even if parsing fails. */
     bucket->parsed++;
     /* Compile the schema doc. */
@@ -10132,7 +10132,7 @@
 	ret = pctxt->err;
 	goto exit;
     }
-    
+
 exit:
     WXS_CONSTRUCTOR(pctxt)->bucket = oldbucket;
     /* Restore schema values. */
@@ -10165,7 +10165,7 @@
 	PERROR_INT("xmlSchemaParseNewDoc",
 	    "no constructor");
 	return(-1);
-    }    
+    }
     /* Create and init the temporary parser context. */
     newpctxt = xmlSchemaNewParserCtxtUseDict(
 	(const char *) bucket->schemaLocation, pctxt->dict);
@@ -10173,7 +10173,7 @@
 	return(-1);
     newpctxt->constructor = pctxt->constructor;
     /*
-    * TODO: Can we avoid that the parser knows about the main schema? 
+    * TODO: Can we avoid that the parser knows about the main schema?
     * It would be better if he knows about the current schema bucket
     * only.
     */
@@ -10183,16 +10183,16 @@
     xmlSchemaSetParserStructuredErrors(newpctxt, pctxt->serror,
 	pctxt->errCtxt);
     newpctxt->counter = pctxt->counter;
-    
+
 
     res = xmlSchemaParseNewDocWithContext(newpctxt, schema, bucket);
-    
+
     /* Channel back errors and cleanup the temporary parser context. */
     if (res != 0)
 	pctxt->err = res;
     pctxt->nberrors += newpctxt->nberrors;
     pctxt->counter = newpctxt->counter;
-    newpctxt->constructor = NULL;    
+    newpctxt->constructor = NULL;
     /* Free the parser context. */
     xmlSchemaFreeParserCtxt(newpctxt);
     return(res);
@@ -10217,11 +10217,11 @@
 static const xmlChar *
 xmlSchemaBuildAbsoluteURI(xmlDictPtr dict, const xmlChar* location,
 			  xmlNodePtr ctxtNode)
-{    
+{
     /*
     * Build an absolue location URI.
     */
-    if (location != NULL) {	
+    if (location != NULL) {
 	if (ctxtNode == NULL)
 	    return(location);
 	else {
@@ -10244,7 +10244,7 @@
     }
     return(NULL);
 }
-    
+
 
 
 /**
@@ -10267,8 +10267,8 @@
 		const char *schemaBuffer,
 		int schemaBufferLen,
 		xmlNodePtr invokingNode,
-		const xmlChar *sourceTargetNamespace,		
-		const xmlChar *importNamespace,	
+		const xmlChar *sourceTargetNamespace,
+		const xmlChar *importNamespace,
 		xmlSchemaBucketPtr *bucket)
 {
     const xmlChar *targetNamespace = NULL;
@@ -10279,7 +10279,7 @@
 
     if (bucket != NULL)
 	*bucket = NULL;
-    
+
     switch (type) {
 	case XML_SCHEMA_SCHEMA_IMPORT:
 	case XML_SCHEMA_SCHEMA_MAIN:
@@ -10291,23 +10291,23 @@
 	case XML_SCHEMA_SCHEMA_REDEFINE:
 	    err = XML_SCHEMAP_SRC_REDEFINE;
 	    break;
-    }    
-       
+    }
+
 
     /* Special handling for the main schema:
     * skip the location and relation logic and just parse the doc.
     * We need just a bucket to be returned in this case.
-    */    
+    */
     if ((type == XML_SCHEMA_SCHEMA_MAIN) || (! WXS_HAS_BUCKETS(pctxt)))
-	goto doc_load;	
+	goto doc_load;
 
-    /* Note that we expect the location to be an absulute URI. */ 
+    /* Note that we expect the location to be an absulute URI. */
     if (schemaLocation != NULL) {
 	bkt = xmlSchemaGetSchemaBucket(pctxt, schemaLocation);
 	if ((bkt != NULL) &&
 	    (pctxt->constructor->bucket == bkt)) {
 	    /* Report self-imports/inclusions/redefinitions. */
-	    
+
 	    xmlSchemaCustomErr(ACTXT_CAST pctxt, err,
 		invokingNode, NULL,
 		"The schema must not import/include/redefine itself",
@@ -10320,7 +10320,7 @@
     */
     relation = xmlSchemaSchemaRelationCreate();
     if (relation == NULL)
-	return(-1);    
+	return(-1);
     xmlSchemaSchemaRelationAddChild(pctxt->constructor->bucket,
 	relation);
     relation->type = type;
@@ -10329,7 +10329,7 @@
     * Save the namespace import information.
     */
     if (WXS_IS_BUCKET_IMPMAIN(type)) {
-	relation->importNamespace = importNamespace;	
+	relation->importNamespace = importNamespace;
 	if (schemaLocation == NULL) {
 	    /*
 	    * No location; this is just an import of the namespace.
@@ -10342,7 +10342,7 @@
     }
 
     /* Did we already fetch the doc? */
-    if (bkt != NULL) {		
+    if (bkt != NULL) {
 	/* TODO: The following nasty cases will produce an error. */
 	if ((WXS_IS_BUCKET_IMPMAIN(type)) && (! bkt->imported)) {
 	    /* We included/redefined and then try to import a schema. */
@@ -10364,14 +10364,14 @@
 		"redefined, since it was already imported",
 		schemaLocation, NULL);
 	    goto exit;
-	}	
+	}
     }
-    	
+
     if (WXS_IS_BUCKET_IMPMAIN(type)) {
 	/*
 	* Given that the schemaLocation [attribute] is only a hint, it is open
 	* to applications to ignore all but the first <import> for a given
-	* namespace, regardless of the ·actual value· of schemaLocation, but
+	* namespace, regardless of the �actual value� of schemaLocation, but
 	* such a strategy risks missing useful information when new
 	* schemaLocations are offered.
 	*
@@ -10387,7 +10387,7 @@
 	* 5 Attempt to resolve the namespace name to locate such a resource.
 	*
 	* NOTE: (3) and (5) are not supported.
-	*/	
+	*/
 	if (bkt != NULL) {
 	    relation->bucket = bkt;
 	    goto exit;
@@ -10395,7 +10395,7 @@
 	bkt = xmlSchemaGetSchemaBucketByTNS(pctxt,
 	    importNamespace, 1);
 
-	if (bkt != NULL) {	    
+	if (bkt != NULL) {
 	    relation->bucket = bkt;
 	    if (bkt->schemaLocation == NULL) {
 		/* First given location of the schema; load the doc. */
@@ -10421,19 +10421,19 @@
 		}
 		goto exit;
 	    }
-	}	
-	/* 
+	}
+	/*
 	* No bucket + first location: load the doc and create a
 	* bucket.
 	*/
     } else {
 	/* <include> and <redefine> */
 	if (bkt != NULL) {
-	    	    
+
 	    if ((bkt->origTargetNamespace == NULL) &&
 		(bkt->targetNamespace != sourceTargetNamespace)) {
 		xmlSchemaBucketPtr chamel;
-		
+
 		/*
 		* Chameleon include/redefine: skip loading only if it was
 		* aleady build for the targetNamespace of the including
@@ -10458,7 +10458,7 @@
 		    relation->bucket = chamel;
 		    goto exit;
 		}
-		/* 
+		/*
 		* We need to parse the chameleon again for a different
 		* targetNamespace.
 		* CHAMELEON TODO: Optimize this by only parsing the
@@ -10469,7 +10469,7 @@
 	    } else {
 		relation->bucket = bkt;
 		goto exit;
-	    }	    
+	    }
 	}
     }
     if ((bkt != NULL) && (bkt->doc != NULL)) {
@@ -10521,7 +10521,7 @@
 		NULL, NULL, SCHEMAS_PARSE_OPTIONS);
 	    schemaLocation = xmlStrdup(BAD_CAST "in_memory_buffer");
 	    if (doc != NULL)
-		doc->URL = schemaLocation;	    
+		doc->URL = schemaLocation;
 	}
 	/*
 	* For <import>:
@@ -10575,11 +10575,11 @@
     if (doc != NULL) {
 	xmlNodePtr docElem = NULL;
 
-	located = 1;	
+	located = 1;
 	docElem = xmlDocGetRootElement(doc);
 	if (docElem == NULL) {
 	    xmlSchemaCustomErr(ACTXT_CAST pctxt, XML_SCHEMAP_NOROOT,
-		invokingNode, NULL, 
+		invokingNode, NULL,
 		"The document '%s' has no document element",
 		schemaLocation, NULL);
 	    goto exit_error;
@@ -10598,14 +10598,14 @@
 		schemaLocation, NULL);
 	    goto exit_error;
 	}
-	/* 
+	/*
 	* Note that we don't apply a type check for the
 	* targetNamespace value here.
 	*/
 	targetNamespace = xmlSchemaGetProp(pctxt, docElem,
 	    "targetNamespace");
     }
-    
+
 /* after_doc_loading: */
     if ((bkt == NULL) && located) {
 	/* Only create a bucket if the schema was located. */
@@ -10632,14 +10632,14 @@
 	if (relation != NULL)
 	    relation->bucket = bkt;
     }
-  
+
 exit:
     /*
     * Return the bucket explicitely; this is needed for the
     * main schema.
     */
     if (bucket != NULL)
-	*bucket = bkt;    
+	*bucket = bkt;
     return (0);
 
 exit_error:
@@ -10655,7 +10655,7 @@
 	xmlFreeDoc(doc);
 	if (bkt != NULL)
 	    bkt->doc = NULL;
-    }    
+    }
     return (-1);
 }
 
@@ -10755,8 +10755,8 @@
     thisTargetNamespace = WXS_BUCKET(pctxt)->origTargetNamespace;
     if (namespaceName != NULL) {
 	/*
-	* 1.1 If the namespace [attribute] is present, then its ·actual value·
-	* must not match the ·actual value· of the enclosing <schema>'s
+	* 1.1 If the namespace [attribute] is present, then its �actual value�
+	* must not match the �actual value� of the enclosing <schema>'s
 	* targetNamespace [attribute].
 	*/
 	if (xmlStrEqual(thisTargetNamespace, namespaceName)) {
@@ -10810,11 +10810,11 @@
 	    "Failed to locate a schema at location '%s'. "
 	    "Skipping the import", schemaLocation, NULL, NULL);
     }
-    
-    if ((bucket != NULL) && CAN_PARSE_SCHEMA(bucket)) {	
+
+    if ((bucket != NULL) && CAN_PARSE_SCHEMA(bucket)) {
 	ret = xmlSchemaParseNewDoc(pctxt, schema, bucket);
     }
-    
+
     return (ret);
 }
 
@@ -10896,7 +10896,7 @@
 		XML_SCHEMAP_SRC_REDEFINE,
 		NULL, node,
 		"The schema document '%s' cannot redefine itself.",
-		*schemaLocation);	    
+		*schemaLocation);
 	} else {
 	    xmlSchemaPCustomErr(pctxt,
 		XML_SCHEMAP_SRC_INCLUDE,
@@ -10906,7 +10906,7 @@
 	}
 	goto exit_error;
     }
-    
+
     return(0);
 exit_error:
     return(pctxt->err);
@@ -10936,19 +10936,19 @@
     res = xmlSchemaParseIncludeOrRedefineAttrs(pctxt, schema,
 	node, (xmlChar **) (&schemaLocation), type);
     if (res != 0)
-	return(res);    	   
+	return(res);
     /*
     * Load and add the schema document.
     */
     res = xmlSchemaAddSchemaDoc(pctxt, type, schemaLocation, NULL,
 	NULL, 0, node, pctxt->targetNamespace, NULL, &bucket);
     if (res != 0)
-	return(res);    
+	return(res);
     /*
     * If we get no schema bucket back, then this means that the schema
     * document could not be located or was broken XML or was not
     * a schema document.
-    */    
+    */
     if ((bucket == NULL) || (bucket->doc == NULL)) {
 	if (type == XML_SCHEMA_SCHEMA_INCLUDE) {
 	    /*
@@ -10957,7 +10957,7 @@
 	    * for inclusions, since the that was the feedback from the
 	    * schema people. I.e. the following spec piece will *not* be
 	    * satisfied:
-	    * SPEC src-include: "It is not an error for the ·actual value· of the
+	    * SPEC src-include: "It is not an error for the �actual value� of the
 	    * schemaLocation [attribute] to fail to resolve it all, in which
 	    * case no corresponding inclusion is performed.
 	    * So do we need a warning report here?"
@@ -10974,7 +10974,7 @@
 	    *
 	    * SPEC src-redefine (1)
 	    * "If there are any element information items among the [children]
-	    * other than <annotation> then the ·actual value· of the
+	    * other than <annotation> then the �actual value� of the
 	    * schemaLocation [attribute] must successfully resolve."
 	    * TODO: Ask the WG if a the location has always to resolve
 	    * here as well!
@@ -10990,13 +10990,13 @@
 	* Check targetNamespace sanity before parsing the new schema.
 	* TODO: Note that we won't check further content if the
 	* targetNamespace was bad.
-	*/    
-	if (bucket->origTargetNamespace != NULL) {	    
+	*/
+	if (bucket->origTargetNamespace != NULL) {
 	    /*
 	    * SPEC src-include (2.1)
-	    * "SII has a targetNamespace [attribute], and its ·actual
-	    * value· is identical to the ·actual value· of the targetNamespace
-	    * [attribute] of SIIÂ’ (which must have such an [attribute])."
+	    * "SII has a targetNamespace [attribute], and its �actual
+	    * value� is identical to the �actual value� of the targetNamespace
+	    * [attribute] of SII� (which must have such an [attribute])."
 	    */
 	    if (pctxt->targetNamespace == NULL) {
 		xmlSchemaCustomErr(ACTXT_CAST pctxt,
@@ -11020,7 +11020,7 @@
 		    pctxt->targetNamespace);
 		goto exit_error;
 	    }
-	} else if (pctxt->targetNamespace != NULL) {	    
+	} else if (pctxt->targetNamespace != NULL) {
 	    /*
 	    * Chameleons: the original target namespace will
 	    * differ from the resulting namespace.
@@ -11038,10 +11038,10 @@
 	    }
 	    bucket->targetNamespace = pctxt->targetNamespace;
 	}
-    }    
+    }
     /*
     * Parse the schema.
-    */   
+    */
     if (bucket && (!bucket->parsed) && (bucket->doc != NULL)) {
 	if (isChameleon) {
 	    /* TODO: Get rid of this flag on the schema itself. */
@@ -11058,8 +11058,8 @@
     /*
     * And now for the children...
     */
-    child = node->children;    
-    if (type == XML_SCHEMA_SCHEMA_REDEFINE) {	
+    child = node->children;
+    if (type == XML_SCHEMA_SCHEMA_REDEFINE) {
 	/*
 	* Parse (simpleType | complexType | group | attributeGroup))*
 	*/
@@ -11082,7 +11082,7 @@
 	    } else if (IS_SCHEMA(child, "complexType")) {
 		xmlSchemaParseComplexType(pctxt, schema, child, 1);
 		/* hasRedefinitions = 1; */
-	    } else if (IS_SCHEMA(child, "group")) {		
+	    } else if (IS_SCHEMA(child, "group")) {
 		/* hasRedefinitions = 1; */
 		xmlSchemaParseModelGroupDefinition(pctxt,
 		    schema, child);
@@ -11102,7 +11102,7 @@
 	    */
 	    child = child->next;
 	}
-    }    
+    }
     if (child != NULL) {
 	res = XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED;
 	if (type == XML_SCHEMA_SCHEMA_REDEFINE) {
@@ -11113,8 +11113,8 @@
 	     xmlSchemaPContentErr(pctxt, res,
 		NULL, node, child, NULL,
 		"(annotation?)");
-	}	
-    }       
+	}
+    }
     return(res);
 
 exit_error:
@@ -11164,7 +11164,7 @@
  *     Redefinition Constraints and Semantics (src-redefine)
  *     (6.1), (6.1.1), (6.1.2)
  *
- *   Schema Component Constraint: 
+ *   Schema Component Constraint:
  *     All Group Limited (cos-all-limited) (2)
  *     TODO: Actually this should go to component-level checks,
  *     but is done here due to performance. Move it to an other layer
@@ -11343,8 +11343,8 @@
 			/*
 			* SPEC src-redefine:
 			* (6.1) "If it has a <group> among its contents at
-			* some level the ·actual value· of whose ref
-			* [attribute] is the same as the ·actual value· of
+			* some level the �actual value� of whose ref
+			* [attribute] is the same as the �actual value� of
 			* its own name attribute plus target namespace, then
 			* all of the following must be true:"
 			* (6.1.1) "It must have exactly one such group."
@@ -11369,9 +11369,9 @@
 			    xmlChar *str = NULL;
 			    /*
 			    * SPEC src-redefine:
-			    * (6.1.2) "The ·actual value· of both that
+			    * (6.1.2) "The �actual value� of both that
 			    * group's minOccurs and maxOccurs [attribute]
-			    * must be 1 (or ·absent·).
+			    * must be 1 (or �absent�).
 			    */
 			    xmlSchemaCustomErr(ACTXT_CAST ctxt,
 				XML_SCHEMAP_SRC_REDEFINE, child, NULL,
@@ -11388,7 +11388,7 @@
 			}
 			ctxt->redef->reference = WXS_BASIC_CAST part;
 			ctxt->redefCounter++;
-		    }		        		   
+		    }
 		}
 	    } else if (IS_SCHEMA(child, "any")) {
 		part = (xmlSchemaTreeItemPtr)
@@ -11425,7 +11425,7 @@
 	WXS_ADD_PENDING(ctxt, item);
     }
     if (withParticle)
-	return ((xmlSchemaTreeItemPtr) particle);	
+	return ((xmlSchemaTreeItemPtr) particle);
     else
 	return ((xmlSchemaTreeItemPtr) item);
 }
@@ -11477,7 +11477,7 @@
     */
     xmlSchemaPValAttrID(ctxt, node, BAD_CAST "id");
     /*
-    * Attribute 
+    * Attribute
     */
     /*
     * Extract the base type. The "base" attribute is mandatory if inside
@@ -11485,8 +11485,8 @@
     *
     * SPEC (1.2) "...otherwise (<restriction> has no <simpleType> "
     * among its [children]), the simple type definition which is
-    * the {content type} of the type definition ·resolved· to by
-    * the ·actual value· of the base [attribute]"
+    * the {content type} of the type definition �resolved� to by
+    * the �actual value� of the base [attribute]"
     */
     if (xmlSchemaPValAttrQName(ctxt, schema, NULL, node, "base",
 	&(type->baseNs), &(type->base)) == 0)
@@ -11509,8 +11509,8 @@
 		/*
 		* REDEFINE: SPEC src-redefine (5)
 		* "Within the [children], each <simpleType> must have a
-		* <restriction> among its [children] ... the ·actual value· of
-		* whose base [attribute] must be the same as the ·actual value·
+		* <restriction> among its [children] ... the �actual value� of
+		* whose base [attribute] must be the same as the �actual value�
 		* of its own name attribute plus target namespace;"
 		*/
 		xmlSchemaPCustomErrExt(ctxt, XML_SCHEMAP_SRC_REDEFINE,
@@ -11526,7 +11526,7 @@
 		type->base = NULL;
 		type->baseNs = NULL;
 	    }
-	}		
+	}
     }
     /*
     * And now for the children...
@@ -11593,7 +11593,7 @@
 	/*
 	* Model group reference <group>.
 	*/
-	} else if (IS_SCHEMA(child, "group")) {	    
+	} else if (IS_SCHEMA(child, "group")) {
 	    type->subtypes = (xmlSchemaTypePtr)
 		xmlSchemaParseModelGroupDefRef(ctxt, schema, child);
 	    /*
@@ -11931,13 +11931,13 @@
 	xmlSchemaPContentErr(ctxt,
 	    XML_SCHEMAP_S4S_ELEM_MISSING,
 	    NULL, node, NULL, NULL,
-	    "(annotation?, (restriction | extension))");	
+	    "(annotation?, (restriction | extension))");
     }
     if (child == NULL) {
 	xmlSchemaPContentErr(ctxt,
 	    XML_SCHEMAP_S4S_ELEM_MISSING,
 	    NULL, node, NULL, NULL,
-	    "(annotation?, (restriction | extension))");	
+	    "(annotation?, (restriction | extension))");
     }
     if (IS_SCHEMA(child, "restriction")) {
         xmlSchemaParseRestriction(ctxt, schema, child,
@@ -12094,7 +12094,7 @@
 	} else if (xmlSchemaPValAttrNode(ctxt, NULL, attr,
 	    xmlSchemaGetBuiltInType(XML_SCHEMAS_NCNAME), &name) != 0) {
 	    return (NULL);
-	}	
+	}
     }
 
     if (topLevel == 0) {
@@ -12183,7 +12183,7 @@
 			    NULL, (xmlNodePtr) attr, NULL,
 			    "(#all | List of (extension | restriction))",
 			    attrValue, NULL, NULL, NULL);
-		    } else 
+		    } else
 			final = 1;
 		} else if (xmlStrEqual(attr->name, BAD_CAST "block")) {
 		    /*
@@ -12201,7 +12201,7 @@
 			    NULL, (xmlNodePtr) attr, NULL,
 			    "(#all | List of (extension | restriction)) ",
 			    attrValue, NULL, NULL, NULL);
-		    } else 
+		    } else
 			block = 1;
 		} else {
 			xmlSchemaPIllegalAttrErr(ctxt,
@@ -12212,7 +12212,7 @@
 		    XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr);
 	    }
 	} else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) {
-	    xmlSchemaPIllegalAttrErr(ctxt, 
+	    xmlSchemaPIllegalAttrErr(ctxt,
 		XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, NULL, attr);
 	}
 	attr = attr->next;
@@ -12271,7 +12271,7 @@
 	* SPEC
 	* "...the third alternative (neither <simpleContent> nor
 	* <complexContent>) is chosen. This case is understood as shorthand
-	* for complex content restricting the ·ur-type definition·, and the
+	* for complex content restricting the �ur-type definition�, and the
 	* details of the mappings should be modified as necessary.
 	*/
 	type->baseType = xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYTYPE);
@@ -12448,7 +12448,7 @@
 	return(NULL);
     ret->buffer = buffer;
     ret->size = size;
-    ret->dict = xmlDictCreate();    
+    ret->dict = xmlDictCreate();
     return (ret);
 }
 
@@ -12491,7 +12491,7 @@
     if (ctxt == NULL)
         return;
     if (ctxt->doc != NULL && !ctxt->preserve)
-        xmlFreeDoc(ctxt->doc);    
+        xmlFreeDoc(ctxt->doc);
     if (ctxt->vctxt != NULL) {
 	xmlSchemaFreeValidCtxt(ctxt->vctxt);
     }
@@ -12573,7 +12573,7 @@
 	    *  was incorrectly used instead of xmlAutomataNewTransition2()
 	    *  (seems like a copy&paste bug from the XML_SCHEMA_TYPE_ALL
 	    *  section in xmlSchemaBuildAContentModel() ).
-	    * TODO: Check if xmlAutomataNewOnceTrans2() was instead 
+	    * TODO: Check if xmlAutomataNewOnceTrans2() was instead
 	    *  intended for the above "counter" section originally. I.e.,
 	    *  check xs:all with subst-groups.
 	    *
@@ -12582,7 +12582,7 @@
 	    *		       1, 1, member);
 	    */
 	    tmp = xmlAutomataNewTransition2(pctxt->am, start, NULL,
-		member->name, member->targetNamespace, member);	    
+		member->name, member->targetNamespace, member);
 	    xmlAutomataNewEpsilon(pctxt->am, tmp, end);
 	}
     } else {
@@ -12645,11 +12645,11 @@
 	} else if ((particle->maxOccurs >= UNBOUNDED) &&
 	           (particle->minOccurs < 2)) {
 	    /* Special case. */
-	    start = ctxt->state;	    
+	    start = ctxt->state;
 	    ctxt->state = xmlAutomataNewTransition2(ctxt->am, start, NULL,
-		elemDecl->name, elemDecl->targetNamespace, elemDecl);	    
+		elemDecl->name, elemDecl->targetNamespace, elemDecl);
 	    ctxt->state = xmlAutomataNewTransition2(ctxt->am, ctxt->state, ctxt->state,
-		elemDecl->name, elemDecl->targetNamespace, elemDecl);	    
+		elemDecl->name, elemDecl->targetNamespace, elemDecl);
 	} else {
 	    int counter;
 	    int maxOccurs = particle->maxOccurs == UNBOUNDED ?
@@ -12684,7 +12684,7 @@
 			    xmlSchemaParticlePtr particle)
 {
     if (particle == NULL) {
-	PERROR_INT("xmlSchemaBuildAContentModel", "particle is NULL");	    
+	PERROR_INT("xmlSchemaBuildAContentModel", "particle is NULL");
 	return;
     }
     if (particle->children == NULL) {
@@ -13115,8 +13115,8 @@
     if ((elemDecl->subtypes == NULL) && (elemDecl->namedType != NULL)) {
 	xmlSchemaTypePtr type;
 
-	/* (type definition) ... otherwise the type definition ·resolved·
-	* to by the ·actual value· of the type [attribute] ...
+	/* (type definition) ... otherwise the type definition �resolved�
+	* to by the �actual value� of the type [attribute] ...
 	*/
 	type = xmlSchemaGetType(ctxt->schema, elemDecl->namedType,
 	    elemDecl->namedTypeNs);
@@ -13154,7 +13154,7 @@
 	    /*
 	    * The type definitions is set to:
 	    * SPEC "...the {type definition} of the element
-	    * declaration ·resolved· to by the ·actual value·
+	    * declaration �resolved� to by the �actual value�
 	    * of the substitutionGroup [attribute], if present"
 	    */
 	    if (elemDecl->subtypes == NULL)
@@ -13192,8 +13192,8 @@
 
     /*
     * SPEC (1) "If the <union> alternative is chosen, then [Definition:]
-    * define the explicit members as the type definitions ·resolved·
-    * to by the items in the ·actual value· of the memberTypes [attribute],
+    * define the explicit members as the type definitions �resolved�
+    * to by the items in the �actual value� of the memberTypes [attribute],
     * if any, followed by the type definitions corresponding to the
     * <simpleType>s among the [children] of <union>, if any."
     */
@@ -13306,7 +13306,6 @@
 
     return (0);
 }
-#endif
 
 static xmlSchemaTypePtr
 xmlSchemaQueryBuiltInType(xmlSchemaTypePtr type)
@@ -13319,6 +13318,7 @@
 	return(type);
     return(xmlSchemaQueryBuiltInType(type->subtypes));
 }
+#endif
 
 /**
  * xmlSchemaGetPrimitiveType:
@@ -13488,7 +13488,7 @@
 	return (0);
     }
     /*
-    * 3 If both O1 and O2 are sets of (namespace names or ·absent·),
+    * 3 If both O1 and O2 are sets of (namespace names or �absent�),
     * then the union of those sets must be the value.
     */
     if ((completeWild->nsSet != NULL) && (curWild->nsSet != NULL)) {
@@ -13522,7 +13522,7 @@
     }
     /*
     * 4 If the two are negations of different values (namespace names
-    * or ·absent·), then a pair of not and ·absent· must be the value.
+    * or �absent�), then a pair of not and �absent� must be the value.
     */
     if ((completeWild->negNsSet != NULL) &&
 	(curWild->negNsSet != NULL) &&
@@ -13564,7 +13564,7 @@
 	if (nsFound && absentFound) {
 	    /*
 	    * 5.1 If the set S includes both the negated namespace
-	    * name and ·absent·, then any must be the value.
+	    * name and �absent�, then any must be the value.
 	    */
 	    completeWild->any = 1;
 	    if (completeWild->nsSet != NULL) {
@@ -13578,7 +13578,7 @@
 	} else if (nsFound && (!absentFound)) {
 	    /*
 	    * 5.2 If the set S includes the negated namespace name
-	    * but not ·absent·, then a pair of not and ·absent· must
+	    * but not �absent�, then a pair of not and �absent� must
 	    * be the value.
 	    */
 	    if (completeWild->nsSet != NULL) {
@@ -13593,7 +13593,7 @@
 	    completeWild->negNsSet->value = NULL;
 	} else if ((!nsFound) && absentFound) {
 	    /*
-	    * 5.3 If the set S includes ·absent· but not the negated
+	    * 5.3 If the set S includes �absent� but not the negated
 	    * namespace name, then the union is not expressible.
 	    */
 	    xmlSchemaPErr(ctxt, completeWild->node,
@@ -13604,7 +13604,7 @@
 	} else if ((!nsFound) && (!absentFound)) {
 	    /*
 	    * 5.4 If the set S does not include either the negated namespace
-	    * name or ·absent·, then whichever of O1 or O2 is a pair of not
+	    * name or �absent�, then whichever of O1 or O2 is a pair of not
 	    * and a namespace name must be the value.
 	    */
 	    if (completeWild->negNsSet == NULL) {
@@ -13638,7 +13638,7 @@
 	while (cur != NULL) {
 	    if (cur->value == NULL) {
 		/*
-		* 6.1 If the set S includes ·absent·, then any must be the
+		* 6.1 If the set S includes �absent�, then any must be the
 		* value.
 		*/
 		completeWild->any = 1;
@@ -13656,8 +13656,8 @@
 	}
 	if (completeWild->negNsSet == NULL) {
 	    /*
-	    * 6.2 If the set S does not include ·absent·, then a pair of not
-	    * and ·absent· must be the value.
+	    * 6.2 If the set S does not include �absent�, then a pair of not
+	    * and �absent� must be the value.
 	    */
 	    if (completeWild->nsSet != NULL) {
 		xmlSchemaFreeWildcardNsSet(completeWild->nsSet);
@@ -13740,9 +13740,9 @@
     }
     /*
     * 3 If either O1 or O2 is a pair of not and a value (a namespace
-    * name or ·absent·) and the other is a set of (namespace names or
-    * ·absent·), then that set, minus the negated value if it was in
-    * the set, minus ·absent· if it was in the set, must be the value.
+    * name or �absent�) and the other is a set of (namespace names or
+    * �absent�), then that set, minus the negated value if it was in
+    * the set, minus �absent� if it was in the set, must be the value.
     */
     if (((completeWild->negNsSet != NULL) && (curWild->nsSet != NULL)) ||
 	((curWild->negNsSet != NULL) && (completeWild->nsSet != NULL))) {
@@ -13791,7 +13791,7 @@
 	return(0);
     }
     /*
-    * 4 If both O1 and O2 are sets of (namespace names or ·absent·),
+    * 4 If both O1 and O2 are sets of (namespace names or �absent�),
     * then the intersection of those sets must be the value.
     */
     if ((completeWild->nsSet != NULL) && (curWild->nsSet != NULL)) {
@@ -13841,7 +13841,7 @@
     }
     /*
     * 6 If the one is a negation of a namespace name and the other
-    * is a negation of ·absent·, then the one which is the negation
+    * is a negation of �absent�, then the one which is the negation
     * of a namespace name must be the value.
     */
     if ((completeWild->negNsSet != NULL) && (curWild->negNsSet != NULL) &&
@@ -13873,7 +13873,7 @@
     if (super->any)
 	return (0);
     /*
-    * 2.1 sub must be a pair of not and a namespace name or ·absent·.
+    * 2.1 sub must be a pair of not and a namespace name or �absent�.
     * 2.2 super must be a pair of not and the same value.
     */
     if ((sub->negNsSet != NULL) &&
@@ -13881,7 +13881,7 @@
 	(sub->negNsSet->value == sub->negNsSet->value))
 	return (0);
     /*
-    * 3.1 sub must be a set whose members are either namespace names or ·absent·.
+    * 3.1 sub must be a set whose members are either namespace names or �absent�.
     */
     if (sub->nsSet != NULL) {
 	/*
@@ -13912,7 +13912,7 @@
 	    xmlSchemaWildcardNsPtr cur;
 	    /*
 	    * 3.2.2 super must be a pair of not and a namespace name or
-	    * ·absent· and that value must not be in sub's set.
+	    * �absent� and that value must not be in sub's set.
 	    */
 	    cur = sub->nsSet;
 	    while (cur != NULL) {
@@ -13937,7 +13937,7 @@
     if (val != 0)
 	*val = NULL;
 
-    if (attruse->defValue != NULL) {	    
+    if (attruse->defValue != NULL) {
 	*value = attruse->defValue;
 	if (val != NULL)
 	    *val = attruse->defVal;
@@ -14017,12 +14017,12 @@
 				       xmlSchemaItemListPtr baseUses,
 				       xmlSchemaWildcardPtr wild,
 				       xmlSchemaWildcardPtr baseWild)
-{        
+{
     xmlSchemaAttributeUsePtr cur = NULL, bcur;
     int i, j, found; /* err = 0; */
     const xmlChar *bEffValue;
     int effFixed;
-    
+
     if (uses != NULL) {
 	for (i = 0; i < uses->nbItems; i++) {
 	    cur = uses->items[i];
@@ -14030,7 +14030,7 @@
 	    if (baseUses == NULL)
 		goto not_found;
 	    for (j = 0; j < baseUses->nbItems; j++) {
-		bcur = baseUses->items[j];	
+		bcur = baseUses->items[j];
 		if ((WXS_ATTRUSE_DECL_NAME(cur) ==
 			WXS_ATTRUSE_DECL_NAME(bcur)) &&
 		    (WXS_ATTRUSE_DECL_TNS(cur) ==
@@ -14043,7 +14043,7 @@
 		    * namespace}, then  all of the following must be true:"
 		    */
 		    found = 1;
-		    
+
 		    if ((cur->occurs == XML_SCHEMAS_ATTR_USE_OPTIONAL) &&
 			(bcur->occurs == XML_SCHEMAS_ATTR_USE_REQUIRED))
 		    {
@@ -14069,12 +14069,12 @@
 			WXS_ATTRUSE_TYPEDEF(bcur), 0) != 0)
 		    {
 			xmlChar *strA = NULL, *strB = NULL, *strC = NULL;
-			
+
 			/*
 			* SPEC (2.1.2) "R's {attribute declaration}'s
 			* {type definition} must be validly derived from
 			* B's {type definition} given the empty set as
-			* defined in Type Derivation OK (Simple) (§3.14.6)."
+			* defined in Type Derivation OK (Simple) (�3.14.6)."
 			*/
 			xmlSchemaPAttrUseErr4(pctxt,
 			    XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_2,
@@ -14106,17 +14106,17 @@
 			/*
 			* 2.1.3 ... one of the following must be true
 			*
-			* 2.1.3.1 B's ·effective value constraint· is
-			* ·absent· or default.
+			* 2.1.3.1 B's �effective value constraint� is
+			* �absent� or default.
 			*/
 			if ((bEffValue != NULL) &&
 			    (effFixed == 1)) {
 			    const xmlChar *rEffValue = NULL;
-			    
+
 			    xmlSchemaGetEffectiveValueConstraint(bcur,
 				&effFixed, &rEffValue, NULL);
 			    /*
-			    * 2.1.3.2 R's ·effective value constraint· is
+			    * 2.1.3.2 R's �effective value constraint� is
 			    * fixed with the same string as B's.
 			    * MAYBE TODO: Compare the computed values.
 			    *       Hmm, it says "same string" so
@@ -14126,7 +14126,7 @@
 				(! WXS_ARE_DEFAULT_STR_EQUAL(rEffValue, bEffValue)))
 			    {
 				xmlChar *str = NULL;
-				
+
 				xmlSchemaPAttrUseErr4(pctxt,
 				    XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_3,
 				    WXS_ITEM_NODE(item), item, cur,
@@ -14145,21 +14145,21 @@
 		    break;
 		}
 	    }
-not_found:	
+not_found:
 	    if (!found) {
 		/*
 		* (2.2) "otherwise the {base type definition} must have an
 		* {attribute wildcard} and the {target namespace} of the
-		* R's {attribute declaration} must be ·valid· with respect
+		* R's {attribute declaration} must be �valid� with respect
 		* to that wildcard, as defined in Wildcard allows Namespace
-		* Name (§3.10.4)."
+		* Name (�3.10.4)."
 		*/
 		if ((baseWild == NULL) ||
 		    (xmlSchemaCheckCVCWildcardNamespace(baseWild,
 		    (WXS_ATTRUSE_DECL(cur))->targetNamespace) != 0))
 		{
 		    xmlChar *str = NULL;
-		    
+
 		    xmlSchemaPAttrUseErr4(pctxt,
 			XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_2,
 			WXS_ITEM_NODE(item), item, cur,
@@ -14175,7 +14175,7 @@
 	}
     }
     /*
-    * SPEC derivation-ok-restriction (3):    
+    * SPEC derivation-ok-restriction (3):
     * (3) "For each attribute use in the {attribute uses} of the {base type
     * definition} whose {required} is true, there must be an attribute
     * use with an {attribute declaration} with the same {name} and
@@ -14190,7 +14190,7 @@
 	    found = 0;
 	    if (uses != NULL) {
 		for (i = 0; i < uses->nbItems; i++) {
-		    cur = uses->items[i];	
+		    cur = uses->items[i];
 		    if ((WXS_ATTRUSE_DECL_NAME(cur) ==
 			WXS_ATTRUSE_DECL_NAME(bcur)) &&
 			(WXS_ATTRUSE_DECL_TNS(cur) ==
@@ -14202,7 +14202,7 @@
 	    }
 	    if (!found) {
 		xmlChar *strA = NULL, *strB = NULL;
-		
+
 		xmlSchemaCustomErr4(ACTXT_CAST pctxt,
 		    XML_SCHEMAP_DERIVATION_OK_RESTRICTION_3,
 		    NULL, item,
@@ -14224,19 +14224,19 @@
 	/*
 	* (4) "If there is an {attribute wildcard}, all of the
 	* following must be true:"
-	*/   
+	*/
 	if (baseWild == NULL) {
 	    xmlChar *str = NULL;
 
 	    /*
 	    * (4.1) "The {base type definition} must also have one."
-	    */	    
+	    */
 	    xmlSchemaCustomErr4(ACTXT_CAST pctxt,
 		XML_SCHEMAP_DERIVATION_OK_RESTRICTION_4_1,
 		NULL, item,
 		"The %s has an attribute wildcard, "
 		"but the %s %s '%s' does not have one",
-		WXS_ITEM_TYPE_NAME(item),		    
+		WXS_ITEM_TYPE_NAME(item),
 		WXS_ACTION_STR(action),
 		WXS_ITEM_TYPE_NAME(baseItem),
 		xmlSchemaGetComponentQName(&str, baseItem));
@@ -14250,7 +14250,7 @@
 	    * (4.2) "The complex type definition's {attribute wildcard}'s
 	    * {namespace constraint} must be a subset of the {base type
 	    * definition}'s {attribute wildcard}'s {namespace constraint},
-	    * as defined by Wildcard Subset (§3.10.6)."
+	    * as defined by Wildcard Subset (�3.10.6)."
 	    */
 	    xmlSchemaCustomErr4(ACTXT_CAST pctxt,
 		XML_SCHEMAP_DERIVATION_OK_RESTRICTION_4_2,
@@ -14264,8 +14264,8 @@
 	    FREE_AND_NULL(str);
 	    return(pctxt->err);
 	}
-	/* 4.3 Unless the {base type definition} is the ·ur-type
-	* definition·, the complex type definition's {attribute
+	/* 4.3 Unless the {base type definition} is the �ur-type
+	* definition�, the complex type definition's {attribute
 	* wildcard}'s {process contents} must be identical to or
 	* stronger than the {base type definition}'s {attribute
 	* wildcard}'s {process contents}, where strict is stronger
@@ -14316,7 +14316,7 @@
 				  xmlSchemaTypePtr type)
 {
     xmlSchemaTypePtr baseType = NULL;
-    xmlSchemaAttributeUsePtr use;    
+    xmlSchemaAttributeUsePtr use;
     xmlSchemaItemListPtr uses, baseUses, prohibs = NULL;
 
     if (type->baseType == NULL) {
@@ -14324,7 +14324,7 @@
 	    "no base type");
         return (-1);
     }
-    baseType = type->baseType;        
+    baseType = type->baseType;
     if (WXS_IS_TYPE_NOT_FIXED(baseType))
 	if (xmlSchemaTypeFixup(baseType, ACTXT_CAST pctxt) == -1)
 	    return(-1);
@@ -14336,7 +14336,7 @@
     * wildcard, i.e. intersect multiple wildcards.
     * Move attribute prohibitions into a separate list.
     */
-    if (uses != NULL) {	
+    if (uses != NULL) {
 	if (WXS_IS_RESTRICTION(type)) {
 	    /*
 	    * This one will transfer all attr. prohibitions
@@ -14370,7 +14370,7 @@
 
 	if (WXS_IS_RESTRICTION(type)) {
 	    int usesCount;
-	    xmlSchemaAttributeUsePtr tmp; 
+	    xmlSchemaAttributeUsePtr tmp;
 
 	    if (uses != NULL)
 		usesCount = uses->nbItems;
@@ -14420,15 +14420,15 @@
 	    }
 	} else {
 	    /* Extension. */
-	    for (i = 0; i < baseUses->nbItems; i++) {	    
-		use = baseUses->items[i];		
+	    for (i = 0; i < baseUses->nbItems; i++) {
+		use = baseUses->items[i];
 		if (uses == NULL) {
 		    type->attrUses = xmlSchemaItemListCreate();
 		    if (type->attrUses == NULL)
 			goto exit_failure;
 		    uses = type->attrUses;
 		}
-		xmlSchemaItemListAddSize(uses, baseUses->nbItems, use); 
+		xmlSchemaItemListAddSize(uses, baseUses->nbItems, use);
 	    }
 	}
     }
@@ -14448,10 +14448,10 @@
     /*
     * Compute the complete wildcard.
     */
-    if (WXS_IS_EXTENSION(type)) {	
+    if (WXS_IS_EXTENSION(type)) {
 	if (baseType->attributeWildcard != NULL) {
 	    /*
-	    * (3.2.2.1) "If the ·base wildcard· is non-·absent·, then
+	    * (3.2.2.1) "If the �base wildcard� is non-�absent�, then
 	    * the appropriate case among the following:"
 	    */
 	    if (type->attributeWildcard != NULL) {
@@ -14459,26 +14459,26 @@
 		* Union the complete wildcard with the base wildcard.
 		* SPEC {attribute wildcard}
 		* (3.2.2.1.2) "otherwise a wildcard whose {process contents}
-		* and {annotation} are those of the ·complete wildcard·,
+		* and {annotation} are those of the �complete wildcard�,
 		* and whose {namespace constraint} is the intensional union
-		* of the {namespace constraint} of the ·complete wildcard·
-		* and of the ·base wildcard·, as defined in Attribute
-		* Wildcard Union (§3.10.6)."
+		* of the {namespace constraint} of the �complete wildcard�
+		* and of the �base wildcard�, as defined in Attribute
+		* Wildcard Union (�3.10.6)."
 		*/
 		if (xmlSchemaUnionWildcards(pctxt, type->attributeWildcard,
 		    baseType->attributeWildcard) == -1)
-		    goto exit_failure;		
+		    goto exit_failure;
 	    } else {
 		/*
-		* (3.2.2.1.1) "If the ·complete wildcard· is ·absent·,
-		* then the ·base wildcard·."
+		* (3.2.2.1.1) "If the �complete wildcard� is �absent�,
+		* then the �base wildcard�."
 		*/
 		type->attributeWildcard = baseType->attributeWildcard;
-	    }	 
+	    }
 	} else {
 	    /*
-	    * (3.2.2.2) "otherwise (the ·base wildcard· is ·absent·) the
-	    * ·complete wildcard"
+	    * (3.2.2.2) "otherwise (the �base wildcard� is �absent�) the
+	    * �complete wildcard"
 	    * NOOP
 	    */
 	}
@@ -14486,11 +14486,11 @@
 	/*
 	* SPEC {attribute wildcard}
 	* (3.1) "If the <restriction> alternative is chosen, then the
-	* ·complete wildcard·;"
+	* �complete wildcard�;"
 	* NOOP
 	*/
     }
-    
+
     return (0);
 
 exit_failure:
@@ -14594,6 +14594,7 @@
     }
 }
 
+#if 0
 /**
  * xmlSchemaGetParticleTotalRangeMax:
  * @particle: the particle
@@ -14653,6 +14654,7 @@
 	return (particle->maxOccurs * sum);
     }
 }
+#endif
 
 /**
  * xmlSchemaIsParticleEmptiable:
@@ -14733,12 +14735,12 @@
     /* 2.2 */
     if (type->baseType == baseType) {
 	/*
-	* 2.2.1 D's ·base type definition· is B.
+	* 2.2.1 D's �base type definition� is B.
 	*/
 	return (0);
     }
     /*
-    * 2.2.2 D's ·base type definition· is not the ·ur-type definition·
+    * 2.2.2 D's �base type definition� is not the �ur-type definition�
     * and is validly derived from B given the subset, as defined by this
     * constraint.
     */
@@ -14748,8 +14750,8 @@
 	return (0);
     }
     /*
-    * 2.2.3 D's {variety} is list or union and B is the ·simple ur-type
-    * definition·.
+    * 2.2.3 D's {variety} is list or union and B is the �simple ur-type
+    * definition�.
     */
     if (WXS_IS_ANY_SIMPLE_TYPE(baseType) &&
 	(WXS_IS_LIST(type) || WXS_IS_UNION(type))) {
@@ -14865,10 +14867,10 @@
 xmlSchemaCheckUnionTypeDefCircularRecur(xmlSchemaParserCtxtPtr pctxt,
 					xmlSchemaTypePtr ctxType,
 					xmlSchemaTypeLinkPtr members)
-{    
+{
     xmlSchemaTypeLinkPtr member;
     xmlSchemaTypePtr memberType;
-    
+
     member = members;
     while (member != NULL) {
 	memberType = member->type;
@@ -14969,7 +14971,7 @@
 	    }
 	    return;
 	}
-    } 
+    }
     /*
     * The ball of letters below means, that if we have a particle
     * which has a QName-helper component as its {term}, we want
@@ -15012,7 +15014,7 @@
 	    * particle's {term}.
 	    */
 	    WXS_TYPE_PARTICLE_TERM(typeDef) = WXS_MODELGROUPDEF_MODEL(groupDef);
-	    
+
 	    if (WXS_MODELGROUPDEF_MODEL(groupDef)->type == XML_SCHEMA_TYPE_ALL) {
 		/*
 		* SPEC cos-all-limited (1.2)
@@ -15061,14 +15063,14 @@
     * NOTE: This is somehow redundant, since we actually built a simple type
     * to have all the needed information; this acts as an self test.
     */
-    /* Base type: If the datatype has been ·derived· by ·restriction·
-    * then the Simple Type Definition component from which it is ·derived·,
-    * otherwise the Simple Type Definition for anySimpleType (§4.1.6).
+    /* Base type: If the datatype has been �derived� by �restriction�
+    * then the Simple Type Definition component from which it is �derived�,
+    * otherwise the Simple Type Definition for anySimpleType (�4.1.6).
     */
     if (baseType == NULL) {
 	/*
 	* TODO: Think about: "modulo the impact of Missing
-	* Sub-components (§5.3)."
+	* Sub-components (�5.3)."
 	*/
 	xmlSchemaPCustomErr(ctxt,
 	    XML_SCHEMAP_ST_PROPS_CORRECT_1,
@@ -15092,7 +15094,7 @@
 	xmlSchemaPCustomErr(ctxt,
 	    XML_SCHEMAP_ST_PROPS_CORRECT_1,
 	    WXS_BASIC_CAST type, NULL,
-	    "A type, derived by list or union, must have"
+	    "A type, derived by list or union, must have "
 	    "the simple ur-type definition as base type, not '%s'",
 	    xmlSchemaGetComponentQName(&str, baseType));
 	FREE_AND_NULL(str)
@@ -15127,10 +15129,10 @@
     }
 
     /*
-    * 2 All simple type definitions must be derived ultimately from the ·simple
-    * ur-type definition (so· circular definitions are disallowed). That is, it
-    * must be possible to reach a built-in primitive datatype or the ·simple
-    * ur-type definition· by repeatedly following the {base type definition}.
+    * 2 All simple type definitions must be derived ultimately from the �simple
+    * ur-type definition (so� circular definitions are disallowed). That is, it
+    * must be possible to reach a built-in primitive datatype or the �simple
+    * ur-type definition� by repeatedly following the {base type definition}.
     *
     * NOTE: this is done in xmlSchemaCheckTypeDefCircular().
     */
@@ -15314,10 +15316,10 @@
 	    }
 	    /*
 	    * MAYBE TODO: (Hmm, not really) Datatypes states:
-	    * A ·list· datatype can be ·derived· from an ·atomic· datatype
-	    * whose ·lexical space· allows space (such as string or anyURI)or
-	    * a ·union· datatype any of whose {member type definitions}'s
-	    * ·lexical space· allows space.
+	    * A �list� datatype can be �derived� from an �atomic� datatype
+	    * whose �lexical space� allows space (such as string or anyURI)or
+	    * a �union� datatype any of whose {member type definitions}'s
+	    * �lexical space� allows space.
 	    */
 	} else {
 	    /*
@@ -15354,7 +15356,7 @@
 	    /*
 	    * 2.3.2.3 The {item type definition} must be validly derived
 	    * from the {base type definition}'s {item type definition} given
-	    * the empty set, as defined in Type Derivation OK (Simple) (§3.14.6).
+	    * the empty set, as defined in Type Derivation OK (Simple) (�3.14.6).
 	    */
 	    {
 		xmlSchemaTypePtr baseItemType;
@@ -15401,7 +15403,7 @@
 			case XML_SCHEMA_FACET_WHITESPACE:
 			    /*
 			    * TODO: 2.5.1.2 List datatypes
-			    * The value of ·whiteSpace· is fixed to the value collapse.
+			    * The value of �whiteSpace� is fixed to the value collapse.
 			    */
 			case XML_SCHEMA_FACET_PATTERN:
 			case XML_SCHEMA_FACET_ENUMERATION:
@@ -15454,8 +15456,8 @@
 	    member = member->next;
 	}
 	/*
-	* 3.3.1 If the {base type definition} is the ·simple ur-type
-	* definition·
+	* 3.3.1 If the {base type definition} is the �simple ur-type
+	* definition�
 	*/
 	if (type->baseType->builtInType == XML_SCHEMAS_ANYSIMPLETYPE) {
 	    /*
@@ -15517,7 +15519,7 @@
 	    * 3.3.2.3 The {member type definitions}, in order, must be validly
 	    * derived from the corresponding type definitions in the {base
 	    * type definition}'s {member type definitions} given the empty set,
-	    * as defined in Type Derivation OK (Simple) (§3.14.6).
+	    * as defined in Type Derivation OK (Simple) (�3.14.6).
 	    */
 	    {
 		xmlSchemaTypeLinkPtr baseMember;
@@ -15609,7 +15611,7 @@
  * @ctxt:  the schema parser context
  * @type:  the simple type definition
  *
- * Checks crc-simple-type constraints. 
+ * Checks crc-simple-type constraints.
  *
  * Returns 0 if the constraints are satisfied,
  * if not a positive error code and -1 on internal
@@ -15623,8 +15625,8 @@
     /*
     * src-simple-type.1 The corresponding simple type definition, if any,
     * must satisfy the conditions set out in Constraints on Simple Type
-    * Definition Schema Components (§3.14.6).
-    */    
+    * Definition Schema Components (�3.14.6).
+    */
     if (WXS_IS_RESTRICTION(type)) {
 	/*
 	* src-simple-type.2 "If the <restriction> alternative is chosen,
@@ -15633,7 +15635,7 @@
 	* NOTE: This is checked in the parse function of <restriction>.
 	*/
 	/*
-	* 
+	*
 	*/
     } else if (WXS_IS_LIST(type)) {
 	/* src-simple-type.3 "If the <list> alternative is chosen, either it must have
@@ -15642,8 +15644,8 @@
 	*
 	* NOTE: This is checked in the parse function of <list>.
 	*/
-    } else if (WXS_IS_UNION(type)) {	
-	/* 
+    } else if (WXS_IS_UNION(type)) {
+	/*
 	* src-simple-type.4 is checked in xmlSchemaCheckUnionTypeDefCircular().
 	*/
     }
@@ -15721,8 +15723,8 @@
 	* SPEC (2.1) "its {content type} must be a simple type definition
 	* or mixed."
 	* SPEC (2.2.2) "If the {content type} is mixed, then the {content
-	* type}'s particle must be ·emptiable· as defined by
-	* Particle Emptiable (§3.9.6)."
+	* type}'s particle must be �emptiable� as defined by
+	* Particle Emptiable (�3.9.6)."
 	*/
 	if ((! WXS_HAS_SIMPLE_CONTENT(type)) &&
 	    ((! WXS_HAS_MIXED_CONTENT(type)) || (! WXS_EMPTIABLE(type)))) {
@@ -15738,14 +15740,14 @@
     }
     /*
     * 1 If the type definition is a simple type definition, then the string
-    * must be ·valid· with respect to that definition as defined by String
-    * Valid (§3.14.4).
+    * must be �valid� with respect to that definition as defined by String
+    * Valid (�3.14.4).
     *
     * AND
     *
     * 2.2.1 If the {content type} is a simple type definition, then the
-    * string must be ·valid· with respect to that simple type definition
-    * as defined by String Valid (§3.14.4).
+    * string must be �valid� with respect to that simple type definition
+    * as defined by String Valid (�3.14.4).
     */
     if (WXS_IS_SIMPLE(type))
 	ret = xmlSchemaVCheckCVCSimpleType(ACTXT_CAST pctxt, node,
@@ -15786,8 +15788,8 @@
     *
     * SPEC (1) "The values of the properties of a complex type definition must
     * be as described in the property tableau in The Complex Type Definition
-    * Schema Component (§3.4.1), modulo the impact of Missing
-    * Sub-components (§5.3)."
+    * Schema Component (�3.4.1), modulo the impact of Missing
+    * Sub-components (�5.3)."
     */
     if ((type->baseType != NULL) &&
 	(WXS_IS_SIMPLE(type->baseType)) &&
@@ -15798,14 +15800,14 @@
 	*/
 	xmlSchemaCustomErr(ACTXT_CAST pctxt,
 	    XML_SCHEMAP_SRC_CT_1,
-	    NULL, WXS_BASIC_CAST type, 
+	    NULL, WXS_BASIC_CAST type,
 	    "If the base type is a simple type, the derivation method must be "
 	    "'extension'", NULL, NULL);
 	return (XML_SCHEMAP_SRC_CT_1);
     }
     /*
-    * SPEC (3) "Circular definitions are disallowed, except for the ·ur-type
-    * definition·. That is, it must be possible to reach the ·ur-type
+    * SPEC (3) "Circular definitions are disallowed, except for the �ur-type
+    * definition�. That is, it must be possible to reach the �ur-type
     * definition by repeatedly following the {base type definition}."
     *
     * NOTE (3) is done in xmlSchemaCheckTypeDefCircular().
@@ -15815,7 +15817,7 @@
     *   - attribute uses need to be already inherited (apply attr. prohibitions)
     *   - attribute group references need to be expanded already
     *   - simple types need to be typefixed already
-    */    
+    */
     if (type->attrUses &&
 	(((xmlSchemaItemListPtr) type->attrUses)->nbItems > 1))
     {
@@ -15825,8 +15827,8 @@
 
 	for (i = uses->nbItems -1; i >= 0; i--) {
 	    use = uses->items[i];
-	    
-	    /* 
+
+	    /*
 	    * SPEC ct-props-correct
 	    * (4) "Two distinct attribute declarations in the
 	    * {attribute uses} must not have identical {name}s and
@@ -15867,10 +15869,10 @@
 	    if (WXS_ATTRUSE_TYPEDEF(use) != NULL) {
 		if (xmlSchemaIsDerivedFromBuiltInType(
 		    WXS_ATTRUSE_TYPEDEF(use), XML_SCHEMAS_ID))
-		{		
+		{
 		    if (hasId) {
 			xmlChar *str = NULL;
-			
+
 			xmlSchemaCustomErr(ACTXT_CAST pctxt,
 			    XML_SCHEMAP_AG_PROPS_CORRECT,
 			    NULL, WXS_BASIC_CAST type,
@@ -15884,7 +15886,7 @@
 			if (xmlSchemaItemListRemove(uses, i) == -1)
 			    goto exit_failure;
 		    }
-		    
+
 		    hasId = 1;
 		}
 	    }
@@ -15958,8 +15960,8 @@
     if (type->baseType == baseType)
 	return (0);
     /*
-    * SPEC (2.3.1) "D's {base type definition} must not be the ·ur-type
-    * definition·."
+    * SPEC (2.3.1) "D's {base type definition} must not be the �ur-type
+    * definition�."
     */
     if (WXS_IS_ANYTYPE(type->baseType))
 	return (1);
@@ -15976,7 +15978,7 @@
 	/*
 	* SPEC (2.3.2.2) "If D's {base type definition} is simple, then it
 	* must be validly derived from B given the subset as defined in Type
-	* Derivation OK (Simple) (§3.14.6).
+	* Derivation OK (Simple) (�3.14.6).
 	*/
 	return (xmlSchemaCheckCOSSTDerivedOK(actxt, type->baseType,
 	    baseType, set));
@@ -16037,7 +16039,7 @@
     * SPEC (1) "If the {base type definition} is a complex type definition,
     * then all of the following must be true:"
     */
-    if (WXS_IS_COMPLEX(base)) {	
+    if (WXS_IS_COMPLEX(base)) {
 	/*
 	* SPEC (1.1) "The {final} of the {base type definition} must not
 	* contain extension."
@@ -16050,7 +16052,7 @@
 		"contains 'extension'", NULL);
 	    return (XML_SCHEMAP_COS_CT_EXTENDS_1_1);
 	}
-	
+
 	/*
 	* ATTENTION: The constrains (1.2) and (1.3) are not applied,
 	* since they are automatically satisfied through the
@@ -16094,11 +16096,11 @@
 		}
 		if (! found) {
 		    xmlChar *str = NULL;
-		
+
 		    xmlSchemaCustomErr(ACTXT_CAST ctxt,
 			XML_SCHEMAP_COS_CT_EXTENDS_1_2,
 			NULL, WXS_BASIC_CAST type,
-			/* 
+			/*
 			* TODO: The report does not indicate that also the
 			* type needs to be the same.
 			*/
@@ -16116,9 +16118,9 @@
 	* definition must also have one, and the base type definition's
 	* {attribute  wildcard}'s {namespace constraint} must be a subset
 	* of the complex  type definition's {attribute wildcard}'s {namespace
-	* constraint}, as defined by Wildcard Subset (§3.10.6)."
+	* constraint}, as defined by Wildcard Subset (�3.10.6)."
 	*/
-  
+
 	/*
 	* MAYBE TODO: Enable if ever needed. But this will be needed only
 	* if created the type via a schema construction API.
@@ -16126,7 +16128,7 @@
 	if (base->attributeWildcard != NULL) {
 	    if (type->attributeWilcard == NULL) {
 		xmlChar *str = NULL;
-		
+
 		xmlSchemaCustomErr(ACTXT_CAST pctxt,
 		    XML_SCHEMAP_COS_CT_EXTENDS_1_3,
 		    NULL, type,
@@ -16139,7 +16141,7 @@
 		base->attributeWildcard, type->attributeWildcard))
 	    {
 		xmlChar *str = NULL;
-		
+
 		xmlSchemaCustomErr(ACTXT_CAST pctxt,
 		    XML_SCHEMAP_COS_CT_EXTENDS_1_3,
 		    NULL, type,
@@ -16213,9 +16215,9 @@
 		}
 		/*
 		* URGENT TODO SPEC (1.4.3.2.2.2) "The particle of the
-		* complex type definition must be a ·valid extension·
+		* complex type definition must be a �valid extension�
 		* of the {base type definition}'s particle, as defined
-		* in Particle Valid (Extension) (§3.9.6)."
+		* in Particle Valid (Extension) (�3.9.6)."
 		*
 		* NOTE that we won't check "Particle Valid (Extension)",
 		* since it is ensured by the derivation process in
@@ -16293,7 +16295,7 @@
     */
     base = type->baseType;
     if (! WXS_IS_COMPLEX(base)) {
-	xmlSchemaCustomErr(ACTXT_CAST ctxt,	    
+	xmlSchemaCustomErr(ACTXT_CAST ctxt,
 	    XML_SCHEMAP_DERIVATION_OK_RESTRICTION_1,
 	    type->node, WXS_BASIC_CAST type,
 	    "The base type must be a complex type", NULL, NULL);
@@ -16304,7 +16306,7 @@
 	* SPEC (1) "The {base type definition} must be a complex type
 	* definition whose {final} does not contain restriction."
 	*/
-	xmlSchemaCustomErr(ACTXT_CAST ctxt,	    
+	xmlSchemaCustomErr(ACTXT_CAST ctxt,
 	    XML_SCHEMAP_DERIVATION_OK_RESTRICTION_1,
 	    type->node, WXS_BASIC_CAST type,
 	    "The 'final' of the base type definition "
@@ -16332,7 +16334,7 @@
     if (base->builtInType == XML_SCHEMAS_ANYTYPE) {
 	/*
 	* SPEC (5.1) "The {base type definition} must be the
-	* ·ur-type definition·."
+	* �ur-type definition�."
 	* PASS
 	*/
     } else if ((type->contentType == XML_SCHEMA_CONTENT_SIMPLE) ||
@@ -16351,11 +16353,11 @@
 	    * SPEC (5.2.2.1) "The {content type} of the {base type
 	    * definition} must be a simple type definition from which
 	    * the {content type} is validly derived given the empty
-	    * set as defined in Type Derivation OK (Simple) (§3.14.6)."
+	    * set as defined in Type Derivation OK (Simple) (�3.14.6)."
 	    *
 	    * ATTENTION TODO: This seems not needed if the type implicitely
 	    * derived from the base type.
-	    * 
+	    *
 	    */
 	    err = xmlSchemaCheckCOSSTDerivedOK(ACTXT_CAST ctxt,
 		type->contentTypeDef, base->contentTypeDef, 0);
@@ -16382,8 +16384,8 @@
 		(xmlSchemaParticlePtr) base->subtypes))) {
 	    /*
 	    * SPEC (5.2.2.2) "The {base type definition} must be mixed
-	    * and have a particle which is ·emptiable· as defined in
-	    * Particle Emptiable (§3.9.6)."
+	    * and have a particle which is �emptiable� as defined in
+	    * Particle Emptiable (�3.9.6)."
 	    * PASS
 	    */
 	} else {
@@ -16412,7 +16414,7 @@
 	    /*
 	    * SPEC (5.3.2.2) "The {content type} of the {base type
 	    * definition} must be elementOnly or mixed and have a particle
-	    * which is ·emptiable· as defined in Particle Emptiable (§3.9.6)."
+	    * which is �emptiable� as defined in Particle Emptiable (�3.9.6)."
 	    * PASS
 	    */
 	} else {
@@ -16429,7 +16431,7 @@
 	/*
 	* SPEC (5.4.1.1) "The {content type} of the complex type definition
 	* itself must be element-only"
-	*/	 
+	*/
 	if (WXS_HAS_MIXED_CONTENT(type) && (! WXS_HAS_MIXED_CONTENT(base))) {
 	    /*
 	    * SPEC (5.4.1.2) "The {content type} of the complex type
@@ -16445,9 +16447,9 @@
 	}
 	/*
 	* SPEC (5.4.2) "The particle of the complex type definition itself
-	* must be a ·valid restriction· of the particle of the {content
+	* must be a �valid restriction� of the particle of the {content
 	* type} of the {base type definition} as defined in Particle Valid
-	* (Restriction) (§3.9.6).
+	* (Restriction) (�3.9.6).
 	*
 	* URGENT TODO: (5.4.2)
 	*/
@@ -16516,7 +16518,7 @@
     if (! WXS_HAS_SIMPLE_CONTENT(type)) {
 	/*
 	* 1 If the <complexContent> alternative is chosen, the type definition
-	* ·resolved· to by the ·actual value· of the base [attribute]
+	* �resolved� to by the �actual value� of the base [attribute]
 	* must be a complex type definition;
 	*/
 	if (! WXS_IS_COMPLEX(base)) {
@@ -16536,7 +16538,7 @@
 	* SPEC
 	* 2 If the <simpleContent> alternative is chosen, all of the
 	* following must be true:
-	* 2.1 The type definition ·resolved· to by the ·actual value· of the
+	* 2.1 The type definition �resolved� to by the �actual value� of the
 	* base [attribute] must be one of the following:
 	*/
 	if (WXS_IS_SIMPLE(base)) {
@@ -16586,11 +16588,11 @@
 		if (! xmlSchemaIsParticleEmptiable(
 		    (xmlSchemaParticlePtr) base->subtypes)) {
 		    ret = XML_SCHEMAP_SRC_CT_1;
-		} else 
+		} else
 		    /*
 		    * Attention: at this point the <simpleType> child is in
 		    * ->contentTypeDef (put there during parsing).
-		    */		    
+		    */
 		    if (type->contentTypeDef == NULL) {
 		    xmlChar *str = NULL;
 		    /*
@@ -16642,14 +16644,14 @@
     /*
     * SPEC (3) "The corresponding complex type definition component must
     * satisfy the conditions set out in Constraints on Complex Type
-    * Definition Schema Components (§3.4.6);"
+    * Definition Schema Components (�3.4.6);"
     * NOTE (3) will be done in xmlSchemaTypeFixup().
     */
     /*
     * SPEC (4) If clause 2.2.1 or clause 2.2.2 in the correspondence specification
     * above for {attribute wildcard} is satisfied, the intensional
     * intersection must be expressible, as defined in Attribute Wildcard
-    * Intersection (§3.10.6).
+    * Intersection (�3.10.6).
     * NOTE (4) is done in xmlSchemaFixupTypeAttributeUses().
     */
     return (ret);
@@ -16720,7 +16722,7 @@
 	return (1);
     /*
     * SPEC (2) "R's occurrence range is a valid restriction of B's
-    * occurrence range as defined by Occurrence Range OK (§3.9.6)."
+    * occurrence range as defined by Occurrence Range OK (�3.9.6)."
     */
     if (xmlSchemaCheckParticleRangeOK(r->minOccurs, r->maxOccurs,
 	    b->minOccurs, b->maxOccurs) != 0)
@@ -16812,19 +16814,19 @@
 {
     /* TODO:Error codes (rcase-NSCompat). */
     /*
-    * SPEC "For an element declaration particle to be a ·valid restriction·
+    * SPEC "For an element declaration particle to be a �valid restriction�
     * of a wildcard particle all of the following must be true:"
     *
-    * SPEC (1) "The element declaration's {target namespace} is ·valid·
+    * SPEC (1) "The element declaration's {target namespace} is �valid�
     * with respect to the wildcard's {namespace constraint} as defined by
-    * Wildcard allows Namespace Name (§3.10.4)."
+    * Wildcard allows Namespace Name (�3.10.4)."
     */
     if (xmlSchemaCheckCVCWildcardNamespace((xmlSchemaWildcardPtr) b->children,
 	((xmlSchemaElementPtr) r->children)->targetNamespace) != 0)
 	return (1);
     /*
     * SPEC (2) "R's occurrence range is a valid restriction of B's
-    * occurrence range as defined by Occurrence Range OK (§3.9.6)."
+    * occurrence range as defined by Occurrence Range OK (�3.9.6)."
     */
     if (xmlSchemaCheckParticleRangeOK(r->minOccurs, r->maxOccurs,
 	    b->minOccurs, b->maxOccurs) != 0)
@@ -16884,21 +16886,21 @@
     /* TODO: Error codes (rcase-NSSubset). */
     /*
     * SPEC (1) "R's occurrence range is a valid restriction of B's
-    * occurrence range as defined by Occurrence Range OK (§3.9.6)."
+    * occurrence range as defined by Occurrence Range OK (�3.9.6)."
     */
     if (xmlSchemaCheckParticleRangeOK(r->minOccurs, r->maxOccurs,
 	    b->minOccurs, b->maxOccurs))
 	return (1);
     /*
     * SPEC (2) "R's {namespace constraint} must be an intensional subset
-    * of B's {namespace constraint} as defined by Wildcard Subset (§3.10.6)."
+    * of B's {namespace constraint} as defined by Wildcard Subset (�3.10.6)."
     */
     if (xmlSchemaCheckCOSNSSubset((xmlSchemaWildcardPtr) r->children,
 	(xmlSchemaWildcardPtr) b->children))
 	return (1);
     /*
-    * SPEC (3) "Unless B is the content model wildcard of the ·ur-type
-    * definition·, R's {process contents} must be identical to or stronger
+    * SPEC (3) "Unless B is the content model wildcard of the �ur-type
+    * definition�, R's {process contents} must be identical to or stronger
     * than B's {process contents}, where strict is stronger than lax is
     * stronger than skip."
     */
@@ -16948,6 +16950,7 @@
     return (0);
 }
 
+#if 0
 /**
  * xmlSchemaCheckRCaseNSRecurseCheckCardinality:
  * @ctxt:  the schema parser context
@@ -16975,12 +16978,12 @@
     if ((r->children == NULL) || (r->children->children == NULL))
 	return (-1);
     /*
-    * SPEC "For a group particle to be a ·valid restriction· of a
+    * SPEC "For a group particle to be a �valid restriction� of a
     * wildcard particle..."
     *
-    * SPEC (1) "Every member of the {particles} of the group is a ·valid
-    * restriction· of the wildcard as defined by
-    * Particle Valid (Restriction) (§3.9.6)."
+    * SPEC (1) "Every member of the {particles} of the group is a �valid
+    * restriction� of the wildcard as defined by
+    * Particle Valid (Restriction) (�3.9.6)."
     */
     part = (xmlSchemaParticlePtr) r->children->children;
     do {
@@ -16991,7 +16994,7 @@
     /*
     * SPEC (2) "The effective total range of the group [...] is a
     * valid restriction of B's occurrence range as defined by
-    * Occurrence Range OK (§3.9.6)."
+    * Occurrence Range OK (�3.9.6)."
     */
     if (xmlSchemaCheckParticleRangeOK(
 	    xmlSchemaGetParticleTotalRangeMin(r),
@@ -17000,6 +17003,7 @@
 	return (1);
     return (0);
 }
+#endif
 
 /**
  * xmlSchemaCheckRCaseRecurse:
@@ -17030,11 +17034,11 @@
 	(r->children->type != b->children->type))
 	return (-1);
     /*
-    * SPEC "For an all or sequence group particle to be a ·valid
-    * restriction· of another group particle with the same {compositor}..."
+    * SPEC "For an all or sequence group particle to be a �valid
+    * restriction� of another group particle with the same {compositor}..."
     *
     * SPEC (1) "R's occurrence range is a valid restriction of B's
-    * occurrence range as defined by Occurrence Range OK (§3.9.6)."
+    * occurrence range as defined by Occurrence Range OK (�3.9.6)."
     */
     if (xmlSchemaCheckParticleRangeOK(r->minOccurs, r->maxOccurs,
 	    b->minOccurs, b->maxOccurs))
@@ -17131,7 +17135,7 @@
 
     /*
     * SPEC st-restrict-facets 1:
-    * "The {variety} of R is the same as that of B."    
+    * "The {variety} of R is the same as that of B."
     */
     /*
     * SPEC st-restrict-facets 2:
@@ -17603,7 +17607,7 @@
 			* The whitespace must be stronger.
 			*/
 			if (facet->whitespace < bfacet->whitespace) {
-			    FACET_RESTR_ERR(flength,
+			    FACET_RESTR_ERR(facet,
 				"The 'whitespace' value has to be equal to "
 				"or stronger than the 'whitespace' value of "
 				"the base type")
@@ -17658,7 +17662,7 @@
     xmlSchemaTypeLinkPtr link, lastLink, prevLink, subLink, newLink;
     /*
     * The actual value is then formed by replacing any union type
-    * definition in the ·explicit members· with the members of their
+    * definition in the �explicit members� with the members of their
     * {member type definitions}, in order.
     *
     * TODO: There's a bug entry at
@@ -17704,7 +17708,7 @@
 
 static void
 xmlSchemaTypeFixupOptimFacets(xmlSchemaTypePtr type)
-{       
+{
     int has = 0, needVal = 0, normVal = 0;
 
     has	= (type->baseType->flags & XML_SCHEMAS_TYPE_HAS_FACETS) ? 1 : 0;
@@ -17716,7 +17720,7 @@
     }
     if (type->facets != NULL) {
 	xmlSchemaFacetPtr fac;
-	
+
 	for (fac = type->facets; fac != NULL; fac = fac->next) {
 	    switch (fac->type) {
 		case XML_SCHEMA_FACET_WHITESPACE:
@@ -17734,7 +17738,7 @@
 		    has = 1;
 		    break;
 	    }
-	}	
+	}
     }
     if (normVal)
 	type->flags |= XML_SCHEMAS_TYPE_NORMVALUENEEDED;
@@ -17751,24 +17755,24 @@
 	if ((prim->builtInType != XML_SCHEMAS_ANYSIMPLETYPE) &&
 	    (prim->builtInType != XML_SCHEMAS_STRING)) {
 	    type->flags |= XML_SCHEMAS_TYPE_FACETSNEEDVALUE;
-	} 	
-    }       
+	}
+    }
 }
 
 static int
 xmlSchemaTypeFixupWhitespace(xmlSchemaTypePtr type)
 {
-    
-    
+
+
     /*
     * Evaluate the whitespace-facet value.
-    */    
+    */
     if (WXS_IS_LIST(type)) {
 	type->flags |= XML_SCHEMAS_TYPE_WHITESPACE_COLLAPSE;
 	return (0);
     } else if (WXS_IS_UNION(type))
 	return (0);
-    
+
     if (type->facetSet != NULL) {
 	xmlSchemaFacetLinkPtr lin;
 
@@ -17792,23 +17796,23 @@
 	}
     }
     /*
-    * For all ·atomic· datatypes other than string (and types ·derived· 
-    * by ·restriction· from it) the value of whiteSpace is fixed to 
+    * For all �atomic� datatypes other than string (and types �derived�
+    * by �restriction� from it) the value of whiteSpace is fixed to
     * collapse
     */
     {
 	xmlSchemaTypePtr anc;
 
-	for (anc = type->baseType; anc != NULL && 
+	for (anc = type->baseType; anc != NULL &&
 		anc->builtInType != XML_SCHEMAS_ANYTYPE;
 		anc = anc->baseType) {
 
 	    if (anc->type == XML_SCHEMA_TYPE_BASIC) {
-		if (anc->builtInType == XML_SCHEMAS_NORMSTRING) {	    
+		if (anc->builtInType == XML_SCHEMAS_NORMSTRING) {
 		    type->flags |= XML_SCHEMAS_TYPE_WHITESPACE_REPLACE;
 
 		} else if ((anc->builtInType == XML_SCHEMAS_STRING) ||
-		    (anc->builtInType == XML_SCHEMAS_ANYSIMPLETYPE)) {		    
+		    (anc->builtInType == XML_SCHEMAS_ANYSIMPLETYPE)) {
 		    type->flags |= XML_SCHEMAS_TYPE_WHITESPACE_PRESERVE;
 
 		} else
@@ -17845,7 +17849,7 @@
     } else if (WXS_IS_UNION(type)) {
 	/*
 	* Corresponds to <simpleType><union>...
-	*/	
+	*/
 	if (type->memberTypes == NULL) {
 	    /*
 	    * This one is really needed, so get out.
@@ -17853,8 +17857,8 @@
 	    PERROR_INT("xmlSchemaFixupSimpleTypeStageOne",
 		"union type has no member-types assigned");
 	    return(-1);
-	}	    
-    } else {    
+	}
+    } else {
 	/*
 	* Corresponds to <simpleType><restriction>...
 	*/
@@ -17969,7 +17973,7 @@
     }
     if (WXS_IS_TYPE_NOT_FIXED(type->baseType))
 	xmlSchemaTypeFixup(type->baseType, ACTXT_CAST pctxt);
-    /* 
+    /*
     * If a member type of a union is a union itself, we need to substitute
     * that member type for its member types.
     * NOTE that this might change in WXS 1.1; i.e. we will keep the union
@@ -17977,12 +17981,12 @@
     */
     if ((type->memberTypes != NULL) &&
 	(xmlSchemaFinishMemberTypeDefinitionsProperty(pctxt, type) == -1))
-	return(-1);        
+	return(-1);
     /*
-    * SPEC src-simple-type 1 
+    * SPEC src-simple-type 1
     * "The corresponding simple type definition, if any, must satisfy
     * the conditions set out in Constraints on Simple Type Definition
-    * Schema Components (§3.14.6)."
+    * Schema Components (�3.14.6)."
     */
     /*
     * Schema Component Constraint: Simple Type Definition Properties Correct
@@ -17990,7 +17994,7 @@
     */
     res = xmlSchemaCheckSTPropsCorrect(pctxt, type);
     HFAILURE HERROR
-    /* 
+    /*
     * Schema Component Constraint: Derivation Valid (Restriction, Simple)
     * (cos-st-restricts)
     */
@@ -18023,7 +18027,7 @@
     */
     res = xmlSchemaTypeFixupWhitespace(type);
     HFAILURE HERROR
-    xmlSchemaTypeFixupOptimFacets(type);    
+    xmlSchemaTypeFixupOptimFacets(type);
 
 exit_error:
 #ifdef DEBUG_TYPE
@@ -18054,7 +18058,7 @@
 	PERROR_INT("xmlSchemaFixupComplexType",
 	    "missing baseType");
 	goto exit_failure;
-    }    
+    }
     /*
     * Fixup the base type.
     */
@@ -18066,12 +18070,12 @@
 	* TODO: Generate a warning!
 	*/
 	return(0);
-    }	
+    }
     /*
     * This basically checks if the base type can be derived.
     */
     res = xmlSchemaCheckSRCCT(pctxt, type);
-    HFAILURE HERROR   
+    HFAILURE HERROR
     /*
     * Fixup the content type.
     */
@@ -18145,7 +18149,7 @@
 	    type->facets = NULL;
 	    content->facetSet = type->facetSet;
 	    type->facetSet = NULL;
-	    
+
 	    type->contentTypeDef = content;
 	    if (WXS_IS_TYPE_NOT_FIXED(contentBase))
 		xmlSchemaTypeFixup(contentBase, ACTXT_CAST pctxt);
@@ -18154,10 +18158,10 @@
 	    * for circularity here.
 	    */
 	    res = xmlSchemaFixupSimpleTypeStageOne(pctxt, content);
-	    HFAILURE HERROR 
+	    HFAILURE HERROR
 	    res = xmlSchemaFixupSimpleTypeStageTwo(pctxt, content);
-	    HFAILURE HERROR 
-		
+	    HFAILURE HERROR
+
 	} else if ((WXS_IS_COMPLEX(baseType)) &&
 	    (baseType->contentType == XML_SCHEMA_CONTENT_MIXED) &&
 	    (WXS_IS_RESTRICTION(type))) {
@@ -18242,7 +18246,7 @@
 	    ( ((xmlSchemaTreeItemPtr) particle->children)->children == NULL))) {
 	    if (type->flags & XML_SCHEMAS_TYPE_MIXED) {
 		/*
-		* SPEC (2.1.4) "If the ·effective mixed· is true, then
+		* SPEC (2.1.4) "If the �effective mixed� is true, then
 		* a particle whose properties are as follows:..."
 		*
 		* Empty sequence model group with
@@ -18267,7 +18271,7 @@
 			XML_SCHEMA_TYPE_SEQUENCE, type->node);
 		    if (particle->children == NULL)
 			goto exit_failure;
-		    
+
 		    type->subtypes = (xmlSchemaTypePtr) particle;
 		}
 		dummySequence = 1;
@@ -18304,7 +18308,7 @@
 	    if (type->contentType == XML_SCHEMA_CONTENT_EMPTY) {
 		/*
 		* SPEC (3.2.1)
-		* "If the ·effective content· is empty, then the
+		* "If the �effective content� is empty, then the
 		*  {content type} of the [...] base ..."
 		*/
 		type->contentType = baseType->contentType;
@@ -18411,7 +18415,7 @@
 		    particle->children =
 			((xmlSchemaParticlePtr) baseType->subtypes)->children;
 		    /*
-		    * SPEC "followed by the ·effective content·."
+		    * SPEC "followed by the �effective content�."
 		    */
 		    particle->next = effectiveContent;
 		    /*
@@ -18555,12 +18559,12 @@
 
 		/* 4.3.5.5 Constraints on enumeration Schema Components
 		* Schema Component Constraint: enumeration valid restriction
-		* It is an ·error· if any member of {value} is not in the
-		* ·value space· of {base type definition}.
+		* It is an �error� if any member of {value} is not in the
+		* �value space� of {base type definition}.
 		*
 		* minInclusive, maxInclusive, minExclusive, maxExclusive:
-		* The value ·must· be in the
-		* ·value space· of the ·base type·.
+		* The value �must� be in the
+		* �value space� of the �base type�.
 		*/
 		/*
 		* This function is intended to deliver a compiled value
@@ -18580,11 +18584,11 @@
 		    }
 		} else
 		    base = typeDecl;
-	                 
+
 		if (! ctxtGiven) {
 		    /*
 		    * A context is needed if called from RelaxNG.
-		    */		    
+		    */
 		    pctxt = xmlSchemaNewParserCtxt("*");
 		    if (pctxt == NULL)
 			return (-1);
@@ -18595,17 +18599,17 @@
 		* facet->node is just the node holding the facet
 		* definition, *not* the attribute holding the *value*
 		* of the facet.
-		*/		
+		*/
 		ret = xmlSchemaVCheckCVCSimpleType(
 		    ACTXT_CAST pctxt, facet->node, base,
 		    facet->value, &(facet->val), 1, 1, 0);
                 if (ret != 0) {
 		    if (ret < 0) {
 			/* No error message for RelaxNG. */
-			if (ctxtGiven) {			    
+			if (ctxtGiven) {
 			    xmlSchemaCustomErr(ACTXT_CAST pctxt,
 				XML_SCHEMAP_INTERNAL, facet->node, NULL,
-				"Internal error: xmlSchemaCheckFacet, " 
+				"Internal error: xmlSchemaCheckFacet, "
 				"failed to validate the value '%s' of the "
 				"facet '%s' against the base type",
 				facet->value, xmlSchemaFacetTypeToString(facet->type));
@@ -18680,17 +18684,17 @@
 		    /* error code */
 		    xmlSchemaCustomErr4(ACTXT_CAST pctxt,
 			ret, facet->node, WXS_BASIC_CAST typeDecl,
-			"The value '%s' of the facet '%s' is not a valid '%s'",			
+			"The value '%s' of the facet '%s' is not a valid '%s'",
 			facet->value,
 			xmlSchemaFacetTypeToString(facet->type),
-			(facet->type != XML_SCHEMA_FACET_TOTALDIGITS) ? 
+			(facet->type != XML_SCHEMA_FACET_TOTALDIGITS) ?
 			    BAD_CAST "nonNegativeInteger" :
 			    BAD_CAST "positiveInteger",
 			NULL);
 		}
 	    }
 	    break;
-            
+
         case XML_SCHEMA_FACET_WHITESPACE:{
                 if (xmlStrEqual(facet->value, BAD_CAST "preserve")) {
                     facet->whitespace = XML_SCHEMAS_FACET_PRESERVE;
@@ -18903,7 +18907,7 @@
 	{
 	    particle = WXS_PTC_CAST particle->next;
 	    continue;
-	} 
+	}
 	if (WXS_MODELGROUPDEF_MODEL(WXS_PARTICLE_TERM(particle)) == NULL) {
 	    /*
 	    * TODO: Remove the particle.
@@ -18953,7 +18957,7 @@
 	    if (gr == ctxtGr)
 		return(ref);
 	    if (gr->flags & XML_SCHEMAS_ATTRGROUP_MARKED)
-		continue;	    
+		continue;
 	    /*
 	    * Mark as visited to avoid infinite recursion on
 	    * circular references not yet examined.
@@ -18963,12 +18967,12 @@
 	    {
 		gr->flags |= XML_SCHEMAS_ATTRGROUP_MARKED;
 		circ = xmlSchemaCheckAttrGroupCircularRecur(ctxtGr,
-		    (xmlSchemaItemListPtr) gr->attrUses);		
+		    (xmlSchemaItemListPtr) gr->attrUses);
 		gr->flags ^= XML_SCHEMAS_ATTRGROUP_MARKED;
 		if (circ != NULL)
 		    return (circ);
 	    }
-	    
+
 	}
     }
     return (NULL);
@@ -18995,9 +18999,9 @@
     * not be an <attributeGroup> with ref [attribute] which resolves
     * to the component corresponding to this <attributeGroup>. Indirect
     * circularity is also ruled out. That is, when QName resolution
-    * (Schema Document) (§3.15.3) is applied to a ·QName· arising from
+    * (Schema Document) (�3.15.3) is applied to a �QName� arising from
     * any <attributeGroup>s with a ref [attribute] among the [children],
-    * it must not be the case that a ·QName· is encountered at any depth
+    * it must not be the case that a �QName� is encountered at any depth
     * which resolves to the component corresponding to this <attributeGroup>.
     */
     if (attrGr->attrUses == NULL)
@@ -19006,9 +19010,9 @@
 	return(0);
     else {
 	xmlSchemaQNameRefPtr circ;
-	
+
 	circ = xmlSchemaCheckAttrGroupCircularRecur(attrGr,
-	    (xmlSchemaItemListPtr) attrGr->attrUses);	
+	    (xmlSchemaItemListPtr) attrGr->attrUses);
 	if (circ != NULL) {
 	    xmlChar *str = NULL;
 	    /*
@@ -19040,7 +19044,7 @@
  * xmlSchemaExpandAttributeGroupRefs:
  * @pctxt: the parser context
  * @node: the node of the component holding the attribute uses
- * @completeWild: the intersected wildcard to be returned 
+ * @completeWild: the intersected wildcard to be returned
  * @list: the attribute uses
  *
  * Substitutes contained attribute group references
@@ -19069,7 +19073,7 @@
     for (i = 0; i < list->nbItems; i++) {
 	use = list->items[i];
 
-	if (use->type == XML_SCHEMA_EXTRA_ATTR_USE_PROHIB) {	    
+	if (use->type == XML_SCHEMA_EXTRA_ATTR_USE_PROHIB) {
 	    if (prohibs == NULL) {
 		PERROR_INT("xmlSchemaExpandAttributeGroupRefs",
 		    "unexpected attr prohibition found");
@@ -19084,7 +19088,7 @@
 	    /*
 	    * Note that duplicate prohibitions were already
 	    * handled at parsing time.
-	    */	    
+	    */
 	    /*
 	    * Add to list of prohibitions.
 	    */
@@ -19137,7 +19141,7 @@
 			*completeWild = tmpWild;
 			created = 1;
 		    }
-		    
+
 		    if (xmlSchemaIntersectWildcards(pctxt, *completeWild,
 			gr->attributeWildcard) == -1)
 			return(-1);
@@ -19211,7 +19215,7 @@
 /**
  * xmlSchemaAttributeGroupExpandRefs:
  * @pctxt:  the parser context
- * @attrGr:  the attribute group definition 
+ * @attrGr:  the attribute group definition
  *
  * Computation of:
  * {attribute uses} property
@@ -19223,7 +19227,7 @@
 static int
 xmlSchemaAttributeGroupExpandRefs(xmlSchemaParserCtxtPtr pctxt,
 				  xmlSchemaAttributeGroupPtr attrGr)
-{  
+{
     if ((attrGr->attrUses == NULL) ||
 	(attrGr->flags & XML_SCHEMAS_ATTRGROUP_WILDCARD_BUILDED))
 	return(0);
@@ -19231,33 +19235,33 @@
     attrGr->flags |= XML_SCHEMAS_ATTRGROUP_WILDCARD_BUILDED;
     if (xmlSchemaExpandAttributeGroupRefs(pctxt, WXS_BASIC_CAST attrGr,
 	&(attrGr->attributeWildcard), attrGr->attrUses, NULL) == -1)
-	return(-1);    
+	return(-1);
     return(0);
 }
 
 /**
  * xmlSchemaAttributeGroupExpandRefs:
  * @pctxt:  the parser context
- * @attrGr:  the attribute group definition 
+ * @attrGr:  the attribute group definition
  *
  * Substitutes contained attribute group references
  * for their attribute uses. Wilcards are intersected.
- * 
+ *
  * Schema Component Constraint:
- *    Attribute Group Definition Properties Correct (ag-props-correct) 
+ *    Attribute Group Definition Properties Correct (ag-props-correct)
  */
 static int
 xmlSchemaCheckAGPropsCorrect(xmlSchemaParserCtxtPtr pctxt,
 				  xmlSchemaAttributeGroupPtr attrGr)
-{  
+{
     /*
     * SPEC ag-props-correct
     * (1) "The values of the properties of an attribute group definition
     * must be as described in the property tableau in The Attribute
-    * Group Definition Schema Component (§3.6.1), modulo the impact of
-    * Missing Sub-components (§5.3);"
+    * Group Definition Schema Component (�3.6.1), modulo the impact of
+    * Missing Sub-components (�5.3);"
     */
-    
+
     if ((attrGr->attrUses != NULL) &&
 	(WXS_LIST_CAST attrGr->attrUses)->nbItems > 1)
     {
@@ -19266,7 +19270,7 @@
 	int i, j, hasId = 0;
 
 	for (i = uses->nbItems -1; i >= 0; i--) {
-	    use = uses->items[i];	    
+	    use = uses->items[i];
 	    /*
 	    * SPEC ag-props-correct
 	    * (2) "Two distinct members of the {attribute uses} must not have
@@ -19282,7 +19286,7 @@
 			WXS_ATTRUSE_DECL_TNS(tmp)))
 		    {
 			xmlChar *str = NULL;
-			
+
 			xmlSchemaCustomErr(ACTXT_CAST pctxt,
 			    XML_SCHEMAP_AG_PROPS_CORRECT,
 			    attrGr->node, WXS_BASIC_CAST attrGr,
@@ -19306,13 +19310,13 @@
 	    * are derived from ID."
 	    * TODO: Does 'derived' include member-types of unions?
 	    */
-	    if (WXS_ATTRUSE_TYPEDEF(use) != NULL) {		
+	    if (WXS_ATTRUSE_TYPEDEF(use) != NULL) {
 		if (xmlSchemaIsDerivedFromBuiltInType(
 		    WXS_ATTRUSE_TYPEDEF(use), XML_SCHEMAS_ID))
-		{		
+		{
 		    if (hasId) {
 			xmlChar *str = NULL;
-			
+
 			xmlSchemaCustomErr(ACTXT_CAST pctxt,
 			    XML_SCHEMAP_AG_PROPS_CORRECT,
 			    attrGr->node, WXS_BASIC_CAST attrGr,
@@ -19325,7 +19329,7 @@
 			FREE_AND_NULL(str);
 			if (xmlSchemaItemListRemove(uses, i) == -1)
 			    return(-1);
-		    }		    
+		    }
 		    hasId = 1;
 		}
 	    }
@@ -19389,10 +19393,10 @@
     * SPEC a-props-correct (1)
     * "The values of the properties of an attribute declaration must
     * be as described in the property tableau in The Attribute
-    * Declaration Schema Component (§3.2.1), modulo the impact of
-    * Missing Sub-components (§5.3)."
+    * Declaration Schema Component (�3.2.1), modulo the impact of
+    * Missing Sub-components (�5.3)."
     */
-    
+
     if (WXS_ATTR_TYPEDEF(attr) == NULL)
 	return(0);
 
@@ -19418,8 +19422,8 @@
 	/*
 	* SPEC a-props-correct (2)
 	* "if there is a {value constraint}, the canonical lexical
-	* representation of its value must be ·valid· with respect
-	* to the {type definition} as defined in String Valid (§3.14.4)."
+	* representation of its value must be �valid� with respect
+	* to the {type definition} as defined in String Valid (�3.14.4)."
 	* TODO: Don't care about the *cononical* stuff here, this requirement
 	* will be removed in WXS 1.1 anyway.
 	*/
@@ -19441,7 +19445,7 @@
 	    return(pctxt->err);
 	}
     }
-   
+
     return(0);
 }
 
@@ -19487,15 +19491,15 @@
     /*
     * SPEC (1) "The values of the properties of an element declaration
     * must be as described in the property tableau in The Element
-    * Declaration Schema Component (§3.3.1), modulo the impact of Missing
-    * Sub-components (§5.3)."
+    * Declaration Schema Component (�3.3.1), modulo the impact of Missing
+    * Sub-components (�5.3)."
     */
     if (WXS_SUBST_HEAD(elemDecl) != NULL) {
 	xmlSchemaElementPtr head = WXS_SUBST_HEAD(elemDecl), circ;
 
 	xmlSchemaCheckElementDeclComponent(head, pctxt);
 	/*
-	* SPEC (3) "If there is a non-·absent· {substitution group
+	* SPEC (3) "If there is a non-�absent� {substitution group
 	* affiliation}, then {scope} must be global."
 	*/
 	if ((elemDecl->flags & XML_SCHEMAS_ELEM_GLOBAL) == 0) {
@@ -19539,9 +19543,9 @@
 	* of the element declaration must be validly derived from the {type
 	* definition} of the {substitution group affiliation}, given the value
 	* of the {substitution group exclusions} of the {substitution group
-	* affiliation}, as defined in Type Derivation OK (Complex) (§3.4.6)
+	* affiliation}, as defined in Type Derivation OK (Complex) (�3.4.6)
 	* (if the {type definition} is complex) or as defined in
-	* Type Derivation OK (Simple) (§3.14.6) (if the {type definition} is
+	* Type Derivation OK (Simple) (�3.14.6) (if the {type definition} is
 	* simple)."
 	*
 	* NOTE: {substitution group exclusions} means the values of the
@@ -19605,9 +19609,9 @@
 
 	/*
 	* SPEC (2) "If there is a {value constraint}, the canonical lexical
-	* representation of its value must be ·valid· with respect to the
+	* representation of its value must be �valid� with respect to the
 	* {type definition} as defined in Element Default Valid (Immediate)
-	* (§3.3.6)."
+	* (�3.3.6)."
 	*/
 	if (typeDef == NULL) {
 	    xmlSchemaPErr(pctxt, elemDecl->node,
@@ -19675,7 +19679,7 @@
 	/*
 	* SPEC (2) "It is validly substitutable for HEAD subject to HEAD's
 	* {disallowed substitutions} as the blocking constraint, as defined in
-	* Substitution Group OK (Transitive) (§3.3.6)."
+	* Substitution Group OK (Transitive) (�3.3.6)."
 	*/
 	for (head = WXS_SUBST_HEAD(elemDecl); head != NULL;
 	    head = WXS_SUBST_HEAD(head)) {
@@ -19767,12 +19771,12 @@
  * @ctxtParticle: the first particle of the context component
  * @searchParticle: the element declaration particle to be analysed
  *
- * Schema Component Constraint: Element Declarations Consistent 
+ * Schema Component Constraint: Element Declarations Consistent
  */
 static int
 xmlSchemaCheckElementDeclConsistent(xmlSchemaParserCtxtPtr pctxt,
 				    xmlSchemaBasicItemPtr ctxtComponent,
-				    xmlSchemaParticlePtr ctxtParticle,				    
+				    xmlSchemaParticlePtr ctxtParticle,
 				    xmlSchemaParticlePtr searchParticle,
 				    xmlSchemaParticlePtr curParticle,
 				    int search)
@@ -19781,7 +19785,7 @@
 
     int ret = 0;
     xmlSchemaParticlePtr cur = curParticle;
-    if (curParticle == NULL) {	
+    if (curParticle == NULL) {
 	return(0);
     }
     if (WXS_PARTICLE_TERM(curParticle) == NULL) {
@@ -19790,7 +19794,7 @@
 	* might arise due to an invalid "term" component.
 	*/
 	return(0);
-    }    
+    }
     while (cur != NULL) {
 	switch (WXS_PARTICLE_TERM(cur)->type) {
 	    case XML_SCHEMA_TYPE_ANY:
@@ -19800,7 +19804,7 @@
 		    ret = xmlSchemaCheckElementDeclConsistent(pctxt,
 			ctxtComponent, ctxtParticle, cur, ctxtParticle, 1);
 		    if (ret != 0)
-			return(ret);		    
+			return(ret);
 		} else {
 		    xmlSchemaElementPtr elem =
 			WXS_ELEM_CAST(WXS_PARTICLE_TERM(cur));
@@ -19808,7 +19812,7 @@
 		    * SPEC Element Declarations Consistent:
 		    * "If the {particles} contains, either directly,
 		    * indirectly (that is, within the {particles} of a
-		    * contained model group, recursively) or ·implicitly·
+		    * contained model group, recursively) or �implicitly�
 		    * two or more element declaration particles with
 		    * the same {name} and {target namespace}, then
 		    * all their type definitions must be the same
@@ -19820,7 +19824,7 @@
 			    WXS_PARTICLE_TERM_AS_ELEM(searchParticle)->targetNamespace))
 		    {
 			xmlChar *strA = NULL, *strB = NULL;
-			
+
 			xmlSchemaCustomErr(ACTXT_CAST pctxt,
 			    /* TODO: error code */
 			    XML_SCHEMAP_COS_NONAMBIG,
@@ -19837,16 +19841,16 @@
 			FREE_AND_NULL(strB);
 			return(XML_SCHEMAP_COS_NONAMBIG);
 		    }
-		}	    
+		}
 		break;
-	    case XML_SCHEMA_TYPE_SEQUENCE: {		
+	    case XML_SCHEMA_TYPE_SEQUENCE: {
 		break;
 		}
 	    case XML_SCHEMA_TYPE_CHOICE:{
 		/*
 		xmlSchemaTreeItemPtr sub;
-		
-		sub = WXS_PARTICLE_TERM(particle)->children;  (xmlSchemaParticlePtr) 
+
+		sub = WXS_PARTICLE_TERM(particle)->children;  (xmlSchemaParticlePtr)
 		while (sub != NULL) {
 		    ret = xmlSchemaCheckElementDeclConsistent(pctxt, ctxtComponent,
 			ctxtParticle, ctxtElem);
@@ -19883,7 +19887,7 @@
  * @name:  the name of the attribute
  *
  * Validates the value constraints of an element declaration.
- * Adds substitution group members. 
+ * Adds substitution group members.
  */
 static void
 xmlSchemaCheckElementDeclComponent(xmlSchemaElementPtr elemDecl,
@@ -19898,7 +19902,7 @@
 	/*
 	* Adds substitution group members.
 	*/
-	xmlSchemaCheckElemSubstGroup(ctxt, elemDecl);	
+	xmlSchemaCheckElemSubstGroup(ctxt, elemDecl);
     }
 }
 
@@ -19928,7 +19932,7 @@
 		XML_SCHEMA_EXTRA_QNAMEREF))
 	{
 	    goto next_particle;
-	} 
+	}
 	ref = WXS_QNAME_CAST WXS_PARTICLE_TERM(particle);
 	/*
 	* Resolve the reference.
@@ -19944,7 +19948,7 @@
 		ref->targetNamespace, ref->itemType, NULL);
 	    /* TODO: remove the particle. */
 	    goto next_particle;
-	} 
+	}
 	if (refItem->type == XML_SCHEMA_TYPE_GROUP) {
 	    if (WXS_MODELGROUPDEF_MODEL(refItem) == NULL)
 		/* TODO: remove the particle. */
@@ -19994,9 +19998,9 @@
 
 static int
 xmlSchemaAreValuesEqual(xmlSchemaValPtr x,
-		       xmlSchemaValPtr y) 
-{   
-    xmlSchemaTypePtr tx, ty, ptx, pty;    
+		       xmlSchemaValPtr y)
+{
+    xmlSchemaTypePtr tx, ty, ptx, pty;
     int ret;
 
     while (x != NULL) {
@@ -20006,12 +20010,12 @@
 	ptx = xmlSchemaGetPrimitiveType(tx);
 	pty = xmlSchemaGetPrimitiveType(ty);
 	/*
-	* (1) if a datatype T' is ·derived· by ·restriction· from an
-	* atomic datatype T then the ·value space· of T' is a subset of
-	* the ·value space· of T. */
+	* (1) if a datatype T' is �derived� by �restriction� from an
+	* atomic datatype T then the �value space� of T' is a subset of
+	* the �value space� of T. */
 	/*
-	* (2) if datatypes T' and T'' are ·derived· by ·restriction·
-	* from a common atomic ancestor T then the ·value space·s of T'
+	* (2) if datatypes T' and T'' are �derived� by �restriction�
+	* from a common atomic ancestor T then the �value space�s of T'
 	* and T'' may overlap.
 	*/
 	if (ptx != pty)
@@ -20042,7 +20046,7 @@
 	if (x != NULL) {
 	    y = xmlSchemaValueGetNext(y);
 	    if (y == NULL)
-		return (0);	    
+		return (0);
 	} else if (xmlSchemaValueGetNext(y) != NULL)
 	    return (0);
 	else
@@ -20092,11 +20096,11 @@
 /**
  * xmlSchemaCheckAttrUsePropsCorrect:
  * @ctxt:  a parser context
- * @use:  an attribute use 
+ * @use:  an attribute use
  *
  * Schema Component Constraint:
  * Attribute Use Correct (au-props-correct)
- * 
+ *
  */
 static int
 xmlSchemaCheckAttrUsePropsCorrect(xmlSchemaParserCtxtPtr ctxt,
@@ -20106,16 +20110,16 @@
 	return(-1);
     if ((use->defValue == NULL) || (WXS_ATTRUSE_DECL(use) == NULL) ||
 	((WXS_ATTRUSE_DECL(use))->type != XML_SCHEMA_TYPE_ATTRIBUTE))
-	return(0);	
+	return(0);
 
     /*
     * SPEC au-props-correct (1)
     * "The values of the properties of an attribute use must be as
     * described in the property tableau in The Attribute Use Schema
-    * Component (§3.5.1), modulo the impact of Missing
-    * Sub-components (§5.3)."
+    * Component (�3.5.1), modulo the impact of Missing
+    * Sub-components (�5.3)."
     */
-    
+
     if (((WXS_ATTRUSE_DECL(use))->defValue != NULL) &&
 	((WXS_ATTRUSE_DECL(use))->flags & XML_SCHEMAS_ATTR_FIXED) &&
         ((use->flags & XML_SCHEMA_ATTR_USE_FIXED) == 0))
@@ -20135,7 +20139,7 @@
     if ((use->defVal != NULL) && (WXS_ATTRUSE_TYPEDEF(use) != NULL)) {
 	int ret;
 	/*
-	* TODO: The spec seems to be missing a check of the 
+	* TODO: The spec seems to be missing a check of the
 	* value constraint of the attribute use. We will do it here.
 	*/
 	/*
@@ -20152,7 +20156,7 @@
 		NULL, NULL);
 	    return(ctxt->err);
 	}
-	
+
 	ret = xmlSchemaVCheckCVCSimpleType(ACTXT_CAST ctxt,
 	    use->node, WXS_ATTRUSE_TYPEDEF(use),
 	    use->defValue, &(use->defVal),
@@ -20203,7 +20207,7 @@
 /**
  * xmlSchemaResolveAttrTypeReferences:
  * @item:  an attribute declaration
- * @ctxt:  a parser context 
+ * @ctxt:  a parser context
  *
  * Resolves the referenced type definition component.
  */
@@ -20214,8 +20218,8 @@
     /*
     * The simple type definition corresponding to the <simpleType> element
     * information item in the [children], if present, otherwise the simple
-    * type definition ·resolved· to by the ·actual value· of the type
-    * [attribute], if present, otherwise the ·simple ur-type definition·.
+    * type definition �resolved� to by the �actual value� of the type
+    * [attribute], if present, otherwise the �simple ur-type definition�.
     */
     if (item->flags & XML_SCHEMAS_ATTR_INTERNAL_RESOLVED)
 	return(0);
@@ -20294,7 +20298,7 @@
 		((xmlSchemaIDCPtr) idc->ref->item)->nbFields) {
 		xmlChar *str = NULL;
 		xmlSchemaIDCPtr refer;
-		
+
 		refer = (xmlSchemaIDCPtr) idc->ref->item;
 		/*
 		* SPEC c-props-correct(2)
@@ -20353,7 +20357,7 @@
     int wasRedefined;
 
     if (redef == NULL)
-	return(0);   	
+	return(0);
 
     do {
 	item = redef->item;
@@ -20368,7 +20372,7 @@
 	*   <redefine>d schema. Currenlty we latter approach is used.
 	*   SUPPLEMENT: It seems that the WG moves towards the latter
 	*   approach, so we are doing it right.
-	*   
+	*
 	*/
 	prev = xmlSchemaFindRedefCompInGraph(
 	    redef->targetBucket, item->type,
@@ -20379,11 +20383,11 @@
 
 	    /*
 	    * SPEC src-redefine:
-	    * (6.2.1) "The ·actual value· of its own name attribute plus
-	    * target namespace must successfully ·resolve· to a model
+	    * (6.2.1) "The �actual value� of its own name attribute plus
+	    * target namespace must successfully �resolve� to a model
 	    * group definition in I."
-	    * (7.2.1) "The ·actual value· of its own name attribute plus
-	    * target namespace must successfully ·resolve· to an attribute
+	    * (7.2.1) "The �actual value� of its own name attribute plus
+	    * target namespace must successfully �resolve� to an attribute
 	    * group definition in I."
 
 	    *
@@ -20400,7 +20404,7 @@
 		/*
 		* TODO: error code.
 		* Probably XML_SCHEMAP_SRC_RESOLVE, if this is using the
-		* reference kind.		
+		* reference kind.
 		*/
 		XML_SCHEMAP_SRC_REDEFINE, node, NULL,
 		"The %s '%s' to be redefined could not be found in "
@@ -20408,7 +20412,7 @@
 		WXS_ITEM_TYPE_NAME(item),
 		xmlSchemaFormatQName(&str, redef->refTargetNs,
 		    redef->refName));
-	    FREE_AND_NULL(str);	    
+	    FREE_AND_NULL(str);
 	    err = pctxt->err;
 	    redef = redef->next;
 	    continue;
@@ -20434,7 +20438,7 @@
 		* base type of the redefining type.
 		* TODO: How
 		*/
-		((xmlSchemaTypePtr) item)->baseType = 
+		((xmlSchemaTypePtr) item)->baseType =
 		    (xmlSchemaTypePtr) prev;
 		break;
 	    case XML_SCHEMA_TYPE_GROUP:
@@ -20489,7 +20493,7 @@
 	    default:
 		PERROR_INT("xmlSchemaResolveRedefReferences",
 		    "Unexpected redefined component type");
-		return(-1);	
+		return(-1);
 	}
 	if (wasRedefined) {
 	    xmlChar *str = NULL;
@@ -20499,7 +20503,7 @@
 		node = WXS_ITEM_NODE(redef->reference);
 	    else
 		node = WXS_ITEM_NODE(redef->item);
-	    
+
 	    xmlSchemaCustomErr(ACTXT_CAST pctxt,
 		/* TODO: error code. */
 		XML_SCHEMAP_SRC_REDEFINE,
@@ -20508,12 +20512,12 @@
 		"redefinition of the same component is not supported",
 		xmlSchemaGetComponentDesignation(&str, prev),
 		NULL);
-	    FREE_AND_NULL(str)	    
+	    FREE_AND_NULL(str)
 	    err = pctxt->err;
 	    redef = redef->next;
 	    continue;
 	}
-	redef = redef->next;	
+	redef = redef->next;
     } while (redef != NULL);
 
     return(err);
@@ -20527,7 +20531,7 @@
     xmlSchemaBasicItemPtr item;
 
     if (redef == NULL)
-	return(0);   	
+	return(0);
 
     do {
 	if (redef->target == NULL) {
@@ -20535,7 +20539,7 @@
 	    continue;
 	}
 	item = redef->item;
-		
+
 	switch (item->type) {
 	    case XML_SCHEMA_TYPE_SIMPLE:
 	    case XML_SCHEMA_TYPE_COMPLEX:
@@ -20544,7 +20548,7 @@
 		* type to be 'absent', we'll NULL it.
 		*/
 		(WXS_TYPE_CAST redef->target)->name = NULL;
-		
+
 		/*
 		* TODO: Seems like there's nothing more to do. The normal
 		* inheritance mechanism is used. But not 100% sure.
@@ -20556,10 +20560,10 @@
 		* SPEC src-redefine:
 		* (6.2.2) "The {model group} of the model group definition
 		* which corresponds to it per XML Representation of Model
-		* Group Definition Schema Components (§3.7.2) must be a
-		* ·valid restriction· of the {model group} of that model
+		* Group Definition Schema Components (�3.7.2) must be a
+		* �valid restriction� of the {model group} of that model
 		* group definition in I, as defined in Particle Valid
-		* (Restriction) (§3.9.6)."
+		* (Restriction) (�3.9.6)."
 		*/
 		break;
 	    case XML_SCHEMA_TYPE_ATTRIBUTEGROUP:
@@ -20568,11 +20572,11 @@
 		* (7.2.2) "The {attribute uses} and {attribute wildcard} of
 		* the attribute group definition which corresponds to it
 		* per XML Representation of Attribute Group Definition Schema
-		* Components (§3.6.2) must be ·valid restrictions· of the
+		* Components (�3.6.2) must be �valid restrictions� of the
 		* {attribute uses} and {attribute wildcard} of that attribute
 		* group definition in I, as defined in clause 2, clause 3 and
 		* clause 4 of Derivation Valid (Restriction, Complex)
-		* (§3.4.6) (where references to the base type definition are
+		* (�3.4.6) (where references to the base type definition are
 		* understood as references to the attribute group definition
 		* in I)."
 		*/
@@ -20593,7 +20597,7 @@
     } while (redef != NULL);
     return(0);
 }
-	
+
 
 static int
 xmlSchemaAddComponents(xmlSchemaParserCtxtPtr pctxt,
@@ -20627,8 +20631,8 @@
 	return(-1);
     if (bucket->flags & XML_SCHEMA_BUCKET_COMPS_ADDED)
 	return(0);
-    bucket->flags |= XML_SCHEMA_BUCKET_COMPS_ADDED; 
-    
+    bucket->flags |= XML_SCHEMA_BUCKET_COMPS_ADDED;
+
     for (i = 0; i < bucket->globals->nbItems; i++) {
 	item = bucket->globals->items[i];
 	table = NULL;
@@ -20669,12 +20673,12 @@
 	    case XML_SCHEMA_TYPE_NOTATION:
 		name = ((xmlSchemaNotationPtr) item)->name;
 		WXS_GET_GLOBAL_HASH(bucket, notaDecl)
-		break;	    
+		break;
 	    default:
 		PERROR_INT("xmlSchemaAddComponents",
 		    "Unexpected global component type");
-		continue;    		
-	}	
+		continue;
+	}
 	if (*table == NULL) {
 	    *table = xmlHashCreateDict(10, pctxt->dict);
 	    if (*table == NULL) {
@@ -20682,11 +20686,11 @@
 		    "failed to create a component hash table");
 		return(-1);
 	    }
-	}	
+	}
 	err = xmlHashAddEntry(*table, name, item);
-	if (err != 0) {	
+	if (err != 0) {
 	    xmlChar *str = NULL;
-	    
+
 	    xmlSchemaCustomErr(ACTXT_CAST pctxt,
 		XML_SCHEMAP_REDEFINED_TYPE,
 		WXS_ITEM_NODE(item),
@@ -20694,7 +20698,7 @@
 		"A global %s '%s' does already exist",
 		WXS_ITEM_TYPE_NAME(item),
 		xmlSchemaGetComponentQName(&str, item));
-	    FREE_AND_NULL(str);	 
+	    FREE_AND_NULL(str);
 	}
     }
     /*
@@ -20728,34 +20732,34 @@
 
     if ((con->pending == NULL) ||
 	(con->pending->nbItems == 0))
-	return(0);    
+	return(0);
 
     /*
     * Since xmlSchemaFixupComplexType() will create new particles
     * (local components), and those particle components need a bucket
     * on the constructor, we'll assure here that the constructor has
     * a bucket.
-    * TODO: Think about storing locals _only_ on the main bucket.    
-    */    
+    * TODO: Think about storing locals _only_ on the main bucket.
+    */
     if (con->bucket == NULL)
-	con->bucket = rootBucket;    
+	con->bucket = rootBucket;
 
     /* TODO:
     * SPEC (src-redefine):
     * (6.2) "If it has no such self-reference, then all of the
     * following must be true:"
-    
+
     * (6.2.2) The {model group} of the model group definition which
     * corresponds to it per XML Representation of Model Group
-    * Definition Schema Components (§3.7.2) must be a ·valid
-    * restriction· of the {model group} of that model group definition
-    * in I, as defined in Particle Valid (Restriction) (§3.9.6)."
+    * Definition Schema Components (�3.7.2) must be a �valid
+    * restriction� of the {model group} of that model group definition
+    * in I, as defined in Particle Valid (Restriction) (�3.9.6)."
     */
     xmlSchemaCheckSRCRedefineFirst(pctxt);
 
     /*
     * Add global components to the schemata's hash tables.
-    */    
+    */
     xmlSchemaAddComponents(pctxt, rootBucket);
 
     pctxt->ctxtType = NULL;
@@ -20765,7 +20769,7 @@
     * Now that we have parsed *all* the schema document(s) and converted
     * them to schema components, we can resolve references, apply component
     * constraints, create the FSA from the content model, etc.
-    */    
+    */
     /*
     * Resolve references of..
     *
@@ -20786,7 +20790,7 @@
     * 6. IDC key-references:
     *   - the referenced IDC 'key' or 'unique' definition
     * 7. Attribute prohibitions which had a "ref" attribute.
-    */        
+    */
     for (i = 0; i < nbItems; i++) {
 	item = items[i];
 	switch (item->type) {
@@ -20812,7 +20816,7 @@
 		FIXHFAILURE;
 		break;
 	    case XML_SCHEMA_EXTRA_QNAMEREF:
-		if ((WXS_QNAME_CAST item)->itemType == 
+		if ((WXS_QNAME_CAST item)->itemType ==
 		    XML_SCHEMA_TYPE_ATTRIBUTEGROUP)
 		{
 		    xmlSchemaResolveAttrGroupReferences(
@@ -20849,11 +20853,11 @@
     }
     if (pctxt->nberrors != 0)
 	goto exit_error;
-    
+
     /*
     * Now that all references are resolved we
     * can check for circularity of...
-    * 1. the base axis of type definitions 
+    * 1. the base axis of type definitions
     * 2. nested model group definitions
     * 3. nested attribute group definitions
     * TODO: check for circual substitution groups.
@@ -20888,7 +20892,7 @@
 		break;
 	    default:
 		break;
-	}	
+	}
     }
     if (pctxt->nberrors != 0)
 	goto exit_error;
@@ -20904,7 +20908,7 @@
 	item = items[i];
 	switch (item->type) {
 	    case XML_SCHEMA_TYPE_SEQUENCE:
-	    case XML_SCHEMA_TYPE_CHOICE:	
+	    case XML_SCHEMA_TYPE_CHOICE:
 		xmlSchemaModelGroupToModelGroupDefFixup(pctxt,
 		    WXS_MODEL_GROUP_CAST item);
 		break;
@@ -20935,7 +20939,7 @@
     }
     if (pctxt->nberrors != 0)
 	goto exit_error;
-    /* 
+    /*
     * First compute the variety of simple types. This is needed as
     * a seperate step, since otherwise we won't be able to detect
     * circular union types in all cases.
@@ -20965,7 +20969,7 @@
 	switch (item->type) {
             case XML_SCHEMA_TYPE_SIMPLE:
 		if (((xmlSchemaTypePtr) item)->memberTypes != NULL) {
-		    xmlSchemaCheckUnionTypeDefCircular(pctxt,	
+		    xmlSchemaCheckUnionTypeDefCircular(pctxt,
 			(xmlSchemaTypePtr) item);
 		    FIXHFAILURE;
 		}
@@ -20976,7 +20980,7 @@
     }
     if (pctxt->nberrors != 0)
 	goto exit_error;
-    
+
     /*
     * Do the complete type fixup for simple types.
     */
@@ -21004,10 +21008,10 @@
     for (i = 0; i < nbItems; i++) {
 	item = items[i];
 	switch (item->type) {
-	    case XML_SCHEMA_TYPE_ATTRIBUTE:		
+	    case XML_SCHEMA_TYPE_ATTRIBUTE:
 		xmlSchemaCheckAttrPropsCorrect(pctxt, WXS_ATTR_CAST item);
 		FIXHFAILURE;
-		break;	    
+		break;
 	    default:
 		break;
 	}
@@ -21016,7 +21020,7 @@
 	goto exit_error;
     /*
     * Apply constraints for attribute uses.
-    */    
+    */
     for (i = 0; i < nbItems; i++) {
 	item = items[i];
 	switch (item->type) {
@@ -21063,7 +21067,7 @@
     if (pctxt->nberrors != 0)
 	goto exit_error;
 
-    /*    
+    /*
     * Complex types are builded and checked.
     */
     for (i = 0; i < nbItems; i++) {
@@ -21087,8 +21091,8 @@
     * will create particles and model groups in some cases.
     */
     items = (xmlSchemaTreeItemPtr *) con->pending->items;
-    nbItems = con->pending->nbItems;    
-    
+    nbItems = con->pending->nbItems;
+
     /*
     * Apply some constraints for element declarations.
     */
@@ -21097,7 +21101,7 @@
 	switch (item->type) {
 	    case XML_SCHEMA_TYPE_ELEMENT:
 		elemDecl = (xmlSchemaElementPtr) item;
-		
+
 		if ((elemDecl->flags & XML_SCHEMAS_ELEM_INTERNAL_CHECKED) == 0)
 		{
 		    xmlSchemaCheckElementDeclComponent(
@@ -21127,7 +21131,7 @@
     }
     if (pctxt->nberrors != 0)
 	goto exit_error;
- 
+
     /*
     * Finally we can build the automaton from the content model of
     * complex types.
@@ -21148,10 +21152,10 @@
 	goto exit_error;
     /*
     * URGENT TODO: cos-element-consistent
-    */        
-    goto exit;    
+    */
+    goto exit;
 
-exit_error:    
+exit_error:
     ret = pctxt->err;
     goto exit;
 
@@ -21165,12 +21169,12 @@
     * if not cleared here.
     */
     con->bucket = oldbucket;
-    con->pending->nbItems = 0;    
+    con->pending->nbItems = 0;
     if (con->substGroups != NULL) {
 	xmlHashFree(con->substGroups,
 	    (xmlHashDeallocator) xmlSchemaSubstGroupFree);
 	con->substGroups = NULL;
-    }    
+    }
     if (con->redefs != NULL) {
 	xmlSchemaRedefListFree(con->redefs);
 	con->redefs = NULL;
@@ -21233,11 +21237,11 @@
     if (res == -1)
 	goto exit_failure;
     if (res != 0)
-	goto exit;   
+	goto exit;
 
     if (bucket == NULL) {
 	/* TODO: Error code, actually we failed to *locate* the schema. */
-	if (ctxt->URL) 
+	if (ctxt->URL)
 	    xmlSchemaCustomErr(ACTXT_CAST ctxt, XML_SCHEMAP_FAILED_LOAD,
 		NULL, NULL,
 		"Failed to locate the main schema resource at '%s'",
@@ -21248,16 +21252,16 @@
 		"Failed to locate the main schema resource",
 		    NULL, NULL);
 	goto exit;
-    }        
+    }
     /* Then do the parsing for good. */
     if (xmlSchemaParseNewDocWithContext(ctxt, mainSchema, bucket) == -1)
 	goto exit_failure;
     if (ctxt->nberrors != 0)
 	goto exit;
-    
+
     mainSchema->doc = bucket->doc;
     mainSchema->preserve = ctxt->preserve;
-    
+
     ctxt->schema = mainSchema;
 
     if (xmlSchemaFixupComponents(ctxt, WXS_CONSTRUCTOR(ctxt)->mainBucket) == -1)
@@ -21267,8 +21271,8 @@
     * TODO: This is not nice, since we cannot distinguish from the
     * result if there was an internal error or not.
     */
-exit:       
-    if (ctxt->nberrors != 0) {	
+exit:
+    if (ctxt->nberrors != 0) {
 	if (mainSchema) {
 	    xmlSchemaFree(mainSchema);
 	    mainSchema = NULL;
@@ -21282,7 +21286,7 @@
     ctxt->schema = NULL;
     return(mainSchema);
 exit_failure:
-    /* 
+    /*
     * Quite verbose, but should catch internal errors, which were
     * not communitated.
     */
@@ -21296,7 +21300,7 @@
 	ctxt->ownsConstructor = 0;
     }
     PERROR_INT2("xmlSchemaParse",
-	"An internal error occured");    
+	"An internal error occured");
     ctxt->schema = NULL;
     return(NULL);
 }
@@ -21433,8 +21437,8 @@
 	    return(XML_SCHEMA_WHITESPACE_REPLACE);
 	else {
 	    /*
-	    * For all ·atomic· datatypes other than string (and types ·derived·
-	    * by ·restriction· from it) the value of whiteSpace is fixed to
+	    * For all �atomic� datatypes other than string (and types �derived�
+	    * by �restriction� from it) the value of whiteSpace is fixed to
 	    * collapse
 	    * Note that this includes built-in list datatypes.
 	    */
@@ -21521,11 +21525,11 @@
     * XML_SCHEMA_SCHEMA_MAIN if it is the first schema document.
     */
     ret = xmlSchemaAddSchemaDoc(pctxt, XML_SCHEMA_SCHEMA_IMPORT,
-	location, NULL, NULL, 0, node, NULL, nsName, 
+	location, NULL, NULL, 0, node, NULL, nsName,
 	&bucket);
     if (ret != 0)
-	return(ret);    
-    if (bucket == NULL) {	
+	return(ret);
+    if (bucket == NULL) {
 	/*
 	* Generate a warning that the document could not be located.
 	*/
@@ -21555,17 +21559,17 @@
     pctxt->nberrors = 0;
     pctxt->err = 0;
     pctxt->doc = bucket->doc;
-    
-    ret = xmlSchemaParseNewDocWithContext(pctxt, schema, bucket);        
+
+    ret = xmlSchemaParseNewDocWithContext(pctxt, schema, bucket);
     if (ret == -1) {
 	pctxt->doc = NULL;
 	goto exit_failure;
     }
     /* Paranoid error channelling. */
     if ((ret == 0) && (pctxt->nberrors != 0))
-	ret = pctxt->err;    
-    if (pctxt->nberrors == 0) {	
-	/* 
+	ret = pctxt->err;
+    if (pctxt->nberrors == 0) {
+	/*
 	* Only bother to fixup pending components, if there was
 	* no error yet.
 	* For every XSI acquired schema (and its sub-schemata) we will
@@ -21581,7 +21585,7 @@
 	    vctxt->err = ret;
 	vctxt->nberrors += pctxt->nberrors;
     } else {
-	/* Add to validation error sum. */ 
+	/* Add to validation error sum. */
 	vctxt->nberrors += pctxt->nberrors;
     }
     pctxt->doc = NULL;
@@ -21592,7 +21596,7 @@
 }
 
 static xmlSchemaAttrInfoPtr
-xmlSchemaGetMetaAttrInfo(xmlSchemaValidCtxtPtr vctxt,		      
+xmlSchemaGetMetaAttrInfo(xmlSchemaValidCtxtPtr vctxt,
 			 int metaType)
 {
     if (vctxt->nbAttrInfos == 0)
@@ -21682,7 +21686,7 @@
 		/*
 		* If using @schemaLocation then tuples are expected.
 		* I.e. the namespace name *and* the document's URI.
-		*/		
+		*/
 		xmlSchemaCustomWarning(ACTXT_CAST vctxt, XML_SCHEMAV_MISC,
 		    iattr->node, NULL,
 		    "The value must consist of tuples: the target namespace "
@@ -21711,7 +21715,7 @@
     if (vctxt->sax != NULL) {
 	int i, j;
 	xmlSchemaNodeInfoPtr inode;
-	
+
 	for (i = vctxt->depth; i >= 0; i--) {
 	    if (vctxt->elemInfos[i]->nbNsBindings != 0) {
 		inode = vctxt->elemInfos[i];
@@ -21725,16 +21729,16 @@
 			* Note that the namespace bindings are already
 			* in a string dict.
 			*/
-			return (inode->nsBindings[j+1]);			
+			return (inode->nsBindings[j+1]);
 		    }
 		}
 	    }
 	}
 	return (NULL);
-#ifdef LIBXML_WRITER_ENABLED
+#ifdef LIBXML_READER_ENABLED
     } else if (vctxt->reader != NULL) {
 	xmlChar *nsName;
-	
+
 	nsName = xmlTextReaderLookupNamespace(vctxt->reader, prefix);
 	if (nsName != NULL) {
 	    const xmlChar *ret;
@@ -21766,7 +21770,7 @@
 * This one works on the schema of the validation context.
 */
 static int
-xmlSchemaValidateNotation(xmlSchemaValidCtxtPtr vctxt, 			  
+xmlSchemaValidateNotation(xmlSchemaValidCtxtPtr vctxt,
 			  xmlSchemaPtr schema,
 			  xmlNodePtr node,
 			  const xmlChar *value,
@@ -21791,7 +21795,7 @@
 	if (prefix != NULL) {
 	    const xmlChar *nsName = NULL;
 
-	    if (vctxt != NULL) 
+	    if (vctxt != NULL)
 		nsName = xmlSchemaLookupNamespace(vctxt, BAD_CAST prefix);
 	    else if (node != NULL) {
 		xmlNsPtr ns = xmlSearchNs(node->doc, node, prefix);
@@ -21808,9 +21812,9 @@
 		return (1);
 	    }
 	    if (xmlSchemaGetNotation(schema, localName, nsName) != NULL) {
-		if (valNeeded && (val != NULL)) {
-		    (*val) = xmlSchemaNewNOTATIONValue(BAD_CAST localName,
-			BAD_CAST xmlStrdup(nsName));
+		if ((valNeeded) && (val != NULL)) {
+		    (*val) = xmlSchemaNewNOTATIONValue(xmlStrdup(localName),
+						       xmlStrdup(nsName));
 		    if (*val == NULL)
 			ret = -1;
 		}
@@ -22143,7 +22147,7 @@
     if (bind->nodeTable != NULL)
 	xmlFree(bind->nodeTable);
     if (bind->dupls != NULL)
-	xmlSchemaItemListFree(bind->dupls);	
+	xmlSchemaItemListFree(bind->dupls);
     xmlFree(bind);
 }
 
@@ -22178,12 +22182,12 @@
 
     while (matcher != NULL) {
 	next = matcher->next;
-	if (matcher->keySeqs != NULL) {	    
+	if (matcher->keySeqs != NULL) {
 	    int i;
 	    for (i = 0; i < matcher->sizeKeySeqs; i++)
 		if (matcher->keySeqs[i] != NULL)
 		    xmlFree(matcher->keySeqs[i]);
-	    xmlFree(matcher->keySeqs);	    
+	    xmlFree(matcher->keySeqs);
 	}
 	if (matcher->targets != NULL) {
 	    if (matcher->idcType == XML_SCHEMA_TYPE_IDC_KEYREF) {
@@ -22223,7 +22227,7 @@
 
     while (matcher != NULL) {
 	next = matcher->next;
-	if (matcher->keySeqs != NULL) {	    
+	if (matcher->keySeqs != NULL) {
 	    int i;
 	    /*
 	    * Don't free the array, but only the content.
@@ -22252,7 +22256,7 @@
 	    }
 	    xmlSchemaItemListFree(matcher->targets);
 	    matcher->targets = NULL;
-	}	
+	}
 	matcher->next = NULL;
 	/*
 	* Cache the matcher.
@@ -22294,7 +22298,7 @@
 	sto = vctxt->xpathStatePool;
 	vctxt->xpathStatePool = sto->next;
 	sto->next = NULL;
-    } else {	
+    } else {
 	/*
 	* Create a new state object.
 	*/
@@ -22305,10 +22309,10 @@
 	    return (-1);
 	}
 	memset(sto, 0, sizeof(xmlSchemaIDCStateObj));
-    }	
+    }
     /*
-    * Add to global list. 
-    */	
+    * Add to global list.
+    */
     if (vctxt->xpathStates != NULL)
 	sto->next = vctxt->xpathStates;
     vctxt->xpathStates = sto;
@@ -22328,13 +22332,13 @@
 	VERROR_INT("xmlSchemaIDCAddStateObject",
 	    "failed to create an XPath validation context");
 	return (-1);
-    }    
+    }
     sto->type = type;
     sto->depth = vctxt->depth;
     sto->matcher = matcher;
     sto->sel = sel;
     sto->nbHistory = 0;
-    
+
 #ifdef DEBUG_IDC
     xmlGenericError(xmlGenericErrorContext, "IDC:   STO push '%s'\n",
 	sto->sel->xpath);
@@ -22358,7 +22362,7 @@
 {
     xmlSchemaIDCStateObjPtr sto, head = NULL, first;
     int res, resolved = 0, depth = vctxt->depth;
-        
+
     if (vctxt->xpathStates == NULL)
 	return (0);
 
@@ -22367,8 +22371,8 @@
 #ifdef DEBUG_IDC
     {
 	xmlChar *str = NULL;
-	xmlGenericError(xmlGenericErrorContext, 
-	    "IDC: EVAL on %s, depth %d, type %d\n",	    
+	xmlGenericError(xmlGenericErrorContext,
+	    "IDC: EVAL on %s, depth %d, type %d\n",
 	    xmlSchemaFormatQName(&str, vctxt->inode->nsName,
 		vctxt->inode->localName), depth, nodeType);
 	FREE_AND_NULL(str)
@@ -22382,10 +22386,10 @@
     while (sto != head) {
 #ifdef DEBUG_IDC
 	if (sto->type == XPATH_STATE_OBJ_TYPE_IDC_SELECTOR)
-	    xmlGenericError(xmlGenericErrorContext, "IDC:   ['%s'] selector '%s'\n", 
+	    xmlGenericError(xmlGenericErrorContext, "IDC:   ['%s'] selector '%s'\n",
 		sto->matcher->aidc->def->name, sto->sel->xpath);
 	else
-	    xmlGenericError(xmlGenericErrorContext, "IDC:   ['%s'] field '%s'\n", 
+	    xmlGenericError(xmlGenericErrorContext, "IDC:   ['%s'] field '%s'\n",
 		sto->matcher->aidc->def->name, sto->sel->xpath);
 #endif
 	if (nodeType == XML_ELEMENT_NODE)
@@ -22415,7 +22419,7 @@
 	if (sto->history == NULL) {
 	    sto->history = (int *) xmlMalloc(5 * sizeof(int));
 	    if (sto->history == NULL) {
-		xmlSchemaVErrMemory(NULL, 
+		xmlSchemaVErrMemory(NULL,
 		    "allocating the state object history", NULL);
 		return(-1);
 	    }
@@ -22425,11 +22429,11 @@
 	    sto->history = (int *) xmlRealloc(sto->history,
 		sto->sizeHistory * sizeof(int));
 	    if (sto->history == NULL) {
-		xmlSchemaVErrMemory(NULL, 
+		xmlSchemaVErrMemory(NULL,
 		    "re-allocating the state object history", NULL);
 		return(-1);
 	    }
-	}		
+	}
 	sto->history[sto->nbHistory++] = depth;
 
 #ifdef DEBUG_IDC
@@ -22498,7 +22502,7 @@
     *buf = xmlStrdup(BAD_CAST "[");
     for (i = 0; i < count; i++) {
 	*buf = xmlStrcat(*buf, BAD_CAST "'");
-	res = xmlSchemaGetCanonValueWhtspExt(seq[i]->val, 
+	res = xmlSchemaGetCanonValueWhtspExt(seq[i]->val,
 	    xmlSchemaGetWhiteSpaceFacetValue(seq[i]->type),
 	    &value);
 	if (res == 0)
@@ -22556,7 +22560,7 @@
  *
  * Processes and pops the history items of the IDC state objects.
  * IDC key-sequences are validated/created on IDC bindings.
- * 
+ *
  * Returns 0 on success and -1 on internal errors.
  */
 static int
@@ -22575,13 +22579,13 @@
 #ifdef DEBUG_IDC
     {
 	xmlChar *str = NULL;
-	xmlGenericError(xmlGenericErrorContext, 
+	xmlGenericError(xmlGenericErrorContext,
 	    "IDC: BACK on %s, depth %d\n",
 	    xmlSchemaFormatQName(&str, vctxt->inode->nsName,
 		vctxt->inode->localName), vctxt->depth);
 	FREE_AND_NULL(str)
     }
-#endif    
+#endif
     /*
     * Evaluate the state objects.
     */
@@ -22607,14 +22611,14 @@
 	if (matchDepth != depth) {
 	    sto = sto->next;
 	    continue;
-	}	
+	}
 	if (sto->type == XPATH_STATE_OBJ_TYPE_IDC_FIELD) {
 	    /*
 	    * NOTE: According to
 	    *   http://www.w3.org/Bugs/Public/show_bug.cgi?id=2198
 	    *   ... the simple-content of complex types is also allowed.
 	    */
-	    
+
 	    if (WXS_IS_COMPLEX(type)) {
 		if (WXS_HAS_SIMPLE_CONTENT(type)) {
 		    /*
@@ -22629,17 +22633,17 @@
 		    }
 		} else
 		    simpleType = NULL;
-	    } else 
+	    } else
 		simpleType = type;
 	    if (simpleType == NULL) {
 		xmlChar *str = NULL;
-	
+
 		/*
 		* Not qualified if the field resolves to a node of non
 		* simple type.
-		*/	
+		*/
 		xmlSchemaCustomErr(ACTXT_CAST vctxt,
-		    XML_SCHEMAV_CVC_IDC, NULL,		    
+		    XML_SCHEMAV_CVC_IDC, NULL,
 		    WXS_BASIC_CAST sto->matcher->aidc->def,
 		    "The XPath '%s' of a field of %s does evaluate to a node of "
 		    "non-simple type",
@@ -22649,7 +22653,7 @@
 		sto->nbHistory--;
 		goto deregister_check;
 	    }
-	    
+
 	    if ((key == NULL) && (vctxt->inode->val == NULL)) {
 		/*
 		* Failed to provide the normalized value; maybe
@@ -22665,13 +22669,13 @@
 		xmlSchemaIDCMatcherPtr matcher = sto->matcher;
 		xmlSchemaPSVIIDCKeyPtr *keySeq;
 		int pos, idx;
-		
+
 		/*
 		* The key will be anchored on the matcher's list of
 		* key-sequences. The position in this list is determined
 		* by the target node's depth relative to the matcher's
 		* depth of creation (i.e. the depth of the scope element).
-		* 
+		*
 		* Element        Depth    Pos   List-entries
 		* <scope>          0              NULL
 		*   <bar>          1              NULL
@@ -22682,23 +22686,23 @@
 		* The size of the list is only dependant on the depth of
 		* the tree.
 		* An entry will be NULLed in selector_leave, i.e. when
-		* we hit the target's 
-		*/		    
+		* we hit the target's
+		*/
 		pos = sto->depth - matcher->depth;
 		idx = sto->sel->index;
-		
+
 		/*
 		* Create/grow the array of key-sequences.
 		*/
 		if (matcher->keySeqs == NULL) {
-		    if (pos > 9) 
+		    if (pos > 9)
 			matcher->sizeKeySeqs = pos * 2;
 		    else
 			matcher->sizeKeySeqs = 10;
-		    matcher->keySeqs = (xmlSchemaPSVIIDCKeyPtr **) 
+		    matcher->keySeqs = (xmlSchemaPSVIIDCKeyPtr **)
 			xmlMalloc(matcher->sizeKeySeqs *
-			sizeof(xmlSchemaPSVIIDCKeyPtr *));			
-		    if (matcher->keySeqs == NULL) {		
+			sizeof(xmlSchemaPSVIIDCKeyPtr *));
+		    if (matcher->keySeqs == NULL) {
 			xmlSchemaVErrMemory(NULL,
 			    "allocating an array of key-sequences",
 			    NULL);
@@ -22707,9 +22711,9 @@
 		    memset(matcher->keySeqs, 0,
 			matcher->sizeKeySeqs *
 			sizeof(xmlSchemaPSVIIDCKeyPtr *));
-		} else if (pos >= matcher->sizeKeySeqs) {	
+		} else if (pos >= matcher->sizeKeySeqs) {
 		    int i = matcher->sizeKeySeqs;
-		    
+
 		    matcher->sizeKeySeqs *= 2;
 		    matcher->keySeqs = (xmlSchemaPSVIIDCKeyPtr **)
 			xmlRealloc(matcher->keySeqs,
@@ -22725,29 +22729,29 @@
 		    * The array needs to be NULLed.
 		    * TODO: Use memset?
 		    */
-		    for (; i < matcher->sizeKeySeqs; i++) 
-			matcher->keySeqs[i] = NULL;			
+		    for (; i < matcher->sizeKeySeqs; i++)
+			matcher->keySeqs[i] = NULL;
 		}
-		
+
 		/*
 		* Get/create the key-sequence.
 		*/
-		keySeq = matcher->keySeqs[pos];		    
-		if (keySeq == NULL) {	
+		keySeq = matcher->keySeqs[pos];
+		if (keySeq == NULL) {
 		    goto create_sequence;
 		} else if (keySeq[idx] != NULL) {
 		    xmlChar *str = NULL;
 		    /*
 		    * cvc-identity-constraint:
-		    * 3 For each node in the ·target node set· all
+		    * 3 For each node in the �target node set� all
 		    * of the {fields}, with that node as the context
 		    * node, evaluate to either an empty node-set or
 		    * a node-set with exactly one member, which must
 		    * have a simple type.
-		    * 
+		    *
 		    * The key was already set; report an error.
 		    */
-		    xmlSchemaCustomErr(ACTXT_CAST vctxt, 
+		    xmlSchemaCustomErr(ACTXT_CAST vctxt,
 			XML_SCHEMAV_CVC_IDC, NULL,
 			WXS_BASIC_CAST matcher->aidc->def,
 			"The XPath '%s' of a field of %s evaluates to a "
@@ -22758,27 +22762,27 @@
 		    sto->nbHistory--;
 		    goto deregister_check;
 		} else
-		    goto create_key;		
-		
+		    goto create_key;
+
 create_sequence:
 		/*
 		* Create a key-sequence.
 		*/
 		keySeq = (xmlSchemaPSVIIDCKeyPtr *) xmlMalloc(
-		    matcher->aidc->def->nbFields * 
+		    matcher->aidc->def->nbFields *
 		    sizeof(xmlSchemaPSVIIDCKeyPtr));
 		if (keySeq == NULL) {
-		    xmlSchemaVErrMemory(NULL, 
+		    xmlSchemaVErrMemory(NULL,
 			"allocating an IDC key-sequence", NULL);
-		    return(-1);			
-		}	
-		memset(keySeq, 0, matcher->aidc->def->nbFields * 
+		    return(-1);
+		}
+		memset(keySeq, 0, matcher->aidc->def->nbFields *
 		    sizeof(xmlSchemaPSVIIDCKeyPtr));
 		matcher->keySeqs[pos] = keySeq;
 create_key:
 		/*
 		* Create a key once per node only.
-		*/  
+		*/
 		if (key == NULL) {
 		    key = (xmlSchemaPSVIIDCKeyPtr) xmlMalloc(
 			sizeof(xmlSchemaPSVIIDCKey));
@@ -22787,7 +22791,7 @@
 			    "allocating a IDC key", NULL);
 			xmlFree(keySeq);
 			matcher->keySeqs[pos] = NULL;
-			return(-1);			
+			return(-1);
 		    }
 		    /*
 		    * Consume the compiled value.
@@ -22803,10 +22807,10 @@
 			return (-1);
 		    }
 		}
-		keySeq[idx] = key;		    
+		keySeq[idx] = key;
 	    }
 	} else if (sto->type == XPATH_STATE_OBJ_TYPE_IDC_SELECTOR) {
-		
+
 	    xmlSchemaPSVIIDCKeyPtr **keySeq = NULL;
 	    /* xmlSchemaPSVIIDCBindingPtr bind; */
 	    xmlSchemaPSVIIDCNodePtr ntItem;
@@ -22817,22 +22821,22 @@
 	    /*
 	    * Here we have the following scenario:
 	    * An IDC 'selector' state object resolved to a target node,
-	    * during the time this target node was in the 
-	    * ancestor-or-self axis, the 'field' state object(s) looked 
-	    * out for matching nodes to create a key-sequence for this 
+	    * during the time this target node was in the
+	    * ancestor-or-self axis, the 'field' state object(s) looked
+	    * out for matching nodes to create a key-sequence for this
 	    * target node. Now we are back to this target node and need
-	    * to put the key-sequence, together with the target node 
-	    * itself, into the node-table of the corresponding IDC 
+	    * to put the key-sequence, together with the target node
+	    * itself, into the node-table of the corresponding IDC
 	    * binding.
 	    */
 	    matcher = sto->matcher;
 	    idc = matcher->aidc->def;
 	    nbKeys = idc->nbFields;
-	    pos = depth - matcher->depth;		
+	    pos = depth - matcher->depth;
 	    /*
 	    * Check if the matcher has any key-sequences at all, plus
 	    * if it has a key-sequence for the current target node.
-	    */		
+	    */
 	    if ((matcher->keySeqs == NULL) ||
 		(matcher->sizeKeySeqs <= pos)) {
 		if (idc->type == XML_SCHEMA_TYPE_IDC_KEY)
@@ -22840,15 +22844,15 @@
 		else
 		    goto selector_leave;
 	    }
-	    
-	    keySeq = &(matcher->keySeqs[pos]);		
+
+	    keySeq = &(matcher->keySeqs[pos]);
 	    if (*keySeq == NULL) {
 		if (idc->type == XML_SCHEMA_TYPE_IDC_KEY)
 		    goto selector_key_error;
 		else
 		    goto selector_leave;
 	    }
-	    
+
 	    for (i = 0; i < nbKeys; i++) {
 		if ((*keySeq)[i] == NULL) {
 		    /*
@@ -22859,18 +22863,18 @@
 			* All fields of a "key" IDC must resolve.
 			*/
 			goto selector_key_error;
-		    }		    
+		    }
 		    goto selector_leave;
 		}
 	    }
 	    /*
 	    * All fields did resolve.
 	    */
-	    
+
 	    /*
 	    * 4.1 If the {identity-constraint category} is unique(/key),
-	    * then no two members of the ·qualified node set· have
-	    * ·key-sequences· whose members are pairwise equal, as
+	    * then no two members of the �qualified node set� have
+	    * �key-sequences� whose members are pairwise equal, as
 	    * defined by Equal in [XML Schemas: Datatypes].
 	    *
 	    * Get the IDC binding from the matcher and check for
@@ -22880,10 +22884,10 @@
 	    bind = xmlSchemaIDCAcquireBinding(vctxt, matcher);
 #endif
 	    targets = xmlSchemaIDCAcquireTargetList(vctxt, matcher);
-	    if ((idc->type != XML_SCHEMA_TYPE_IDC_KEYREF) && 
+	    if ((idc->type != XML_SCHEMA_TYPE_IDC_KEYREF) &&
 		(targets->nbItems != 0)) {
 		xmlSchemaPSVIIDCKeyPtr ckey, bkey, *bkeySeq;
-		
+
 		i = 0;
 		res = 0;
 		/*
@@ -22894,7 +22898,7 @@
 			((xmlSchemaPSVIIDCNodePtr) targets->items[i])->keys;
 		    for (j = 0; j < nbKeys; j++) {
 			ckey = (*keySeq)[j];
-			bkey = bkeySeq[j];							
+			bkey = bkeySeq[j];
 			res = xmlSchemaAreValuesEqual(ckey->val, bkey->val);
 			if (res == -1) {
 			    return (-1);
@@ -22916,10 +22920,10 @@
 		} while (i < targets->nbItems);
 		if (i != targets->nbItems) {
 		    xmlChar *str = NULL, *strB = NULL;
-		    /*   
+		    /*
 		    * TODO: Try to report the key-sequence.
 		    */
-		    xmlSchemaCustomErr(ACTXT_CAST vctxt, 
+		    xmlSchemaCustomErr(ACTXT_CAST vctxt,
 			XML_SCHEMAV_CVC_IDC, NULL,
 			WXS_BASIC_CAST idc,
 			"Duplicate key-sequence %s in %s",
@@ -22937,15 +22941,15 @@
 	    ntItem = (xmlSchemaPSVIIDCNodePtr) xmlMalloc(
 		sizeof(xmlSchemaPSVIIDCNode));
 	    if (ntItem == NULL) {
-		xmlSchemaVErrMemory(NULL, 
+		xmlSchemaVErrMemory(NULL,
 		    "allocating an IDC node-table item", NULL);
 		xmlFree(*keySeq);
 		*keySeq = NULL;
 		return(-1);
-	    }	
+	    }
 	    memset(ntItem, 0, sizeof(xmlSchemaPSVIIDCNode));
-	    
-	    /* 
+
+	    /*
 	    * Store the node-table item in a global list.
 	    */
 	    if (idc->type != XML_SCHEMA_TYPE_IDC_KEYREF) {
@@ -22967,7 +22971,7 @@
 		    xmlFree(ntItem);
 		    xmlFree(*keySeq);
 		    *keySeq = NULL;
-		    return (-1);		    
+		    return (-1);
 		}
 	    }
 	    /*
@@ -22979,11 +22983,11 @@
 	    ntItem->keys = *keySeq;
 	    *keySeq = NULL;
 #if 0
-	    if (xmlSchemaIDCAppendNodeTableItem(bind, ntItem) == -1) {
+	    if (xmlSchemaIDCAppendNodeTableItem(bind, ntItem) == -1)
 #endif
 	    if (xmlSchemaItemListAdd(targets, ntItem) == -1) {
 		if (idc->type == XML_SCHEMA_TYPE_IDC_KEYREF) {
-		    /* 
+		    /*
 		    * Free the item, since keyref items won't be
 		    * put on a global list.
 		    */
@@ -22992,18 +22996,18 @@
 		}
 		return (-1);
 	    }
-	    
+
 	    goto selector_leave;
 selector_key_error:
 	    {
 		xmlChar *str = NULL;
 		/*
-		* 4.2.1 (KEY) The ·target node set· and the 
-		* ·qualified node set· are equal, that is, every 
-		* member of the ·target node set· is also a member
-		* of the ·qualified node set· and vice versa.
+		* 4.2.1 (KEY) The �target node set� and the
+		* �qualified node set� are equal, that is, every
+		* member of the �target node set� is also a member
+		* of the �qualified node set� and vice versa.
 		*/
-		xmlSchemaCustomErr(ACTXT_CAST vctxt, 
+		xmlSchemaCustomErr(ACTXT_CAST vctxt,
 		    XML_SCHEMAV_CVC_IDC, NULL,
 		    WXS_BASIC_CAST idc,
 		    "Not all fields of %s evaluate to a node",
@@ -23019,7 +23023,7 @@
 		*keySeq = NULL;
 	    }
 	} /* if selector */
-	
+
 	sto->nbHistory--;
 
 deregister_check:
@@ -23070,15 +23074,15 @@
     xmlSchemaIDCMatcherPtr matcher, last = NULL;
     xmlSchemaIDCPtr idc, refIdc;
     xmlSchemaIDCAugPtr aidc;
-        
+
     idc = (xmlSchemaIDCPtr) elemDecl->idcs;
     if (idc == NULL)
 	return (0);
-    
+
 #ifdef DEBUG_IDC
     {
 	xmlChar *str = NULL;
-	xmlGenericError(xmlGenericErrorContext, 
+	xmlGenericError(xmlGenericErrorContext,
 	    "IDC: REGISTER on %s, depth %d\n",
 	    (char *) xmlSchemaFormatQName(&str, vctxt->inode->nsName,
 		vctxt->inode->localName), vctxt->depth);
@@ -23119,7 +23123,7 @@
 			"Could not find an augmented IDC item for an IDC "
 			"definition");
 		    return (-1);
-		}		
+		}
 		if ((aidc->keyrefDepth == -1) ||
 		    (vctxt->depth < aidc->keyrefDepth))
 		    aidc->keyrefDepth = vctxt->depth;
@@ -23150,10 +23154,10 @@
 	    vctxt->idcMatcherCache = matcher->nextCached;
 	    matcher->nextCached = NULL;
 	} else {
-	    matcher = (xmlSchemaIDCMatcherPtr) 
+	    matcher = (xmlSchemaIDCMatcherPtr)
 		xmlMalloc(sizeof(xmlSchemaIDCMatcher));
 	    if (matcher == NULL) {
-		xmlSchemaVErrMemory(vctxt, 
+		xmlSchemaVErrMemory(vctxt,
 		    "allocating an IDC matcher", NULL);
 		return (-1);
 	    }
@@ -23166,16 +23170,16 @@
 	last = matcher;
 
 	matcher->type = IDC_MATCHER;
-	matcher->depth = vctxt->depth;	
+	matcher->depth = vctxt->depth;
 	matcher->aidc = aidc;
 	matcher->idcType = aidc->def->type;
-#ifdef DEBUG_IDC	
+#ifdef DEBUG_IDC
 	xmlGenericError(xmlGenericErrorContext, "IDC:   register matcher\n");
-#endif 
+#endif
 	/*
-	* Init the automaton state object. 
+	* Init the automaton state object.
 	*/
-	if (xmlSchemaIDCAddStateObject(vctxt, matcher, 
+	if (xmlSchemaIDCAddStateObject(vctxt, matcher,
 	    idc->selector, XPATH_STATE_OBJ_TYPE_IDC_SELECTOR) == -1)
 	    return (-1);
 
@@ -23192,7 +23196,7 @@
     int res, i, j, k, nbTargets, nbFields, nbDupls, nbNodeTable;
     xmlSchemaPSVIIDCKeyPtr *keys, *ntkeys;
     xmlSchemaPSVIIDCNodePtr *targets, *dupls;
-    
+
     xmlSchemaIDCMatcherPtr matcher = ielem->idcMatchers;
     /* vctxt->createIDCNodeTables */
     while (matcher != NULL) {
@@ -23226,7 +23230,7 @@
 	    nbDupls = bind->dupls->nbItems;
 	} else {
 	    dupls = NULL;
-	    nbDupls = 0;	    
+	    nbDupls = 0;
 	}
 	if (bind->nodeTable != NULL) {
 	    nbNodeTable = bind->nbNodes;
@@ -23239,29 +23243,29 @@
 	    * Transfer all IDC target-nodes to the IDC node-table.
 	    */
 	    bind->nodeTable =
-		(xmlSchemaPSVIIDCNodePtr *) matcher->targets->items;		
+		(xmlSchemaPSVIIDCNodePtr *) matcher->targets->items;
 	    bind->sizeNodes = matcher->targets->sizeItems;
 	    bind->nbNodes = matcher->targets->nbItems;
 
 	    matcher->targets->items = NULL;
 	    matcher->targets->sizeItems = 0;
-	    matcher->targets->nbItems = 0;	    
+	    matcher->targets->nbItems = 0;
 	} else {
 	    /*
 	    * Compare the key-sequences and add to the IDC node-table.
 	    */
 	    nbTargets = matcher->targets->nbItems;
-	    targets = (xmlSchemaPSVIIDCNodePtr *) matcher->targets->items;	
+	    targets = (xmlSchemaPSVIIDCNodePtr *) matcher->targets->items;
 	    nbFields = matcher->aidc->def->nbFields;
 	    i = 0;
 	    do {
 		keys = targets[i]->keys;
-		if (nbDupls) {			
+		if (nbDupls) {
 		    /*
 		    * Search in already found duplicates first.
 		    */
 		    j = 0;
-		    do {						
+		    do {
 			if (nbFields == 1) {
 			    res = xmlSchemaAreValuesEqual(keys[0]->val,
 				dupls[j]->keys[0]->val);
@@ -23296,11 +23300,11 @@
 			    }
 			}
 			j++;
-		    } while (j < nbDupls);		    
+		    } while (j < nbDupls);
 		}
 		if (nbNodeTable) {
 		    j = 0;
-		    do {						
+		    do {
 			if (nbFields == 1) {
 			    res = xmlSchemaAreValuesEqual(keys[0]->val,
 				bind->nodeTable[j]->keys[0]->val);
@@ -23327,7 +23331,7 @@
 				    goto next_node_table_entry;
 				}
 			    }
-			}			
+			}
 			/*
 			* Add the duplicate to the list of duplicates.
 			*/
@@ -23335,7 +23339,7 @@
 			    bind->dupls = xmlSchemaItemListCreate();
 			    if (bind->dupls == NULL)
 				goto internal_error;
-			}		    
+			}
 			if (xmlSchemaItemListAdd(bind->dupls, bind->nodeTable[j]) == -1)
 			    goto internal_error;
 			/*
@@ -23370,12 +23374,12 @@
 }
 
 /**
- * xmlSchemaBubbleIDCNodeTables: 
+ * xmlSchemaBubbleIDCNodeTables:
  * @depth: the current tree depth
  *
- * Merges IDC bindings of an element at @depth into the corresponding IDC 
- * bindings of its parent element. If a duplicate note-table entry is found, 
- * both, the parent node-table entry and child entry are discarded from the 
+ * Merges IDC bindings of an element at @depth into the corresponding IDC
+ * bindings of its parent element. If a duplicate note-table entry is found,
+ * both, the parent node-table entry and child entry are discarded from the
  * node-table of the parent.
  *
  * Returns 0 if OK and -1 on internal errors.
@@ -23389,19 +23393,19 @@
     xmlSchemaIDCAugPtr aidc;
     int i, j, k, ret = 0, nbFields, oldNum, oldDupls;
 
-    bind = vctxt->inode->idcTable;        
+    bind = vctxt->inode->idcTable;
     if (bind == NULL) {
 	/* Fine, no table, no bubbles. */
 	return (0);
     }
-    
+
     parTable = &(vctxt->elemInfos[vctxt->depth -1]->idcTable);
     /*
     * Walk all bindings; create new or add to existing bindings.
     * Remove duplicate key-sequences.
     */
     while (bind != NULL) {
-	
+
 	if ((bind->nbNodes == 0) && WXS_ILIST_IS_EMPTY(bind->dupls))
 	    goto next_binding;
 	/*
@@ -23411,7 +23415,7 @@
 	    aidc = vctxt->aidcs;
 	    do {
 		if (aidc->def == bind->definition) {
-		    if ((aidc->keyrefDepth == -1) || 
+		    if ((aidc->keyrefDepth == -1) ||
 			(aidc->keyrefDepth >= vctxt->depth)) {
 			goto next_binding;
 		    }
@@ -23427,7 +23431,7 @@
 	* Search a matching parent binding for the
 	* IDC definition.
 	*/
-	while (parBind != NULL) {	    
+	while (parBind != NULL) {
 	    if (parBind->definition == bind->definition)
 		break;
 	    parBind = parBind->next;
@@ -23435,7 +23439,7 @@
 
 	if (parBind != NULL) {
 	    /*
-	    * Compare every node-table entry of the child node, 
+	    * Compare every node-table entry of the child node,
 	    * i.e. the key-sequence within, ...
 	    */
 	    oldNum = parBind->nbNodes; /* Skip newly added items. */
@@ -23445,12 +23449,12 @@
 		dupls = (xmlSchemaPSVIIDCNodePtr *) parBind->dupls->items;
 	    } else {
 		dupls = NULL;
-		oldDupls = 0;		
+		oldDupls = 0;
 	    }
-	    
+
 	    parNodes = parBind->nodeTable;
 	    nbFields = bind->definition->nbFields;
-	    
+
 	    for (i = 0; i < bind->nbNodes; i++) {
 		node = bind->nodeTable[i];
 		if (node == NULL)
@@ -23460,7 +23464,7 @@
 		* evaluated to be a duplicate key-sequence.
 		*/
 		if (oldDupls) {
-		    j = 0; 
+		    j = 0;
 		    while (j < oldDupls) {
 			if (nbFields == 1) {
 			    ret = xmlSchemaAreValuesEqual(
@@ -23493,12 +23497,12 @@
 			/* Duplicate found. Skip this entry. */
 			continue;
 		    }
-		}		    
+		}
 		/*
 		* ... and with every key-sequence of the parent node.
 		*/
 		if (oldNum) {
-		    j = 0; 
+		    j = 0;
 		    while (j < oldNum) {
 			parNode = parNodes[j];
 			if (nbFields == 1) {
@@ -23511,7 +23515,7 @@
 				j++;
 				continue;
 			    }
-			} else {			    
+			} else {
 			    for (k = 0; k < nbFields; k++) {
 				ret = xmlSchemaAreValuesEqual(
 				    node->keys[k]->val,
@@ -23532,20 +23536,20 @@
 			* Handle duplicates. Move the duplicate in
 			* the parent's node-table to the list of
 			* duplicates.
-			*/			
+			*/
 			oldNum--;
 			parBind->nbNodes--;
 			/*
 			* Move last old item to pos of duplicate.
 			*/
 			parNodes[j] = parNodes[oldNum];
-			
+
 			if (parBind->nbNodes != oldNum) {
 			    /*
-			    * If new items exist, move last new item to 
+			    * If new items exist, move last new item to
 			    * last of old items.
 			    */
-			    parNodes[oldNum] = 
+			    parNodes[oldNum] =
 				parNodes[parBind->nbNodes];
 			}
 			if (parBind->dupls == NULL) {
@@ -23553,31 +23557,31 @@
 			    if (parBind->dupls == NULL)
 				goto internal_error;
 			}
-			xmlSchemaItemListAdd(parBind->dupls, parNode);			
+			xmlSchemaItemListAdd(parBind->dupls, parNode);
 		    } else {
 			/*
-			* Add the node-table entry (node and key-sequence) of 
+			* Add the node-table entry (node and key-sequence) of
 			* the child node to the node table of the parent node.
 			*/
-			if (parBind->nodeTable == NULL) {			
-			    parBind->nodeTable = (xmlSchemaPSVIIDCNodePtr *) 
+			if (parBind->nodeTable == NULL) {
+			    parBind->nodeTable = (xmlSchemaPSVIIDCNodePtr *)
 				xmlMalloc(10 * sizeof(xmlSchemaPSVIIDCNodePtr));
 			    if (parBind->nodeTable == NULL) {
-				xmlSchemaVErrMemory(NULL, 
+				xmlSchemaVErrMemory(NULL,
 				    "allocating IDC list of node-table items", NULL);
 				goto internal_error;
 			    }
 			    parBind->sizeNodes = 1;
 			} else if (parBind->nbNodes >= parBind->sizeNodes) {
 			    parBind->sizeNodes *= 2;
-			    parBind->nodeTable = (xmlSchemaPSVIIDCNodePtr *) 
-				xmlRealloc(parBind->nodeTable, parBind->sizeNodes * 
+			    parBind->nodeTable = (xmlSchemaPSVIIDCNodePtr *)
+				xmlRealloc(parBind->nodeTable, parBind->sizeNodes *
 				sizeof(xmlSchemaPSVIIDCNodePtr));
 			    if (parBind->nodeTable == NULL) {
-				xmlSchemaVErrMemory(NULL, 
+				xmlSchemaVErrMemory(NULL,
 				    "re-allocating IDC list of node-table items", NULL);
 				goto internal_error;
-			    }			    
+			    }
 			}
 			parNodes = parBind->nodeTable;
 			/*
@@ -23587,9 +23591,9 @@
 			parNodes[parBind->nbNodes++] = node;
 		    }
 
-		}	
-		
-	    }	
+		}
+
+	    }
 	} else {
 	    /*
 	    * No binding for the IDC was found: create a new one and
@@ -23598,7 +23602,7 @@
 	    parBind = xmlSchemaIDCNewBinding(bind->definition);
 	    if (parBind == NULL)
 		goto internal_error;
-	    
+
 	    /*
 	    * TODO: Hmm, how to optimize the initial number of
 	    * allocated entries?
@@ -23624,11 +23628,11 @@
 		    /*
 		    * Copy the entries.
 		    */
-		    parBind->nodeTable = (xmlSchemaPSVIIDCNodePtr *) 
+		    parBind->nodeTable = (xmlSchemaPSVIIDCNodePtr *)
 			xmlMalloc(bind->nbNodes *
 			sizeof(xmlSchemaPSVIIDCNodePtr));
 		    if (parBind->nodeTable == NULL) {
-			xmlSchemaVErrMemory(NULL, 
+			xmlSchemaVErrMemory(NULL,
 			    "allocating an array of IDC node-table "
 			    "items", NULL);
 			xmlSchemaIDCFreeBinding(parBind);
@@ -23647,15 +23651,15 @@
 		if (parBind->dupls != NULL)
 		    xmlSchemaItemListFree(parBind->dupls);
 		parBind->dupls = bind->dupls;
-		bind->dupls = NULL;		
+		bind->dupls = NULL;
 	    }
 	    if (*parTable == NULL)
 		*parTable = parBind;
 	    else {
 		parBind->next = *parTable;
 		*parTable = parBind;
-	    }	   
-	}	
+	    }
+	}
 
 next_binding:
 	bind = bind->next;
@@ -23678,7 +23682,7 @@
 {
     xmlSchemaIDCMatcherPtr matcher;
     xmlSchemaPSVIIDCBindingPtr bind;
-    
+
     matcher = vctxt->inode->idcMatchers;
     /*
     * Find a keyref.
@@ -23699,7 +23703,7 @@
 	    */
 	    bind = vctxt->inode->idcTable;
 	    while (bind != NULL) {
-		if ((xmlSchemaIDCPtr) matcher->aidc->def->ref->item == 
+		if ((xmlSchemaIDCPtr) matcher->aidc->def->ref->item ==
 		    bind->definition)
 		    break;
 		bind = bind->next;
@@ -23768,7 +23772,7 @@
 			}
 		    }
 		}
-		
+
 		if (res == 0) {
 		    xmlChar *str = NULL, *strB = NULL;
 		    xmlSchemaKeyrefErr(vctxt,
@@ -23852,7 +23856,7 @@
 			xmlNodePtr attrNode,
 			int nodeLine,
 			const xmlChar *localName,
-			const xmlChar *nsName,			
+			const xmlChar *nsName,
 			int ownedNames,
 			xmlChar *value,
 			int ownedValue)
@@ -23878,7 +23882,7 @@
     if (nsName != NULL) {
 	if (xmlStrEqual(localName, BAD_CAST "nil")) {
 	    if (xmlStrEqual(attr->nsName, xmlSchemaInstanceNs)) {
-		attr->metaType = XML_SCHEMA_ATTR_INFO_META_XSI_NIL;		
+		attr->metaType = XML_SCHEMA_ATTR_INFO_META_XSI_NIL;
 	    }
 	} else if (xmlStrEqual(localName, BAD_CAST "type")) {
 	    if (xmlStrEqual(attr->nsName, xmlSchemaInstanceNs)) {
@@ -24099,7 +24103,7 @@
 	valType = valType;
     else
 	valType = xmlSchemaGetValType(val);
-    
+
     ret = 0;
     for (facetLink = type->facetSet; facetLink != NULL;
 	facetLink = facetLink->next) {
@@ -24148,11 +24152,11 @@
     ret = 0;
     for (facetLink = type->facetSet; facetLink != NULL;
 	facetLink = facetLink->next) {
-	
+
 	switch (facetLink->facet->type) {
 	    case XML_SCHEMA_FACET_LENGTH:
 	    case XML_SCHEMA_FACET_MINLENGTH:
-	    case XML_SCHEMA_FACET_MAXLENGTH:		    
+	    case XML_SCHEMA_FACET_MAXLENGTH:
 		ret = xmlSchemaValidateListSimpleTypeFacet(facetLink->facet,
 		    value, length, NULL);
 		break;
@@ -24164,7 +24168,7 @@
 		"validating against a list type facet");
 	    return (-1);
 	} else if (ret > 0) {
-	    if (fireErrors)		
+	    if (fireErrors)
 		xmlSchemaFacetErr(actxt, ret, node,
 		value, length, type, facetLink->facet, NULL, NULL, NULL);
 	    else
@@ -24241,7 +24245,7 @@
 		if (facetLink->facet->type != XML_SCHEMA_FACET_PATTERN)
 		    continue;
 		found = 1;
-		/* 
+		/*
 		* NOTE that for patterns, @value needs to be the
 		* normalized vaule.
 		*/
@@ -24253,7 +24257,7 @@
 			"validating against a pattern facet");
 		    return (-1);
 		} else {
-		    /* 
+		    /*
 		    * Save the last non-validating facet.
 		    */
 		    facet = facetLink->facet;
@@ -24276,12 +24280,12 @@
 
     return (error);
 }
- 
+
 static xmlChar *
 xmlSchemaNormalizeValue(xmlSchemaTypePtr type,
 			const xmlChar *value)
 {
-    switch (xmlSchemaGetWhiteSpaceFacetValue(type)) {	
+    switch (xmlSchemaGetWhiteSpaceFacetValue(type)) {
 	case XML_SCHEMA_WHITESPACE_COLLAPSE:
 	    return (xmlSchemaCollapseString(value));
 	case XML_SCHEMA_WHITESPACE_REPLACE:
@@ -24300,7 +24304,7 @@
     int ret;
     const xmlChar *nsName;
     xmlChar *local, *prefix = NULL;
-    
+
     ret = xmlValidateQName(value, 1);
     if (ret != 0) {
 	if (ret == -1) {
@@ -24323,7 +24327,7 @@
     *  - is there a default namespace?
     */
     nsName = xmlSchemaLookupNamespace(vctxt, prefix);
-    
+
     if (prefix != NULL) {
 	xmlFree(prefix);
 	/*
@@ -24380,7 +24384,7 @@
 	    value = normValue; \
 	isNormalized = 1; \
     }
-    
+
     if ((retVal != NULL) && (*retVal != NULL)) {
 	xmlSchemaFreeValue(*retVal);
 	*retVal = NULL;
@@ -24395,14 +24399,14 @@
     */
     /*
     * 2.1 If The definition is ENTITY or is validly derived from ENTITY given
-    * the empty set, as defined in Type Derivation OK (Simple) (§3.14.6), then
-    * the string must be a ·declared entity name·.
+    * the empty set, as defined in Type Derivation OK (Simple) (�3.14.6), then
+    * the string must be a �declared entity name�.
     */
     /*
     * 2.2 If The definition is ENTITIES or is validly derived from ENTITIES
-    * given the empty set, as defined in Type Derivation OK (Simple) (§3.14.6),
-    * then every whitespace-delimited substring of the string must be a ·declared
-    * entity name·.
+    * given the empty set, as defined in Type Derivation OK (Simple) (�3.14.6),
+    * then every whitespace-delimited substring of the string must be a �declared
+    * entity name�.
     */
     /*
     * 2.3 otherwise no further condition applies.
@@ -24414,8 +24418,8 @@
     if (WXS_IS_ANY_SIMPLE_TYPE(type) || WXS_IS_ATOMIC(type)) {
 	xmlSchemaTypePtr biType; /* The built-in type. */
 	/*
-	* SPEC (1.2.1) "if {variety} is ·atomic· then the string must ·match·
-	* a literal in the ·lexical space· of {base type definition}"
+	* SPEC (1.2.1) "if {variety} is �atomic� then the string must �match�
+	* a literal in the �lexical space� of {base type definition}"
 	*/
 	/*
 	* Whitespace-normalize.
@@ -24441,9 +24445,9 @@
 	* NOTATIONs need to be processed here, since they need
 	* to lookup in the hashtable of NOTATION declarations of the schema.
 	*/
-	if (actxt->type == XML_SCHEMA_CTXT_VALIDATOR) {	    
-	    switch (biType->builtInType) {		
-		case XML_SCHEMAS_NOTATION:		    
+	if (actxt->type == XML_SCHEMA_CTXT_VALIDATOR) {
+	    switch (biType->builtInType) {
+		case XML_SCHEMAS_NOTATION:
 		    ret = xmlSchemaValidateNotation(
 			(xmlSchemaValidCtxtPtr) actxt,
 			((xmlSchemaValidCtxtPtr) actxt)->schema,
@@ -24463,8 +24467,8 @@
 			    value, NULL, NULL);
 		    break;
 	    }
-	} else if (actxt->type == XML_SCHEMA_CTXT_PARSER) {	    
-	    switch (biType->builtInType) {		    
+	} else if (actxt->type == XML_SCHEMA_CTXT_PARSER) {
+	    switch (biType->builtInType) {
 		case XML_SCHEMAS_NOTATION:
 		    ret = xmlSchemaValidateNotation(NULL,
 			((xmlSchemaParserCtxtPtr) actxt)->schema, node,
@@ -24479,7 +24483,7 @@
 			ret = xmlSchemaValPredefTypeNodeNoNorm(biType,
 			    value, NULL, node);
 		    break;
-	    }	   
+	    }
 	} else {
 	    /*
 	    * Validation via a public API is not implemented yet.
@@ -24496,7 +24500,7 @@
 	    if (WXS_IS_LIST(type))
 		ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_2;
 	    else
-		ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_1;	    
+		ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_1;
 	}
 	if ((ret == 0) && (type->flags & XML_SCHEMAS_TYPE_HAS_FACETS)) {
 	    /*
@@ -24511,10 +24515,10 @@
 			"validating facets of atomic simple type");
 		    goto internal_error;
 		}
-		if (WXS_IS_LIST(type)) 
+		if (WXS_IS_LIST(type))
 		    ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_2;
 		else
-		    ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_1;		
+		    ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_1;
 	    }
 	}
 	if (fireErrors && (ret > 0))
@@ -24526,9 +24530,9 @@
 	xmlChar *tmpValue = NULL;
 	unsigned long len = 0;
 	xmlSchemaValPtr prevVal = NULL, curVal = NULL;
-	/* 1.2.2 if {variety} is ·list· then the string must be a sequence
-	* of white space separated tokens, each of which ·match·es a literal
-	* in the ·lexical space· of {item type definition}
+	/* 1.2.2 if {variety} is �list� then the string must be a sequence
+	* of white space separated tokens, each of which �match�es a literal
+	* in the �lexical space� of {item type definition}
 	*/
 	/*
 	* Note that XML_SCHEMAS_TYPE_NORMVALUENEEDED will be set if
@@ -24539,7 +24543,7 @@
 	* VAL TODO: Optimize validation of empty values.
 	* VAL TODO: We do not have computed values for lists.
 	*/
-	itemType = WXS_LIST_ITEMTYPE(type);	
+	itemType = WXS_LIST_ITEMTYPE(type);
 	cur = value;
 	do {
 	    while (IS_BLANK_CH(*cur))
@@ -24578,7 +24582,7 @@
 		}
 		ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_2;
 		break;
-	    }	    
+	    }
 	    cur = end;
 	} while (*cur != 0);
 	FREE_AND_NULL(tmpValue);
@@ -24599,7 +24603,7 @@
 	    }
 	}
 	if (fireErrors && (ret > 0)) {
-	    /* 
+	    /*
 	    * Report the normalized value.
 	    */
 	    normalize = 1;
@@ -24609,10 +24613,10 @@
     } else if (WXS_IS_UNION(type)) {
 	xmlSchemaTypeLinkPtr memberLink;
 	/*
-	* TODO: For all datatypes ·derived· by ·union·  whiteSpace does
-	* not apply directly; however, the normalization behavior of ·union·
+	* TODO: For all datatypes �derived� by �union�  whiteSpace does
+	* not apply directly; however, the normalization behavior of �union�
 	* types is controlled by the value of whiteSpace on that one of the
-	* ·memberTypes· against which the ·union· is successfully validated.
+	* �memberTypes� against which the �union� is successfully validated.
 	*
 	* This means that the value is normalized by the first validating
 	* member type, then the facets of the union type are applied. This
@@ -24620,8 +24624,8 @@
 	*/
 
 	/*
-	* 1.2.3 if {variety} is ·union· then the string must ·match· a
-	* literal in the ·lexical space· of at least one member of
+	* 1.2.3 if {variety} is �union� then the string must �match� a
+	* literal in the �lexical space� of at least one member of
 	* {member type definitions}
 	*/
 	memberLink = xmlSchemaGetUnionSimpleTypeMemberTypes(type);
@@ -24629,7 +24633,7 @@
 	    AERROR_INT("xmlSchemaVCheckCVCSimpleType",
 		"union simple type has no member types");
 	    goto internal_error;
-	}	
+	}
 	/*
 	* Always normalize union type values, since we currently
 	* cannot store the whitespace information with the value
@@ -24637,7 +24641,7 @@
 	* not possible.
 	*/
 	while (memberLink != NULL) {
-	    if (valNeeded) 
+	    if (valNeeded)
 		ret = xmlSchemaVCheckCVCSimpleType(actxt, node,
 		    memberLink->type, value, &val, 0, 1, 0);
 	    else
@@ -24660,9 +24664,9 @@
 	*/
 	if ((ret == 0) && (type->flags & XML_SCHEMAS_TYPE_HAS_FACETS)) {
 	    /*
-	    * The normalization behavior of ·union· types is controlled by
-	    * the value of whiteSpace on that one of the ·memberTypes·
-	    * against which the ·union· is successfully validated.
+	    * The normalization behavior of �union� types is controlled by
+	    * the value of whiteSpace on that one of the �memberTypes�
+	    * against which the �union� is successfully validated.
 	    */
 	    NORMALIZE(memberLink->type);
 	    ret = xmlSchemaValidateFacets(actxt, node, type,
@@ -24674,7 +24678,7 @@
 			"validating facets of union simple type");
 		    goto internal_error;
 		}
-		ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_3;		
+		ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_3;
 	    }
 	}
 	if (fireErrors && (ret > 0))
@@ -24822,14 +24826,14 @@
 
 	    /*
 	    * SPEC cvc-elt (3.3.4) : (4.3) (Type Derivation OK)
-	    * "The ·local type definition· must be validly
+	    * "The �local type definition� must be validly
 	    * derived from the {type definition} given the union of
 	    * the {disallowed substitutions} and the {type definition}'s
 	    * {prohibited substitutions}, as defined in
-	    * Type Derivation OK (Complex) (§3.4.6)
+	    * Type Derivation OK (Complex) (�3.4.6)
 	    * (if it is a complex type definition),
 	    * or given {disallowed substitutions} as defined in Type
-	    * Derivation OK (Simple) (§3.14.6) (if it is a simple type
+	    * Derivation OK (Simple) (�3.14.6) (if it is a simple type
 	    * definition)."
 	    *
 	    * {disallowed substitutions}: the "block" on the element decl.
@@ -25089,19 +25093,19 @@
 static int
 xmlSchemaVAttributesComplex(xmlSchemaValidCtxtPtr vctxt)
 {
-    xmlSchemaTypePtr type = vctxt->inode->typeDef;    
+    xmlSchemaTypePtr type = vctxt->inode->typeDef;
     xmlSchemaItemListPtr attrUseList;
     xmlSchemaAttributeUsePtr attrUse = NULL;
     xmlSchemaAttributePtr attrDecl = NULL;
-    xmlSchemaAttrInfoPtr iattr, tmpiattr;    
+    xmlSchemaAttrInfoPtr iattr, tmpiattr;
     int i, j, found, nbAttrs, nbUses;
     int xpathRes = 0, res, wildIDs = 0, fixed;
     xmlNodePtr defAttrOwnerElem = NULL;
 
     /*
     * SPEC (cvc-attribute)
-    * (1) "The declaration must not be ·absent· (see Missing
-    * Sub-components (§5.3) for how this can fail to be
+    * (1) "The declaration must not be �absent� (see Missing
+    * Sub-components (�5.3) for how this can fail to be
     * the case)."
     * (2) "Its {type definition} must not be absent."
     *
@@ -25151,15 +25155,15 @@
 	    * use with an {attribute declaration} whose {name} matches
 	    * the attribute information item's [local name] and whose
 	    * {target namespace} is identical to the attribute information
-	    * item's [namespace name] (where an ·absent· {target namespace}
+	    * item's [namespace name] (where an �absent� {target namespace}
 	    * is taken to be identical to a [namespace name] with no value),
-	    * then the attribute information must be ·valid· with respect
+	    * then the attribute information must be �valid� with respect
 	    * to that attribute use as per Attribute Locally Valid (Use)
-	    * (§3.5.4). In this case the {attribute declaration} of that
-	    * attribute use is the ·context-determined declaration· for the
+	    * (�3.5.4). In this case the {attribute declaration} of that
+	    * attribute use is the �context-determined declaration� for the
 	    * attribute information item with respect to Schema-Validity
-	    * Assessment (Attribute) (§3.2.4) and
-	    * Assessment Outcome (Attribute) (§3.2.5).
+	    * Assessment (Attribute) (�3.2.4) and
+	    * Assessment Outcome (Attribute) (�3.2.5).
 	    */
 	    iattr->state = XML_SCHEMAS_ATTR_ASSESSED;
 	    iattr->use = attrUse;
@@ -25193,7 +25197,7 @@
 	    }
 	    tmpiattr->state = XML_SCHEMAS_ATTR_ERR_MISSING;
 	    tmpiattr->use = attrUse;
-	    tmpiattr->decl = attrDecl;	    
+	    tmpiattr->decl = attrDecl;
 	} else if ((attrUse->occurs == XML_SCHEMAS_ATTR_USE_OPTIONAL) &&
 	    ((attrUse->defValue != NULL) ||
 	     (attrDecl->defValue != NULL))) {
@@ -25237,13 +25241,13 @@
 		continue;
 	    /*
 	    * SPEC (cvc-complex-type)
-	    * (3.2.2) "The attribute information item must be ·valid· with
-	    * respect to it as defined in Item Valid (Wildcard) (§3.10.4)."
+	    * (3.2.2) "The attribute information item must be �valid� with
+	    * respect to it as defined in Item Valid (Wildcard) (�3.10.4)."
 	    *
 	    * SPEC Item Valid (Wildcard) (cvc-wildcard)
-	    * "... its [namespace name] must be ·valid· with respect to
+	    * "... its [namespace name] must be �valid� with respect to
 	    * the wildcard constraint, as defined in Wildcard allows
-	    * Namespace Name (§3.10.4)."
+	    * Namespace Name (�3.10.4)."
 	    */
 	    if (xmlSchemaCheckCVCWildcardNamespace(type->attributeWildcard,
 		    iattr->nsName) == 0) {
@@ -25279,11 +25283,11 @@
 		    * SPEC (cvc-complex-type)
 		    * (5) "Let [Definition:]  the wild IDs be the set of
 		    * all attribute information item to which clause 3.2
-		    * applied and whose ·validation· resulted in a
-		    * ·context-determined declaration· of mustFind or no
-		    * ·context-determined declaration· at all, and whose
+		    * applied and whose �validation� resulted in a
+		    * �context-determined declaration� of mustFind or no
+		    * �context-determined declaration� at all, and whose
 		    * [local name] and [namespace name] resolve (as
-		    * defined by QName resolution (Instance) (§3.15.4)) to
+		    * defined by QName resolution (Instance) (�3.15.4)) to
 		    * an attribute declaration whose {type definition} is
 		    * or is derived from ID. Then all of the following
 		    * must be true:"
@@ -25293,7 +25297,7 @@
 			iattr->typeDef, XML_SCHEMAS_ID)) {
 			/*
 			* SPEC (5.1) "There must be no more than one
-			* item in ·wild IDs·."
+			* item in �wild IDs�."
 			*/
 			if (wildIDs != 0) {
 			    /* VAL TODO */
@@ -25304,7 +25308,7 @@
 			wildIDs++;
 			/*
 			* SPEC (cvc-complex-type)
-			* (5.2) "If ·wild IDs· is non-empty, there must not
+			* (5.2) "If �wild IDs� is non-empty, there must not
 			* be any attribute uses among the {attribute uses}
 			* whose {attribute declaration}'s {type definition}
 			* is or is derived from ID."
@@ -25421,7 +25425,7 @@
 	    * VAL TODO: Should we use the *normalized* value? This currently
 	    *   uses the *initial* value.
 	    */
-	    
+
 	    if (defAttrOwnerElem) {
 		xmlChar *normValue;
 		const xmlChar *value;
@@ -25512,9 +25516,9 @@
 	    fixed = 0;
 	/*
 	* SPEC (cvc-attribute)
-	* (3) "The item's ·normalized value· must be locally ·valid·
-	* with respect to that {type definition} as per 
-	* String Valid (§3.14.4)."
+	* (3) "The item's �normalized value� must be locally �valid�
+	* with respect to that {type definition} as per
+	* String Valid (�3.14.4)."
 	*
 	* VAL TODO: Do we already have the
 	* "normalized attribute value" here?
@@ -25534,7 +25538,7 @@
 		iattr->node, iattr->typeDef, iattr->value, NULL,
 		1, 0, 0);
 	}
-	    
+
 	if (res != 0) {
 	    if (res == -1) {
 		VERROR_INT("xmlSchemaVAttributesComplex",
@@ -25549,12 +25553,12 @@
 	    goto eval_idcs;
 	}
 
-	if (fixed) {	    
+	if (fixed) {
 	    /*
 	    * SPEC Attribute Locally Valid (Use) (cvc-au)
-	    * "For an attribute information item to be·valid·
+	    * "For an attribute information item to be�valid�
 	    * with respect to an attribute use its *normalized*
-	    * value· must match the *canonical* lexical
+	    * value� must match the *canonical* lexical
 	    * representation of the attribute use's {value
 	    * constraint}value, if it is present and fixed."
 	    *
@@ -25563,7 +25567,7 @@
 	    */
 	    /*
 	    * SPEC Attribute Locally Valid (cvc-attribute)
-	    * (4) "The item's *actual* value· must match the *value* of
+	    * (4) "The item's *actual* value� must match the *value* of
 	    * the {value constraint}, if it is present and fixed."
 	    */
 	    if (iattr->val == NULL) {
@@ -25655,8 +25659,8 @@
 		xmlSchemaCustomErr(ACTXT_CAST vctxt,
 		    XML_SCHEMAV_CVC_AU, NULL, NULL,
 		    "The value '%s' does not match the fixed "
-		    "value constraint '%s'", 
-		    iattr->value, iattr->vcValue);		
+		    "value constraint '%s'",
+		    iattr->value, iattr->vcValue);
 		break;
 	    case XML_SCHEMAS_ATTR_ERR_WILD_STRICT_NO_DECL:
 		VERROR(XML_SCHEMAV_CVC_WILDCARD, NULL,
@@ -25718,7 +25722,7 @@
 	xmlSchemaElementPtr decl = NULL;
 
 	decl = xmlSchemaGetElem(vctxt->schema,
-	    vctxt->inode->localName, vctxt->inode->nsName);	    
+	    vctxt->inode->localName, vctxt->inode->nsName);
 	if (decl != NULL) {
 	    vctxt->inode->decl = decl;
 	    return (0);
@@ -25776,16 +25780,16 @@
 xmlSchemaCheckCOSValidDefault(xmlSchemaValidCtxtPtr vctxt,
 			      const xmlChar *value,
 			      xmlSchemaValPtr *val)
-{   
+{
     int ret = 0;
     xmlSchemaNodeInfoPtr inode = vctxt->inode;
 
     /*
     * cos-valid-default:
     * Schema Component Constraint: Element Default Valid (Immediate)
-    * For a string to be a valid default with respect to a type 
+    * For a string to be a valid default with respect to a type
     * definition the appropriate case among the following must be true:
-    */    
+    */
     if WXS_IS_COMPLEX(inode->typeDef) {
 	/*
 	* Complex type.
@@ -25793,8 +25797,8 @@
 	* SPEC (2.1) "its {content type} must be a simple type definition
 	* or mixed."
 	* SPEC (2.2.2) "If the {content type} is mixed, then the {content
-	* type}'s particle must be ·emptiable· as defined by 
-	* Particle Emptiable (§3.9.6)."
+	* type}'s particle must be �emptiable� as defined by
+	* Particle Emptiable (�3.9.6)."
 	*/
 	if ((! WXS_HAS_SIMPLE_CONTENT(inode->typeDef)) &&
 	    ((! WXS_HAS_MIXED_CONTENT(inode->typeDef)) ||
@@ -25807,18 +25811,18 @@
 		"or mixed content and a particle emptiable");
 	    return(ret);
 	}
-    }	
+    }
     /*
-    * 1 If the type definition is a simple type definition, then the string 
-    * must be ·valid· with respect to that definition as defined by String 
-    * Valid (§3.14.4).
+    * 1 If the type definition is a simple type definition, then the string
+    * must be �valid� with respect to that definition as defined by String
+    * Valid (�3.14.4).
     *
     * AND
     *
-    * 2.2.1 If the {content type} is a simple type definition, then the 
-    * string must be ·valid· with respect to that simple type definition 
-    * as defined by String Valid (§3.14.4).
-    */  
+    * 2.2.1 If the {content type} is a simple type definition, then the
+    * string must be �valid� with respect to that simple type definition
+    * as defined by String Valid (�3.14.4).
+    */
     if (WXS_IS_SIMPLE(inode->typeDef)) {
 
 	ret = xmlSchemaVCheckCVCSimpleType(ACTXT_CAST vctxt,
@@ -25832,7 +25836,7 @@
     if (ret < 0) {
 	VERROR_INT("xmlSchemaCheckCOSValidDefault",
 	    "calling xmlSchemaVCheckCVCSimpleType()");
-    }    
+    }
     return (ret);
 }
 
@@ -25866,13 +25870,13 @@
 
 static int
 xmlSchemaValidatorPushElem(xmlSchemaValidCtxtPtr vctxt)
-{    
+{
     vctxt->inode = xmlSchemaGetFreshElemInfo(vctxt);
     if (vctxt->inode == NULL) {
 	VERROR_INT("xmlSchemaValidatorPushElem",
 	    "calling xmlSchemaGetFreshElemInfo()");
 	return (-1);
-    }   
+    }
     vctxt->nbAttrInfos = 0;
     return (0);
 }
@@ -25895,7 +25899,7 @@
 
 
 
-/* 
+/*
 * Process END of element.
 */
 static int
@@ -25914,7 +25918,7 @@
 	*/
 	vctxt->skipDepth = vctxt->depth -1;
 	goto end_elem;
-    }    
+    }
     if ((inode->typeDef == NULL) ||
 	(inode->flags & XML_SCHEMA_NODE_INFO_ERR_BAD_TYPE)) {
 	/*
@@ -25934,8 +25938,8 @@
 	* Workaround for "anyType".
 	*/
 	if (inode->typeDef->builtInType == XML_SCHEMAS_ANYTYPE)
-	    goto character_content;			
-	
+	    goto character_content;
+
 	if ((inode->flags & XML_SCHEMA_ELEM_INFO_ERR_BAD_CONTENT) == 0) {
 	    xmlChar *values[10];
 	    int terminal, nbval = 10, nbneg;
@@ -25956,12 +25960,12 @@
 #ifdef DEBUG_AUTOMATA
 		xmlGenericError(xmlGenericErrorContext,
 		    "AUTOMATON create on '%s'\n", inode->localName);
-#endif	    
+#endif
 	    }
 	    /*
 	    * Get hold of the still expected content, since a further
 	    * call to xmlRegExecPushString() will loose this information.
-	    */ 
+	    */
 	    xmlRegExecNextValues(inode->regexCtxt,
 		&nbval, &nbneg, &values[0], &terminal);
 	    ret = xmlRegExecPushString(inode->regexCtxt, NULL, NULL);
@@ -26011,14 +26015,14 @@
 	/*
 	* Speedup if no declaration exists.
 	*/
-	if (WXS_IS_SIMPLE(inode->typeDef)) {	    
+	if (WXS_IS_SIMPLE(inode->typeDef)) {
 	    ret = xmlSchemaVCheckINodeDataType(vctxt,
 		inode, inode->typeDef, inode->value);
 	} else if (WXS_HAS_SIMPLE_CONTENT(inode->typeDef)) {
 	    ret = xmlSchemaVCheckINodeDataType(vctxt,
 		inode, inode->typeDef->contentTypeDef,
 		inode->value);
-	}		
+	}
 	if (ret < 0) {
 	    VERROR_INT("xmlSchemaValidatorPopElem",
 		"calling xmlSchemaVCheckCVCSimpleType()");
@@ -26027,26 +26031,26 @@
 	goto end_elem;
     }
     /*
-    * cvc-elt (3.3.4) : 5 
+    * cvc-elt (3.3.4) : 5
     * The appropriate case among the following must be true:
     */
     /*
-    * cvc-elt (3.3.4) : 5.1 
-    * If the declaration has a {value constraint}, 
-    * the item has neither element nor character [children] and 
+    * cvc-elt (3.3.4) : 5.1
+    * If the declaration has a {value constraint},
+    * the item has neither element nor character [children] and
     * clause 3.2 has not applied, then all of the following must be true:
     */
     if ((inode->decl->value != NULL) &&
-	(inode->flags & XML_SCHEMA_ELEM_INFO_EMPTY) && 
+	(inode->flags & XML_SCHEMA_ELEM_INFO_EMPTY) &&
 	(! INODE_NILLED(inode))) {
 	/*
-	* cvc-elt (3.3.4) : 5.1.1 
-	* If the ·actual type definition· is a ·local type definition·
+	* cvc-elt (3.3.4) : 5.1.1
+	* If the �actual type definition� is a �local type definition�
 	* then the canonical lexical representation of the {value constraint}
-	* value must be a valid default for the ·actual type definition· as 
-	* defined in Element Default Valid (Immediate) (§3.3.6). 
+	* value must be a valid default for the �actual type definition� as
+	* defined in Element Default Valid (Immediate) (�3.3.6).
 	*/
-	/* 
+	/*
 	* NOTE: 'local' above means types acquired by xsi:type.
 	* NOTE: Although the *canonical* value is stated, it is not
 	* relevant if canonical or not. Additionally XML Schema 1.1
@@ -26069,22 +26073,22 @@
 	    * (see following).
 	    */
 	    goto default_psvi;
-	}	
+	}
 	/*
-	* cvc-elt (3.3.4) : 5.1.2 
-	* The element information item with the canonical lexical 
-	* representation of the {value constraint} value used as its 
-	* ·normalized value· must be ·valid· with respect to the 
-	* ·actual type definition· as defined by Element Locally Valid (Type)
-	* (§3.3.4).
-	*/	    
+	* cvc-elt (3.3.4) : 5.1.2
+	* The element information item with the canonical lexical
+	* representation of the {value constraint} value used as its
+	* �normalized value� must be �valid� with respect to the
+	* �actual type definition� as defined by Element Locally Valid (Type)
+	* (�3.3.4).
+	*/
 	if (WXS_IS_SIMPLE(inode->typeDef)) {
 	    ret = xmlSchemaVCheckINodeDataType(vctxt,
 		inode, inode->typeDef, inode->decl->value);
 	} else if (WXS_HAS_SIMPLE_CONTENT(inode->typeDef)) {
 	    ret = xmlSchemaVCheckINodeDataType(vctxt,
 		inode, inode->typeDef->contentTypeDef,
-		inode->decl->value);	    
+		inode->decl->value);
 	}
 	if (ret != 0) {
 	    if (ret < 0) {
@@ -26105,7 +26109,7 @@
 	    xmlChar *normValue;
 	    /*
 	    * VAL TODO: Normalize the value.
-	    */	    
+	    */
 	    normValue = xmlSchemaNormalizeValue(inode->typeDef,
 		inode->decl->value);
 	    if (normValue != NULL) {
@@ -26118,42 +26122,42 @@
 		    "calling xmlNewText()");
 		goto internal_error;
 	    } else
-		xmlAddChild(inode->node, textChild);	    
+		xmlAddChild(inode->node, textChild);
 	}
-	
-    } else if (! INODE_NILLED(inode)) {	
+
+    } else if (! INODE_NILLED(inode)) {
 	/*
-	* 5.2.1 The element information item must be ·valid· with respect 
-	* to the ·actual type definition· as defined by Element Locally 
-	* Valid (Type) (§3.3.4).
-	*/	
+	* 5.2.1 The element information item must be �valid� with respect
+	* to the �actual type definition� as defined by Element Locally
+	* Valid (Type) (�3.3.4).
+	*/
 	if (WXS_IS_SIMPLE(inode->typeDef)) {
 	     /*
 	    * SPEC (cvc-type) (3.1)
 	    * "If the type definition is a simple type definition, ..."
 	    * (3.1.3) "If clause 3.2 of Element Locally Valid
-	    * (Element) (§3.3.4) did not apply, then the ·normalized value·
-	    * must be ·valid· with respect to the type definition as defined
-	    * by String Valid (§3.14.4).
-	    */	    
+	    * (Element) (�3.3.4) did not apply, then the �normalized value�
+	    * must be �valid� with respect to the type definition as defined
+	    * by String Valid (�3.14.4).
+	    */
 	    ret = xmlSchemaVCheckINodeDataType(vctxt,
 		    inode, inode->typeDef, inode->value);
 	} else if (WXS_HAS_SIMPLE_CONTENT(inode->typeDef)) {
 	    /*
 	    * SPEC (cvc-type) (3.2) "If the type definition is a complex type
 	    * definition, then the element information item must be
-	    * ·valid· with respect to the type definition as per
-	    * Element Locally Valid (Complex Type) (§3.4.4);"
+	    * �valid� with respect to the type definition as per
+	    * Element Locally Valid (Complex Type) (�3.4.4);"
 	    *
 	    * SPEC (cvc-complex-type) (2.2)
-	    * "If the {content type} is a simple type definition, ... 
-	    * the ·normalized value· of the element information item is
-	    * ·valid· with respect to that simple type definition as
-	    * defined by String Valid (§3.14.4)."
+	    * "If the {content type} is a simple type definition, ...
+	    * the �normalized value� of the element information item is
+	    * �valid� with respect to that simple type definition as
+	    * defined by String Valid (�3.14.4)."
 	    */
 	    ret = xmlSchemaVCheckINodeDataType(vctxt,
 		inode, inode->typeDef->contentTypeDef, inode->value);
-	}	
+	}
 	if (ret != 0) {
 	    if (ret < 0) {
 		VERROR_INT("xmlSchemaValidatorPopElem",
@@ -26163,7 +26167,7 @@
 	    goto end_elem;
 	}
 	/*
-	* 5.2.2 If there is a fixed {value constraint} and clause 3.2 has 
+	* 5.2.2 If there is a fixed {value constraint} and clause 3.2 has
 	* not applied, all of the following must be true:
 	*/
 	if ((inode->decl->value != NULL) &&
@@ -26174,7 +26178,7 @@
 	    * done on computed values.
 	    */
 	    /*
-	    * 5.2.2.1 The element information item must have no element 
+	    * 5.2.2.1 The element information item must have no element
 	    * information item [children].
 	    */
 	    if (inode->flags &
@@ -26186,28 +26190,28 @@
 		goto end_elem;
 	    } else {
 		/*
-		* 5.2.2.2 The appropriate case among the following must 
+		* 5.2.2.2 The appropriate case among the following must
 		* be true:
-		*/		
+		*/
 		if (WXS_HAS_MIXED_CONTENT(inode->typeDef)) {
 		    /*
-		    * 5.2.2.2.1 If the {content type} of the ·actual type 
-		    * definition· is mixed, then the *initial value* of the 
-		    * item must match the canonical lexical representation 
+		    * 5.2.2.2.1 If the {content type} of the �actual type
+		    * definition� is mixed, then the *initial value* of the
+		    * item must match the canonical lexical representation
 		    * of the {value constraint} value.
 		    *
-		    * ... the *initial value* of an element information 
-		    * item is the string composed of, in order, the 
-		    * [character code] of each character information item in 
+		    * ... the *initial value* of an element information
+		    * item is the string composed of, in order, the
+		    * [character code] of each character information item in
 		    * the [children] of that element information item.
-		    */		   
+		    */
 		    if (! xmlStrEqual(inode->value, inode->decl->value)){
-			/* 
+			/*
 			* VAL TODO: Report invalid & expected values as well.
 			* VAL TODO: Implement the canonical stuff.
 			*/
 			ret = XML_SCHEMAV_CVC_ELT_5_2_2_2_1;
-			xmlSchemaCustomErr(ACTXT_CAST vctxt, 
+			xmlSchemaCustomErr(ACTXT_CAST vctxt,
 			    ret, NULL, NULL,
 			    "The initial value '%s' does not match the fixed "
 			    "value constraint '%s'",
@@ -26216,9 +26220,9 @@
 		    }
 		} else if (WXS_HAS_SIMPLE_CONTENT(inode->typeDef)) {
 		    /*
-		    * 5.2.2.2.2 If the {content type} of the ·actual type 
-		    * definition· is a simple type definition, then the 
-		    * *actual value* of the item must match the canonical 
+		    * 5.2.2.2.2 If the {content type} of the �actual type
+		    * definition� is a simple type definition, then the
+		    * *actual value* of the item must match the canonical
 		    * lexical representation of the {value constraint} value.
 		    */
 		    /*
@@ -26233,16 +26237,16 @@
 			xmlSchemaCustomErr(ACTXT_CAST vctxt,
 			    ret, NULL, NULL,
 			    "The actual value '%s' does not match the fixed "
-			    "value constraint '%s'", 
+			    "value constraint '%s'",
 			    inode->value,
 			    inode->decl->value);
 			goto end_elem;
-		    }		    
+		    }
 		}
-	    }	    
+	    }
 	}
     }
-    
+
 end_elem:
     if (vctxt->depth < 0) {
 	/* TODO: raise error? */
@@ -26252,15 +26256,15 @@
 	vctxt->skipDepth = -1;
     /*
     * Evaluate the history of XPath state objects.
-    */    
+    */
     if (inode->appliedXPath &&
 	(xmlSchemaXPathProcessHistory(vctxt, vctxt->depth) == -1))
 	goto internal_error;
     /*
     * MAYBE TODO:
-    * SPEC (6) "The element information item must be ·valid· with
+    * SPEC (6) "The element information item must be �valid� with
     * respect to each of the {identity-constraint definitions} as per
-    * Identity-constraint Satisfied (§3.11.4)."
+    * Identity-constraint Satisfied (�3.11.4)."
     */
     /*
     * PSVI TODO: If we expose IDC node-tables via PSVI then the tables
@@ -26268,7 +26272,7 @@
     *   We will currently build IDC node-tables and bubble them only if
     *   keyrefs do exist.
     */
-    
+
     /*
     * Add the current IDC target-nodes to the IDC node-tables.
     */
@@ -26302,7 +26306,7 @@
 	    */
 	    if (xmlSchemaBubbleIDCNodeTables(vctxt) == -1)
 		goto internal_error;
-	}	
+	}
     }
     /*
     * Clear the current ielem.
@@ -26335,11 +26339,11 @@
 	    aidc = aidc->next;
 	} while (aidc != NULL);
     }
-    vctxt->depth--;        
+    vctxt->depth--;
     vctxt->inode = vctxt->elemInfos[vctxt->depth];
     /*
-    * VAL TODO: 7 If the element information item is the ·validation root·, it must be 
-    * ·valid· per Validation Root Valid (ID/IDREF) (§3.3.4).
+    * VAL TODO: 7 If the element information item is the �validation root�, it must be
+    * �valid� per Validation Root Valid (ID/IDREF) (�3.3.4).
     */
     return (ret);
 
@@ -26420,11 +26424,11 @@
 		 * Fallback to "anyType".
 		 *
 		 * SPEC (cvc-assess-elt)
-		 * "If the item cannot be ·strictly assessed·, [...]
+		 * "If the item cannot be �strictly assessed�, [...]
 		 * an element information item's schema validity may be laxly
-		 * assessed if its ·context-determined declaration· is not
-		 * skip by ·validating· with respect to the ·ur-type
-		 * definition· as per Element Locally Valid (Type) (§3.3.4)."
+		 * assessed if its �context-determined declaration� is not
+		 * skip by �validating� with respect to the �ur-type
+		 * definition� as per Element Locally Valid (Type) (�3.3.4)."
 		*/
 		vctxt->inode->typeDef =
 		    xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYTYPE);
@@ -26496,9 +26500,9 @@
 	    * SPEC (2.4) "If the {content type} is element-only or mixed,
 	    * then the sequence of the element information item's
 	    * element information item [children], if any, taken in
-	    * order, is ·valid· with respect to the {content type}'s
+	    * order, is �valid� with respect to the {content type}'s
 	    * particle, as defined in Element Sequence Locally Valid
-	    * (Particle) (§3.9.4)."
+	    * (Particle) (�3.9.4)."
 	    */
 	    ret = xmlRegExecPushString2(regexCtxt,
 		vctxt->inode->localName,
@@ -26595,7 +26599,7 @@
     if (consumed != NULL)
 	*consumed = 0;
     if (INODE_NILLED(vctxt->inode)) {
-	/* 
+	/*
 	* SPEC cvc-elt (3.3.4 - 3.2.1)
 	* "The element information item must have no character or
 	* element information item [children]."
@@ -26611,7 +26615,7 @@
     * information item [children]."
     */
     if (vctxt->inode->typeDef->contentType ==
-	    XML_SCHEMA_CONTENT_EMPTY) {    
+	    XML_SCHEMA_CONTENT_EMPTY) {
 	VERROR(XML_SCHEMAV_CVC_COMPLEX_TYPE_2_1, NULL,
 	    "Character content is not allowed, "
 	    "because the content type is empty");
@@ -26622,12 +26626,12 @@
 	    XML_SCHEMA_CONTENT_ELEMENTS) {
 	if ((nodeType != XML_TEXT_NODE) ||
 	    (! xmlSchemaIsBlank((xmlChar *) value, len))) {
-	    /* 
-	    * SPEC cvc-complex-type (2.3) 
-	    * "If the {content type} is element-only, then the 
-	    * element information item has no character information 
-	    * item [children] other than those whose [character 
-	    * code] is defined as a white space in [XML 1.0 (Second 
+	    /*
+	    * SPEC cvc-complex-type (2.3)
+	    * "If the {content type} is element-only, then the
+	    * element information item has no character information
+	    * item [children] other than those whose [character
+	    * code] is defined as a white space in [XML 1.0 (Second
 	    * Edition)]."
 	    */
 	    VERROR(XML_SCHEMAV_CVC_COMPLEX_TYPE_2_3, NULL,
@@ -26637,7 +26641,7 @@
 	}
 	return (0);
     }
-    
+
     if ((value == NULL) || (value[0] == 0))
 	return (0);
     /*
@@ -26649,7 +26653,7 @@
 	((vctxt->inode->decl == NULL) ||
 	(vctxt->inode->decl->value == NULL)))
 	return (0);
-    
+
     if (vctxt->inode->value == NULL) {
 	/*
 	* Set the value.
@@ -26692,7 +26696,7 @@
 	    len = xmlStrlen(value);
 	/*
 	* Concat the value.
-	*/	
+	*/
 	if (vctxt->inode->flags & XML_SCHEMA_NODE_INFO_FLAG_OWNED_VALUES) {
 	    vctxt->inode->value = BAD_CAST xmlStrncat(
 		(xmlChar *) vctxt->inode->value, value, len);
@@ -26701,7 +26705,7 @@
 		BAD_CAST xmlStrncatNew(vctxt->inode->value, value, len);
 	    vctxt->inode->flags |= XML_SCHEMA_NODE_INFO_FLAG_OWNED_VALUES;
 	}
-    }	
+    }
 
     return (0);
 }
@@ -26718,7 +26722,7 @@
 	goto internal_error;
     }
     if (vctxt->xsiAssemble) {
-	/* 
+	/*
 	* We will stop validation if there was an error during
 	* dynamic schema construction.
 	* Note that we simply set @skipDepth to 0, this could
@@ -26831,12 +26835,12 @@
     	VERROR(ret, NULL,
     	    "The type definition is absent");
 	goto exit;
-    }    
+    }
     if (vctxt->inode->typeDef->flags & XML_SCHEMAS_TYPE_ABSTRACT) {
 	vctxt->inode->flags |= XML_SCHEMA_NODE_INFO_ERR_BAD_TYPE;
 	ret = XML_SCHEMAV_CVC_TYPE_2;
     	    VERROR(ret, NULL,
-    	    "The type definition is abstract");	
+    	    "The type definition is abstract");
 	goto exit;
     }
     /*
@@ -26917,7 +26921,7 @@
 	nodeType = xmlTextReaderNodeType(vctxt->reader);
 
 	if (nodeType == XML_ELEMENT_NODE) {
-	    
+
 	    vctxt->depth++;
 	    if (xmlSchemaValidatorPushElem(vctxt) == -1) {
 		VERROR_INT("xmlSchemaVReaderWalk",
@@ -27092,8 +27096,8 @@
 * Process text content.
 */
 static void
-xmlSchemaSAXHandleText(void *ctx, 
-		       const xmlChar * ch, 
+xmlSchemaSAXHandleText(void *ctx,
+		       const xmlChar * ch,
 		       int len)
 {
     xmlSchemaValidCtxtPtr vctxt = (xmlSchemaValidCtxtPtr) ctx;
@@ -27117,10 +27121,10 @@
 * Process CDATA content.
 */
 static void
-xmlSchemaSAXHandleCDataSection(void *ctx, 
-			     const xmlChar * ch, 
+xmlSchemaSAXHandleCDataSection(void *ctx,
+			     const xmlChar * ch,
 			     int len)
-{   
+{
     xmlSchemaValidCtxtPtr vctxt = (xmlSchemaValidCtxtPtr) ctx;
 
     if (vctxt->depth < 0)
@@ -27154,20 +27158,20 @@
 
 static void
 xmlSchemaSAXHandleStartElementNs(void *ctx,
-				 const xmlChar * localname, 
-				 const xmlChar * prefix ATTRIBUTE_UNUSED, 
-				 const xmlChar * URI, 
-				 int nb_namespaces, 
-				 const xmlChar ** namespaces, 
-				 int nb_attributes, 
-				 int nb_defaulted ATTRIBUTE_UNUSED, 
+				 const xmlChar * localname,
+				 const xmlChar * prefix ATTRIBUTE_UNUSED,
+				 const xmlChar * URI,
+				 int nb_namespaces,
+				 const xmlChar ** namespaces,
+				 int nb_attributes,
+				 int nb_defaulted ATTRIBUTE_UNUSED,
 				 const xmlChar ** attributes)
-{  
+{
     xmlSchemaValidCtxtPtr vctxt = (xmlSchemaValidCtxtPtr) ctx;
     int ret;
     xmlSchemaNodeInfoPtr ielem;
     int i, j;
-    
+
     /*
     * SAX VAL TODO: What to do with nb_defaulted?
     */
@@ -27195,16 +27199,16 @@
     ielem->flags |= XML_SCHEMA_ELEM_INFO_EMPTY;
     /*
     * Register namespaces on the elem info.
-    */    
+    */
     if (nb_namespaces != 0) {
 	/*
 	* Although the parser builds its own namespace list,
 	* we have no access to it, so we'll use an own one.
 	*/
-        for (i = 0, j = 0; i < nb_namespaces; i++, j += 2) {	    
+        for (i = 0, j = 0; i < nb_namespaces; i++, j += 2) {
 	    /*
 	    * Store prefix and namespace name.
-	    */	   
+	    */
 	    if (ielem->nsBindings == NULL) {
 		ielem->nsBindings =
 		    (const xmlChar **) xmlMalloc(10 *
@@ -27240,7 +27244,7 @@
 	    } else
 		ielem->nsBindings[ielem->nbNsBindings * 2 + 1] =
 		    namespaces[j+1];
-	    ielem->nbNsBindings++;	    	    
+	    ielem->nbNsBindings++;
 	}
     }
     /*
@@ -27254,7 +27258,7 @@
         for (j = 0, i = 0; i < nb_attributes; i++, j += 5) {
 	    /*
 	    * Duplicate the value.
-	    */	 
+	    */
 	    value = xmlStrndup(attributes[j+3],
 		attributes[j+4] - attributes[j+3]);
 	    /*
@@ -27281,7 +27285,7 @@
 	    goto internal_error;
 	}
 	goto exit;
-    }    
+    }
 
 exit:
     return;
@@ -27391,7 +27395,7 @@
 #ifdef LIBXML_READER_ENABLED
     vctxt->reader = NULL;
 #endif
-    vctxt->hasKeyrefs = 0;    
+    vctxt->hasKeyrefs = 0;
 
     if (vctxt->value != NULL) {
         xmlSchemaFreeValue(vctxt->value);
@@ -27461,7 +27465,7 @@
 		break;
 	    xmlSchemaClearElemInfo(vctxt, ei);
 	}
-    }    
+    }
     xmlSchemaItemListClear(vctxt->nodeQNames);
     /* Recreate the dict. */
     xmlDictFree(vctxt->dict);
@@ -27563,7 +27567,7 @@
  * @ctxt: the schema validation context
  *
  * Check if any error was detected during validation.
- * 
+ *
  * Returns 1 if valid so far, 0 if errors were detected, and -1 in case
  *         of internal error.
  */
@@ -27622,7 +27626,7 @@
 
 /**
  * xmlSchemaGetValidErrors:
- * @ctxt:	a XML-Schema validation context
+ * @ctxt: a XML-Schema validation context
  * @err: the error function result
  * @warn: the warning function result
  * @ctx: the functions context result
@@ -27683,7 +27687,7 @@
 
 /**
  * xmlSchemaValidCtxtGetOptions:
- * @ctxt:	a schema validation context
+ * @ctxt: a schema validation context
  *
  * Get the validation context options.
  *
@@ -27751,7 +27755,7 @@
 			nsName = NULL;
 		    ret = xmlSchemaValidatorPushAttribute(vctxt,
 			(xmlNodePtr) attr,
-			/* 
+			/*
 			* Note that we give it the line number of the
 			* parent element.
 			*/
@@ -27807,7 +27811,7 @@
 	    (node->type == XML_ENTITY_REF_NODE)) {
 	    /*
 	    * DOC VAL TODO: What to do with entities?
-	    */	    
+	    */
 	    VERROR_INT("xmlSchemaVDocWalk",
 		"there is at least one entity reference in the node-tree "
 		"currently being validated. Processing of entities with "
@@ -27867,7 +27871,7 @@
 xmlSchemaPreRun(xmlSchemaValidCtxtPtr vctxt) {
     /*
     * Some initialization.
-    */    
+    */
     vctxt->err = 0;
     vctxt->nberrors = 0;
     vctxt->depth = -1;
@@ -27884,9 +27888,9 @@
     */
     if (vctxt->schema == NULL) {
 	xmlSchemaParserCtxtPtr pctxt;
-	
+
 	vctxt->xsiAssemble = 1;
-	/* 
+	/*
 	* If not schema was given then we will create a schema
 	* dynamically using XSI schema locations.
 	*
@@ -27902,8 +27906,8 @@
 	*/
 	vctxt->schema = xmlSchemaNewSchema(pctxt);
 	if (vctxt->schema == NULL)
-	    return (-1);		
-	/* 
+	    return (-1);
+	/*
 	* Create the schema construction context.
 	*/
 	pctxt->constructor = xmlSchemaConstructionCtxtCreate(pctxt->dict);
@@ -27914,13 +27918,13 @@
 	* Take ownership of the constructor to be able to free it.
 	*/
 	pctxt->ownsConstructor = 1;
-    }	
-    /* 
-    * Augment the IDC definitions for the main schema and all imported ones 
+    }
+    /*
+    * Augment the IDC definitions for the main schema and all imported ones
     * NOTE: main schema if the first in the imported list
     */
     xmlHashScan(vctxt->schema->schemasImports,(xmlHashScanner)xmlSchemaAugmentImportedIDC, vctxt);
-    
+
     return(0);
 }
 
@@ -28108,8 +28112,8 @@
 {
     xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx;
     if ((ctxt != NULL) && (ctxt->user_sax != NULL) &&
-        (ctxt->user_sax->internalSubset != NULL))
-	ctxt->user_sax->internalSubset(ctxt->user_data, name, ExternalID,
+        (ctxt->user_sax->externalSubset != NULL))
+	ctxt->user_sax->externalSubset(ctxt->user_data, name, ExternalID,
 	                               SystemID);
 }
 
@@ -28315,8 +28319,8 @@
     if (ctxt == NULL)
         return;
     if ((ctxt->user_sax != NULL) &&
-        (ctxt->user_sax->ignorableWhitespace != NULL))
-	ctxt->user_sax->ignorableWhitespace(ctxt->user_data, value, len);
+        (ctxt->user_sax->cdataBlock != NULL))
+	ctxt->user_sax->cdataBlock(ctxt->user_data, value, len);
     if (ctxt->ctxt != NULL)
 	xmlSchemaSAXHandleCDataSection(ctxt->ctxt, value, len);
 }
@@ -28335,10 +28339,10 @@
 }
 
 static void
-startElementNsSplit(void *ctx, const xmlChar * localname, 
-		    const xmlChar * prefix, const xmlChar * URI, 
-		    int nb_namespaces, const xmlChar ** namespaces, 
-		    int nb_attributes, int nb_defaulted, 
+startElementNsSplit(void *ctx, const xmlChar * localname,
+		    const xmlChar * prefix, const xmlChar * URI,
+		    int nb_namespaces, const xmlChar ** namespaces,
+		    int nb_attributes, int nb_defaulted,
 		    const xmlChar ** attributes) {
     xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx;
     if (ctxt == NULL)
@@ -28357,7 +28361,7 @@
 }
 
 static void
-endElementNsSplit(void *ctx, const xmlChar * localname, 
+endElementNsSplit(void *ctx, const xmlChar * localname,
 		    const xmlChar * prefix, const xmlChar * URI) {
     xmlSchemaSAXPlugPtr ctxt = (xmlSchemaSAXPlugPtr) ctx;
     if (ctxt == NULL)
@@ -28398,7 +28402,7 @@
     old_sax = *sax;
     if ((old_sax != NULL) && (old_sax->initialized != XML_SAX2_MAGIC))
         return(NULL);
-    if ((old_sax != NULL) && 
+    if ((old_sax != NULL) &&
         (old_sax->startElementNs == NULL) && (old_sax->endElementNs == NULL) &&
         ((old_sax->startElement != NULL) || (old_sax->endElement != NULL)))
         return(NULL);
@@ -28416,7 +28420,7 @@
     ret->ctxt = ctxt;
     ret->user_sax_ptr = sax;
     ret->user_sax = old_sax;
-    if (old_sax == NULL) {	
+    if (old_sax == NULL) {
         /*
 	 * go direct, no need for the split block and functions.
 	 */
@@ -28437,7 +28441,7 @@
     } else {
        /*
         * for each callback unused by Schemas initialize it to the Split
-	* routine only if non NULL in the user block, this can speed up 
+	* routine only if non NULL in the user block, this can speed up
 	* things at the SAX level.
 	*/
         if (old_sax->internalSubset != NULL)
@@ -28590,7 +28594,7 @@
     if (options)
         xmlCtxtUseOptions(pctxt, options);
 #endif
-    pctxt->linenumbers = 1;    
+    pctxt->linenumbers = 1;
 
     inputStream = xmlNewIOInputStream(pctxt, input, enc);;
     if (inputStream == NULL) {
@@ -28619,7 +28623,7 @@
 	ret = ctxt->parserCtxt->errNo;
 	if (ret == 0)
 	    ret = 1;
-    }    
+    }
 
 done:
     ctxt->parserCtxt = NULL;
@@ -28658,16 +28662,33 @@
 
     if ((ctxt == NULL) || (filename == NULL))
         return (-1);
-    
+
     input = xmlParserInputBufferCreateFilename(filename,
 	XML_CHAR_ENCODING_NONE);
     if (input == NULL)
 	return (-1);
     ret = xmlSchemaValidateStream(ctxt, input, XML_CHAR_ENCODING_NONE,
-	NULL, NULL);    
+	NULL, NULL);
     return (ret);
 }
 
+/**
+ * xmlSchemaValidCtxtGetParserCtxt:
+ * @ctxt: a schema validation context
+ *
+ * allow access to the parser context of the schema validation context
+ *
+ * Returns the parser context of the schema validation context or NULL
+ *         in case of error.
+ */
+xmlParserCtxtPtr
+xmlSchemaValidCtxtGetParserCtxt(xmlSchemaValidCtxtPtr ctxt)
+{
+    if (ctxt == NULL)
+        return(NULL);
+    return (ctxt->parserCtxt);
+}
+
 #define bottom_xmlschemas
 #include "elfgcchack.h"
 #endif /* LIBXML_SCHEMAS_ENABLED */
diff --git a/xmlschemastypes.c b/xmlschemastypes.c
index a35c539..0d967d0 100644
--- a/xmlschemastypes.c
+++ b/xmlschemastypes.c
@@ -2063,7 +2063,7 @@
  * Parse an unsigned long into 3 fields.
  *
  * Returns the number of significant digits in the number or
- * -1 if overflow of the capacity
+ * -1 if overflow of the capacity and -2 if it's not a number.
  */
 static int
 xmlSchemaParseUInt(const xmlChar **str, unsigned long *llo,
@@ -2072,6 +2072,9 @@
     const xmlChar *tmp, *cur = *str;
     int ret = 0, i = 0;
 
+    if (!((*cur >= '0') && (*cur <= '9'))) 
+        return(-2);
+
     while (*cur == '0') {        /* ignore leading zeroes */
         cur++;
     }
@@ -2342,9 +2345,9 @@
 			    * Terminate the (preparsed) string.
 			    */
 			    if (len != 0) {
-				*cptr = 0; 
+				*cptr = 0;
 				cptr = cval;
-				
+
 				xmlSchemaParseUInt((const xmlChar **)&cptr,
 				    &v->value.decimal.lo,
 				    &v->value.decimal.mi,
@@ -3116,7 +3119,7 @@
                 } else if (*cur == '+')
                     cur++;
                 ret = xmlSchemaParseUInt(&cur, &lo, &mi, &hi);
-                if (ret == -1)
+                if (ret < 0)
                     goto return1;
 		if (normOnTheFly)
 		    while IS_WSP_BLANK_CH(*cur) cur++;
@@ -3161,7 +3164,7 @@
         case XML_SCHEMAS_BYTE:
         case XML_SCHEMAS_SHORT:
         case XML_SCHEMAS_INT:{
-                 const xmlChar *cur = value;
+                const xmlChar *cur = value;
                 unsigned long lo, mi, hi;
                 int sign = 0;
 
diff --git a/xmlwriter.c b/xmlwriter.c
index 2d9d109..b88de3a 100644
--- a/xmlwriter.c
+++ b/xmlwriter.c
@@ -626,9 +626,10 @@
  * xmlTextWriterEndDocument:
  * @writer:  the xmlTextWriterPtr
  *
- * End an xml document. All open elements are closed
+ * End an xml document. All open elements are closed, and
+ * the content is flushed to the output.
  *
- * Returns the bytes written (may be 0 because of buffering) or -1 in case of error
+ * Returns the bytes written or -1 in case of error
  */
 int
 xmlTextWriterEndDocument(xmlTextWriterPtr writer)
@@ -702,6 +703,9 @@
             return -1;
         sum += count;
     }
+
+    sum += xmlTextWriterFlush(writer);
+
     return sum;
 }
 
@@ -1236,8 +1240,16 @@
             if (count < 0)
                 return -1;
             sum += count;
+            if (writer->indent)
+                writer->doindent = 0;
             /* fallthrough */
         case XML_TEXTWRITER_TEXT:
+            if ((writer->indent) && (writer->doindent)) {
+                count = xmlTextWriterWriteIndent(writer);
+                sum += count;
+                writer->doindent = 1;
+            } else
+                writer->doindent = 1;
             count = xmlOutputBufferWriteString(writer->out, "</");
             if (count < 0)
                 return -1;
@@ -2610,6 +2622,7 @@
         if (p != 0) {
             switch (p->state) {
                 case XML_TEXTWRITER_NONE:
+		case XML_TEXTWRITER_TEXT:
                 case XML_TEXTWRITER_PI:
                 case XML_TEXTWRITER_PI_TEXT:
                     break;
diff --git a/xpath.c b/xpath.c
index 22a3f9d..57442e6 100644
--- a/xpath.c
+++ b/xpath.c
@@ -59,7 +59,7 @@
 #define XPATH_STREAMING
 #endif
 
-#define TODO 								\
+#define TODO								\
     xmlGenericError(xmlGenericErrorContext,				\
 	    "Unimplemented block at %s:%d\n",				\
             __FILE__, __LINE__);
@@ -79,7 +79,7 @@
 * XP_OPTIMIZED_FILTER_FIRST:
 * If defined, this will optimize expressions like "key('foo', 'val')[b][1]"
 * in a way, that it stop evaluation at the first node.
-*/ 
+*/
 #define XP_OPTIMIZED_FILTER_FIRST
 
 /*
@@ -99,9 +99,9 @@
 #if defined(LIBXML_XPATH_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED)
 
 /************************************************************************
- * 									*
- * 			Floating point stuff				*
- * 									*
+ *									*
+ *			Floating point stuff				*
+ *									*
  ************************************************************************/
 
 #ifndef TRIO_REPLACE_STDIO
@@ -142,7 +142,7 @@
  * Provides a portable isnan() function to detect whether a double
  * is a NotaNumber. Based on trio code
  * http://sourceforge.net/projects/ctrio/
- * 
+ *
  * Returns 1 if the value is a NaN, 0 otherwise
  */
 int
@@ -157,7 +157,7 @@
  * Provides a portable isinf() function to detect whether a double
  * is a +Infinite or -Infinite. Based on trio code
  * http://sourceforge.net/projects/ctrio/
- * 
+ *
  * Returns 1 vi the value is +Infinite, -1 if -Infinite, 0 otherwise
  */
 int
@@ -174,7 +174,7 @@
  * Provides a portable function to detect the sign of a double
  * Modified from trio code
  * http://sourceforge.net/projects/ctrio/
- * 
+ *
  * Returns 1 if the value is Negative, 0 if positive
  */
 static int
@@ -187,11 +187,11 @@
  * TODO: when compatibility allows remove all "fake node libxslt" strings
  *       the test should just be name[0] = ' '
  */
-/* #define DEBUG */
-/* #define DEBUG_STEP */
-/* #define DEBUG_STEP_NTH */
-/* #define DEBUG_EXPR */
-/* #define DEBUG_EVAL_COUNTS */
+#ifdef DEBUG_XPATH_EXPRESSION
+#define DEBUG_STEP
+#define DEBUG_EXPR
+#define DEBUG_EVAL_COUNTS
+#endif
 
 static xmlNs xmlXPathXMLNamespaceStruct = {
     NULL,
@@ -203,7 +203,7 @@
 };
 static xmlNsPtr xmlXPathXMLNamespace = &xmlXPathXMLNamespaceStruct;
 #ifndef LIBXML_THREAD_ENABLED
-/* 
+/*
  * Optimizer is disabled only when threaded apps are detected while
  * the library ain't compiled for thread safety.
  */
@@ -350,7 +350,7 @@
     }
 
     /* cleanup current last error */
-    xmlResetError(&ctxt->context->lastError); 
+    xmlResetError(&ctxt->context->lastError);
 
     ctxt->context->lastError.domain = XML_FROM_XPATH;
     ctxt->context->lastError.code = error + XML_XPATH_EXPRESSION_OK -
@@ -390,9 +390,9 @@
 }
 
 /************************************************************************
- * 									*
- * 			Utilities	    				*
- * 									*
+ *									*
+ *			Utilities					*
+ *									*
  ************************************************************************/
 
 /**
@@ -412,7 +412,7 @@
 * and here, we should make the functions public.
 */
 static int
-xmlPointerListAddSize(xmlPointerListPtr list,		       
+xmlPointerListAddSize(xmlPointerListPtr list,
 		       void *item,
 		       int initialSize)
 {
@@ -486,9 +486,9 @@
 }
 
 /************************************************************************
- * 									*
- * 			Parser Types					*
- * 									*
+ *									*
+ *			Parser Types					*
+ *									*
  ************************************************************************/
 
 /*
@@ -533,7 +533,7 @@
     AXIS_PARENT,
     AXIS_PRECEDING,
     AXIS_PRECEDING_SIBLING,
-    AXIS_SELF    
+    AXIS_SELF
 } xmlXPathAxisVal;
 
 typedef enum {
@@ -549,7 +549,7 @@
     NODE_TYPE_NODE = 0,
     NODE_TYPE_COMMENT = XML_COMMENT_NODE,
     NODE_TYPE_TEXT = XML_TEXT_NODE,
-    NODE_TYPE_PI = XML_PI_NODE   
+    NODE_TYPE_PI = XML_PI_NODE
 } xmlXPathTypeVal;
 
 #define XP_REWRITE_DOS_CHILD_ELEM 1
@@ -587,9 +587,9 @@
 };
 
 /************************************************************************
- * 									*
- * 			Forward declarations				*
- * 									*
+ *									*
+ *			Forward declarations				*
+ *									*
  ************************************************************************/
 static void
 xmlXPathFreeValueTree(xmlNodeSetPtr obj);
@@ -604,9 +604,9 @@
 			    int isPredicate);
 
 /************************************************************************
- * 									*
- * 			Parser Type functions 				*
- * 									*
+ *									*
+ *			Parser Type functions				*
+ *									*
  ************************************************************************/
 
 /**
@@ -796,19 +796,19 @@
     xmlXPathCompExprAdd(ctxt->comp, ctxt->comp->last, -1,		\
 	                (op), (val), (val2), (val3), (val4), (val5))
 
-#define PUSH_LEAVE_EXPR(op, val, val2) 					\
+#define PUSH_LEAVE_EXPR(op, val, val2)					\
 xmlXPathCompExprAdd(ctxt->comp, -1, -1, (op), (val), (val2), 0 ,NULL ,NULL)
 
-#define PUSH_UNARY_EXPR(op, ch, val, val2) 				\
+#define PUSH_UNARY_EXPR(op, ch, val, val2)				\
 xmlXPathCompExprAdd(ctxt->comp, (ch), -1, (op), (val), (val2), 0 ,NULL ,NULL)
 
-#define PUSH_BINARY_EXPR(op, ch1, ch2, val, val2) 			\
+#define PUSH_BINARY_EXPR(op, ch1, ch2, val, val2)			\
 xmlXPathCompExprAdd(ctxt->comp, (ch1), (ch2), (op),			\
 			(val), (val2), 0 ,NULL ,NULL)
 
 /************************************************************************
  *									*
- * 		XPath object cache structures				*
+ *		XPath object cache structures				*
  *									*
  ************************************************************************/
 
@@ -840,8 +840,8 @@
     int dbgCachedLocset;
     int dbgCachedUsers;
     int dbgCachedXSLTTree;
-    int dbgCachedUndefined; 
-    
+    int dbgCachedUndefined;
+
 
     int dbgReusedAll;
     int dbgReusedNodeset;
@@ -860,11 +860,11 @@
 
 /************************************************************************
  *									*
- * 		Debugging related functions				*
+ *		Debugging related functions				*
  *									*
  ************************************************************************/
 
-#define STRANGE 							\
+#define STRANGE							\
     xmlGenericError(xmlGenericErrorContext,				\
 	    "Internal error at %s:%d\n",				\
             __FILE__, __LINE__);
@@ -882,7 +882,7 @@
 	fprintf(output, shift);
 	fprintf(output, "Node is NULL !\n");
 	return;
-        
+
     }
 
     if ((cur->type == XML_DOCUMENT_NODE) ||
@@ -907,7 +907,7 @@
 	fprintf(output, shift);
 	fprintf(output, "Node is NULL !\n");
 	return;
-        
+
     }
 
     while (cur != NULL) {
@@ -930,7 +930,7 @@
 	fprintf(output, shift);
 	fprintf(output, "NodeSet is NULL !\n");
 	return;
-        
+
     }
 
     if (cur != NULL) {
@@ -956,7 +956,7 @@
 	fprintf(output, shift);
 	fprintf(output, "Value Tree is NULL !\n");
 	return;
-        
+
     }
 
     fprintf(output, shift);
@@ -977,7 +977,7 @@
 	fprintf(output, shift);
 	fprintf(output, "LocationSet is NULL !\n");
 	return;
-        
+
     }
 
     for (i = 0;i < cur->locNr;i++) {
@@ -1008,7 +1008,7 @@
     shift[2 * i] = shift[2 * i + 1] = 0;
 
 
-    fprintf(output, shift);    
+    fprintf(output, shift);
 
     if (cur == NULL) {
         fprintf(output, "Object is empty (NULL)\n");
@@ -1333,7 +1333,7 @@
 static int xmlXPathDebugObjTotalLocset = 0;
 static int xmlXPathDebugObjTotalUsers = 0;
 static int xmlXPathDebugObjTotalXSLTTree = 0;
-static int xmlXPathDebugObjTotalAll = 0; 
+static int xmlXPathDebugObjTotalAll = 0;
 
 static int xmlXPathDebugObjMaxUndefined = 0;
 static int xmlXPathDebugObjMaxNodeset = 0;
@@ -1366,7 +1366,7 @@
 	    cache->dbgCachedLocset = 0;
 	    cache->dbgCachedUsers = 0;
 	    cache->dbgCachedXSLTTree = 0;
-	    cache->dbgCachedUndefined = 0; 
+	    cache->dbgCachedUndefined = 0;
 
 	    cache->dbgReusedAll = 0;
 	    cache->dbgReusedNodeset = 0;
@@ -1380,7 +1380,7 @@
 	    cache->dbgReusedXSLTTree = 0;
 	    cache->dbgReusedUndefined = 0;
 	}
-    }    
+    }
 
     xmlXPathDebugObjCounterUndefined = 0;
     xmlXPathDebugObjCounterNodeset = 0;
@@ -1393,7 +1393,7 @@
     xmlXPathDebugObjCounterUsers = 0;
     xmlXPathDebugObjCounterXSLTTree = 0;
     xmlXPathDebugObjCounterAll = 0;
-    
+
     xmlXPathDebugObjTotalUndefined = 0;
     xmlXPathDebugObjTotalNodeset = 0;
     xmlXPathDebugObjTotalBool = 0;
@@ -1404,7 +1404,7 @@
     xmlXPathDebugObjTotalLocset = 0;
     xmlXPathDebugObjTotalUsers = 0;
     xmlXPathDebugObjTotalXSLTTree = 0;
-    xmlXPathDebugObjTotalAll = 0; 
+    xmlXPathDebugObjTotalAll = 0;
 
     xmlXPathDebugObjMaxUndefined = 0;
     xmlXPathDebugObjMaxNodeset = 0;
@@ -1430,10 +1430,10 @@
 	if (ctxt->cache != NULL) {
 	    xmlXPathContextCachePtr cache =
 		(xmlXPathContextCachePtr) ctxt->cache;
-	    
+
 	    isCached = 1;
-	    
-	    cache->dbgReusedAll++;	    
+
+	    cache->dbgReusedAll++;
 	    switch (objType) {
 		case XPATH_UNDEFINED:
 		    cache->dbgReusedUndefined++;
@@ -1467,7 +1467,7 @@
 		    break;
 		default:
 		    break;
-	    }	
+	    }
 	}
     }
 
@@ -1475,7 +1475,7 @@
 	case XPATH_UNDEFINED:
 	    if (! isCached)
 		xmlXPathDebugObjTotalUndefined++;
-	    xmlXPathDebugObjCounterUndefined++;	    
+	    xmlXPathDebugObjCounterUndefined++;
 	    if (xmlXPathDebugObjCounterUndefined >
 		xmlXPathDebugObjMaxUndefined)
 		xmlXPathDebugObjMaxUndefined =
@@ -1484,7 +1484,7 @@
 	case XPATH_NODESET:
 	    if (! isCached)
 		xmlXPathDebugObjTotalNodeset++;
-	    xmlXPathDebugObjCounterNodeset++;	    
+	    xmlXPathDebugObjCounterNodeset++;
 	    if (xmlXPathDebugObjCounterNodeset >
 		xmlXPathDebugObjMaxNodeset)
 		xmlXPathDebugObjMaxNodeset =
@@ -1493,7 +1493,7 @@
 	case XPATH_BOOLEAN:
 	    if (! isCached)
 		xmlXPathDebugObjTotalBool++;
-	    xmlXPathDebugObjCounterBool++;	    
+	    xmlXPathDebugObjCounterBool++;
 	    if (xmlXPathDebugObjCounterBool >
 		xmlXPathDebugObjMaxBool)
 		xmlXPathDebugObjMaxBool =
@@ -1502,7 +1502,7 @@
 	case XPATH_NUMBER:
 	    if (! isCached)
 		xmlXPathDebugObjTotalNumber++;
-	    xmlXPathDebugObjCounterNumber++;	    
+	    xmlXPathDebugObjCounterNumber++;
 	    if (xmlXPathDebugObjCounterNumber >
 		xmlXPathDebugObjMaxNumber)
 		xmlXPathDebugObjMaxNumber =
@@ -1511,7 +1511,7 @@
 	case XPATH_STRING:
 	    if (! isCached)
 		xmlXPathDebugObjTotalString++;
-	    xmlXPathDebugObjCounterString++;	    
+	    xmlXPathDebugObjCounterString++;
 	    if (xmlXPathDebugObjCounterString >
 		xmlXPathDebugObjMaxString)
 		xmlXPathDebugObjMaxString =
@@ -1520,7 +1520,7 @@
 	case XPATH_POINT:
 	    if (! isCached)
 		xmlXPathDebugObjTotalPoint++;
-	    xmlXPathDebugObjCounterPoint++;	    
+	    xmlXPathDebugObjCounterPoint++;
 	    if (xmlXPathDebugObjCounterPoint >
 		xmlXPathDebugObjMaxPoint)
 		xmlXPathDebugObjMaxPoint =
@@ -1547,7 +1547,7 @@
 	case XPATH_USERS:
 	    if (! isCached)
 		xmlXPathDebugObjTotalUsers++;
-	    xmlXPathDebugObjCounterUsers++;	    
+	    xmlXPathDebugObjCounterUsers++;
 	    if (xmlXPathDebugObjCounterUsers >
 		xmlXPathDebugObjMaxUsers)
 		xmlXPathDebugObjMaxUsers =
@@ -1556,7 +1556,7 @@
 	case XPATH_XSLT_TREE:
 	    if (! isCached)
 		xmlXPathDebugObjTotalXSLTTree++;
-	    xmlXPathDebugObjCounterXSLTTree++;	    
+	    xmlXPathDebugObjCounterXSLTTree++;
 	    if (xmlXPathDebugObjCounterXSLTTree >
 		xmlXPathDebugObjMaxXSLTTree)
 		xmlXPathDebugObjMaxXSLTTree =
@@ -1585,8 +1585,8 @@
 	    xmlXPathContextCachePtr cache =
 		(xmlXPathContextCachePtr) ctxt->cache;
 
-	    isCached = 1;	    
-	    
+	    isCached = 1;
+
 	    cache->dbgCachedAll++;
 	    switch (objType) {
 		case XPATH_UNDEFINED:
@@ -1622,7 +1622,7 @@
 		default:
 		    break;
 	    }
-	    
+
 	}
     }
     switch (objType) {
@@ -1658,7 +1658,7 @@
 	    break;
 	default:
 	    break;
-    }   
+    }
     xmlXPathDebugObjCounterAll--;
 }
 
@@ -1681,7 +1681,7 @@
     reqNumber = xmlXPathDebugObjTotalNumber;
     reqXSLTTree = xmlXPathDebugObjTotalXSLTTree;
     reqUndefined = xmlXPathDebugObjTotalUndefined;
-    
+
     printf("# XPath object usage:\n");
 
     if (ctxt != NULL) {
@@ -1703,7 +1703,7 @@
 	    reqXSLTTree += reXSLTTree;
 	    reUndefined = cache->dbgReusedUndefined;
 	    reqUndefined += reUndefined;
-	    
+
 	    caAll = cache->dbgCachedAll;
 	    caBool = cache->dbgCachedBool;
 	    caNodeset = cache->dbgCachedNodeset;
@@ -1711,7 +1711,7 @@
 	    caNumber = cache->dbgCachedNumber;
 	    caXSLTTree = cache->dbgCachedXSLTTree;
 	    caUndefined = cache->dbgCachedUndefined;
-	    
+
 	    if (cache->nodesetObjs)
 		leftObjs -= cache->nodesetObjs->number;
 	    if (cache->stringObjs)
@@ -1724,8 +1724,8 @@
 		leftObjs -= cache->miscObjs->number;
 	}
     }
-       
-    printf("# all\n");       
+
+    printf("# all\n");
     printf("#   total  : %d\n", reqAll);
     printf("#   left  : %d\n", leftObjs);
     printf("#   created: %d\n", xmlXPathDebugObjTotalAll);
@@ -1848,7 +1848,7 @@
     if (cache->numberObjs)
 	xmlXPathCacheFreeObjectList(cache->numberObjs);
     if (cache->miscObjs)
-	xmlXPathCacheFreeObjectList(cache->miscObjs);    
+	xmlXPathCacheFreeObjectList(cache->miscObjs);
     xmlFree(cache);
 }
 
@@ -1857,7 +1857,7 @@
  *
  * @ctxt:  the XPath context
  * @active: enables/disables (creates/frees) the cache
- * @value: a value with semantics dependant on @options 
+ * @value: a value with semantics dependant on @options
  * @options: options (currently only the value 0 is used)
  *
  * Creates/frees an object cache on the XPath context.
@@ -1884,7 +1884,7 @@
 	return(-1);
     if (active) {
 	xmlXPathContextCachePtr cache;
-	
+
 	if (ctxt->cache == NULL) {
 	    ctxt->cache = xmlXPathNewCache();
 	    if (ctxt->cache == NULL)
@@ -1919,7 +1919,7 @@
  */
 static xmlXPathObjectPtr
 xmlXPathCacheWrapNodeSet(xmlXPathContextPtr ctxt, xmlNodeSetPtr val)
-{    
+{
     if ((ctxt != NULL) && (ctxt->cache != NULL)) {
 	xmlXPathContextCachePtr cache =
 	    (xmlXPathContextCachePtr) ctxt->cache;
@@ -1928,7 +1928,7 @@
 	    (cache->miscObjs->number != 0))
 	{
 	    xmlXPathObjectPtr ret;
-	    
+
 	    ret = (xmlXPathObjectPtr)
 		cache->miscObjs->items[--cache->miscObjs->number];
 	    ret->type = XPATH_NODESET;
@@ -1936,12 +1936,12 @@
 #ifdef XP_DEBUG_OBJ_USAGE
 	    xmlXPathDebugObjUsageRequested(ctxt, XPATH_NODESET);
 #endif
-	    return(ret);	    
+	    return(ret);
 	}
     }
-	    
+
     return(xmlXPathWrapNodeSet(val));
-    
+
 }
 
 /**
@@ -1956,16 +1956,16 @@
  */
 static xmlXPathObjectPtr
 xmlXPathCacheWrapString(xmlXPathContextPtr ctxt, xmlChar *val)
-{    
+{
     if ((ctxt != NULL) && (ctxt->cache != NULL)) {
 	xmlXPathContextCachePtr cache = (xmlXPathContextCachePtr) ctxt->cache;
 
 	if ((cache->stringObjs != NULL) &&
 	    (cache->stringObjs->number != 0))
 	{
-	
+
 	    xmlXPathObjectPtr ret;
-	    
+
 	    ret = (xmlXPathObjectPtr)
 		cache->stringObjs->items[--cache->stringObjs->number];
 	    ret->type = XPATH_STRING;
@@ -2014,20 +2014,20 @@
 
 	if ((cache->nodesetObjs != NULL) &&
 	    (cache->nodesetObjs->number != 0))
-	{	
+	{
 	    xmlXPathObjectPtr ret;
 	    /*
 	    * Use the nodset-cache.
-	    */	    
+	    */
 	    ret = (xmlXPathObjectPtr)
 		cache->nodesetObjs->items[--cache->nodesetObjs->number];
 	    ret->type = XPATH_NODESET;
 	    ret->boolval = 0;
-	    if (val) {		
+	    if (val) {
 		if ((ret->nodesetval->nodeMax == 0) ||
 		    (val->type == XML_NAMESPACE_DECL))
 		{
-		    xmlXPathNodeSetAddUnique(ret->nodesetval, val);		
+		    xmlXPathNodeSetAddUnique(ret->nodesetval, val);
 		} else {
 		    ret->nodesetval->nodeTab[0] = val;
 		    ret->nodesetval->nodeNr = 1;
@@ -2072,15 +2072,15 @@
  */
 static xmlXPathObjectPtr
 xmlXPathCacheNewCString(xmlXPathContextPtr ctxt, const char *val)
-{    
+{
     if ((ctxt != NULL) && (ctxt->cache)) {
 	xmlXPathContextCachePtr cache = (xmlXPathContextCachePtr) ctxt->cache;
 
 	if ((cache->stringObjs != NULL) &&
 	    (cache->stringObjs->number != 0))
-	{	
+	{
 	    xmlXPathObjectPtr ret;
-	    
+
 	    ret = (xmlXPathObjectPtr)
 		cache->stringObjs->items[--cache->stringObjs->number];
 
@@ -2121,15 +2121,15 @@
  */
 static xmlXPathObjectPtr
 xmlXPathCacheNewString(xmlXPathContextPtr ctxt, const xmlChar *val)
-{    
+{
     if ((ctxt != NULL) && (ctxt->cache)) {
 	xmlXPathContextCachePtr cache = (xmlXPathContextCachePtr) ctxt->cache;
 
 	if ((cache->stringObjs != NULL) &&
 	    (cache->stringObjs->number != 0))
-	{	
+	{
 	    xmlXPathObjectPtr ret;
-	    
+
 	    ret = (xmlXPathObjectPtr)
 		cache->stringObjs->items[--cache->stringObjs->number];
 	    ret->type = XPATH_STRING;
@@ -2175,15 +2175,15 @@
  */
 static xmlXPathObjectPtr
 xmlXPathCacheNewBoolean(xmlXPathContextPtr ctxt, int val)
-{    
+{
     if ((ctxt != NULL) && (ctxt->cache)) {
 	xmlXPathContextCachePtr cache = (xmlXPathContextCachePtr) ctxt->cache;
 
 	if ((cache->booleanObjs != NULL) &&
 	    (cache->booleanObjs->number != 0))
-	{	
+	{
 	    xmlXPathObjectPtr ret;
-	    
+
 	    ret = (xmlXPathObjectPtr)
 		cache->booleanObjs->items[--cache->booleanObjs->number];
 	    ret->type = XPATH_BOOLEAN;
@@ -2229,9 +2229,9 @@
 
 	if ((cache->numberObjs != NULL) &&
 	    (cache->numberObjs->number != 0))
-	{	
+	{
 	    xmlXPathObjectPtr ret;
-	    
+
 	    ret = (xmlXPathObjectPtr)
 		cache->numberObjs->items[--cache->numberObjs->number];
 	    ret->type = XPATH_NUMBER;
@@ -2273,7 +2273,7 @@
 
 static xmlXPathObjectPtr
 xmlXPathCacheConvertString(xmlXPathContextPtr ctxt, xmlXPathObjectPtr val) {
-    xmlChar *res = NULL;    
+    xmlChar *res = NULL;
 
     if (val == NULL)
 	return(xmlXPathCacheNewCString(ctxt, ""));
@@ -2357,7 +2357,7 @@
 static xmlXPathObjectPtr
 xmlXPathCacheConvertBoolean(xmlXPathContextPtr ctxt, xmlXPathObjectPtr val) {
     xmlXPathObjectPtr ret;
-    
+
     if (val == NULL)
 	return(xmlXPathCacheNewBoolean(ctxt, 0));
     if (val->type == XPATH_BOOLEAN)
@@ -2381,7 +2381,7 @@
 static xmlXPathObjectPtr
 xmlXPathCacheConvertNumber(xmlXPathContextPtr ctxt, xmlXPathObjectPtr val) {
     xmlXPathObjectPtr ret;
-    
+
     if (val == NULL)
 	return(xmlXPathCacheNewFloat(ctxt, 0.0));
     if (val->type == XPATH_NUMBER)
@@ -2393,7 +2393,7 @@
 
 /************************************************************************
  *									*
- * 		Parser stacks related functions and macros		*
+ *		Parser stacks related functions and macros		*
  *									*
  ************************************************************************/
 
@@ -2632,7 +2632,7 @@
 
 #define NEXTL(l)  ctxt->cur += l
 
-#define SKIP_BLANKS 							\
+#define SKIP_BLANKS							\
     while (IS_BLANK_CH(*(ctxt->cur))) NEXT
 
 #define CURRENT (*ctxt->cur)
@@ -3001,17 +3001,17 @@
 
     if (node1 == node2)
 	return(0);
-   
+
     /*
      * a couple of optimizations which will avoid computations in most cases
-     */    
+     */
     switch (node1->type) {
 	case XML_ELEMENT_NODE:
 	    if (node2->type == XML_ELEMENT_NODE) {
 		if ((0 > (long) node1->content) && /* TODO: Would a != 0 suffice here? */
 		    (0 > (long) node2->content) &&
 		    (node1->doc == node2->doc))
-		{		
+		{
 		    l1 = -((long) node1->content);
 		    l2 = -((long) node2->content);
 		    if (l1 < l2)
@@ -3019,7 +3019,7 @@
 		    if (l1 > l2)
 			return(-1);
 		} else
-		    goto turtle_comparison;		    
+		    goto turtle_comparison;
 	    }
 	    break;
 	case XML_ATTRIBUTE_NODE:
@@ -3035,7 +3035,7 @@
 	    miscNode1 = node1;
 	    /*
 	    * Find nearest element node.
-	    */	    
+	    */
 	    if (node1->prev != NULL) {
 		do {
 		    node1 = node1->prev;
@@ -3075,9 +3075,9 @@
 	    return(1);
 	default:
 	    break;
-    }    
+    }
     switch (node2->type) {
-	case XML_ELEMENT_NODE:	    
+	case XML_ELEMENT_NODE:
 	    break;
 	case XML_ATTRIBUTE_NODE:
 	    precedence2 = 1; /* element is owner */
@@ -3106,7 +3106,7 @@
 	    } else {
 		precedence2 = 2; /* element is parent */
 		node2 = node2->parent;
-	    }	    
+	    }
 	    if ((node2 == NULL) || (node2->type != XML_ELEMENT_NODE) ||
 		(0 <= (long) node1->content))
 	    {
@@ -3144,11 +3144,11 @@
 		*   Is this 100% correct?
 		*/
 		if (precedence1 < precedence2)
-		    return(1); 
+		    return(1);
 		else
-		    return(-1);	    
+		    return(-1);
 	    }
-	}    
+	}
 	/*
 	* Special case: One of the helper-elements is contained by the other.
 	* <foo>
@@ -3157,7 +3157,7 @@
 	*   </node2>
 	*   Text-6(precedence2 == 3)
 	* </foo>
-	*/	
+	*/
 	if ((precedence2 == 3) && (precedence1 > 1)) {
 	    cur = node1->parent;
 	    while (cur) {
@@ -3166,7 +3166,7 @@
 		cur = cur->parent;
 	    }
 	}
-	if ((precedence1 == 3) && (precedence2 > 1)) {	
+	if ((precedence1 == 3) && (precedence2 > 1)) {
 	    cur = node2->parent;
 	    while (cur) {
 		if (cur == node1)
@@ -3174,16 +3174,16 @@
 		cur = cur->parent;
 	    }
 	}
-    }        
+    }
 
     /*
      * Speedup using document order if availble.
      */
-    if ((node1->type == XML_ELEMENT_NODE) &&	
+    if ((node1->type == XML_ELEMENT_NODE) &&
 	(node2->type == XML_ELEMENT_NODE) &&
 	(0 > (long) node1->content) &&
 	(0 > (long) node2->content) &&
-	(node1->doc == node2->doc)) {	
+	(node1->doc == node2->doc)) {
 
 	l1 = -((long) node1->content);
 	l2 = -((long) node2->content);
@@ -3251,7 +3251,7 @@
 	(node2->type == XML_ELEMENT_NODE) &&
 	(0 > (long) node1->content) &&
 	(0 > (long) node2->content) &&
-	(node1->doc == node2->doc)) {	
+	(node1->doc == node2->doc)) {
 
 	l1 = -((long) node1->content);
 	l2 = -((long) node2->content);
@@ -3339,9 +3339,9 @@
     memset(cur, 0, sizeof(xmlNs));
     cur->type = XML_NAMESPACE_DECL;
     if (ns->href != NULL)
-	cur->href = xmlStrdup(ns->href); 
+	cur->href = xmlStrdup(ns->href);
     if (ns->prefix != NULL)
-	cur->prefix = xmlStrdup(ns->prefix); 
+	cur->prefix = xmlStrdup(ns->prefix);
     cur->next = (xmlNsPtr) node;
     return((xmlNodePtr) cur);
 }
@@ -3435,7 +3435,7 @@
 	return(NULL);
     }
     memset(ret->nodeTab, 0 , size * (size_t) sizeof(xmlNodePtr));
-    ret->nodeMax = size;  
+    ret->nodeMax = size;
     return(ret);
 }
 
@@ -3488,7 +3488,7 @@
 xmlXPathNodeSetAddNs(xmlNodeSetPtr cur, xmlNodePtr node, xmlNsPtr ns) {
     int i;
 
-    
+
     if ((cur == NULL) || (ns == NULL) || (node == NULL) ||
         (ns->type != XML_NAMESPACE_DECL) ||
 	(node->type != XML_ELEMENT_NODE))
@@ -3587,7 +3587,7 @@
     if (val->type == XML_NAMESPACE_DECL) {
 	xmlNsPtr ns = (xmlNsPtr) val;
 
-	cur->nodeTab[cur->nodeNr++] = 
+	cur->nodeTab[cur->nodeNr++] =
 	    xmlXPathNodeSetDupNs((xmlNodePtr) ns->next, ns);
     } else
 	cur->nodeTab[cur->nodeNr++] = val;
@@ -3639,7 +3639,7 @@
     if (val->type == XML_NAMESPACE_DECL) {
 	xmlNsPtr ns = (xmlNsPtr) val;
 
-	cur->nodeTab[cur->nodeNr++] = 
+	cur->nodeTab[cur->nodeNr++] =
 	    xmlXPathNodeSetDupNs((xmlNodePtr) ns->next, ns);
     } else
 	cur->nodeTab[cur->nodeNr++] = val;
@@ -3663,6 +3663,8 @@
     if (val2 == NULL) return(val1);
     if (val1 == NULL) {
 	val1 = xmlXPathNodeSetCreate(NULL);
+    if (val1 == NULL)
+        return (NULL);
 #if 0
 	/*
 	* TODO: The optimization won't work in every case, since
@@ -3672,7 +3674,7 @@
 	*  If there was a flag on the nodesetval, indicating that
 	*  some temporary nodes are in, that would be helpfull.
 	*/
-	/*	
+	/*
 	* Optimization: Create an equally sized node-set
 	* and memcpy the content.
 	*/
@@ -3696,7 +3698,7 @@
     initNr = val1->nodeNr;
 
     for (i = 0;i < val2->nodeNr;i++) {
-	n2 = val2->nodeTab[i]; 
+	n2 = val2->nodeTab[i];
 	/*
 	 * check against duplicates
 	 */
@@ -3707,7 +3709,7 @@
 		skip = 1;
 		break;
 	    } else if ((n1->type == XML_NAMESPACE_DECL) &&
-		       (n2->type == XML_NAMESPACE_DECL)) {		
+		       (n2->type == XML_NAMESPACE_DECL)) {
 		if ((((xmlNsPtr) n1)->next == ((xmlNsPtr) n2)->next) &&
 		    (xmlStrEqual(((xmlNsPtr) n1)->prefix,
 			((xmlNsPtr) n2)->prefix)))
@@ -3776,6 +3778,8 @@
     if (val1 == NULL) {
 	val1 = xmlXPathNodeSetCreate(NULL);
     }
+    if (val1 == NULL)
+        return (NULL);
 
     /* @@ with_ns to check whether namespace nodes should be looked at @@ */
 
@@ -3852,9 +3856,11 @@
 	xmlNodePtr n1, n2;
 
 	if (set1 == NULL)
-	    	set1 = xmlXPathNodeSetCreate(NULL);
+            set1 = xmlXPathNodeSetCreate(NULL);
+        if (set1 == NULL)
+            return (NULL);
 
-	initNbSet1 = set1->nodeNr;        
+	initNbSet1 = set1->nodeNr;
 	for (i = 0;i < set2->nodeNr;i++) {
 	    n2 = set2->nodeTab[i];
 	    /*
@@ -3867,11 +3873,11 @@
 	    */
 	    for (j = 0; j < initNbSet1; j++) {
 		n1 = set1->nodeTab[j];
-		if (n1 == n2) {		    
+		if (n1 == n2) {
 		    goto skip_node;
 		} else if ((n1->type == XML_NAMESPACE_DECL) &&
 		    (n2->type == XML_NAMESPACE_DECL))
-		{		
+		{
 		    if ((((xmlNsPtr) n1)->next == ((xmlNsPtr) n2)->next) &&
 			(xmlStrEqual(((xmlNsPtr) n1)->prefix,
 			((xmlNsPtr) n2)->prefix)))
@@ -3900,7 +3906,7 @@
 		set1->nodeMax = XML_NODESET_DEFAULT;
 	    } else if (set1->nodeNr >= set1->nodeMax) {
 		xmlNodePtr *temp;
-		
+
 		set1->nodeMax *= 2;
 		temp = (xmlNodePtr *) xmlRealloc(
 		    set1->nodeTab, set1->nodeMax * sizeof(xmlNodePtr));
@@ -3912,7 +3918,7 @@
 	    }
 	    if (n2->type == XML_NAMESPACE_DECL) {
 		xmlNsPtr ns = (xmlNsPtr) n2;
-		
+
 		set1->nodeTab[set1->nodeNr++] =
 		    xmlXPathNodeSetDupNs((xmlNodePtr) ns->next, ns);
 	    } else
@@ -3940,7 +3946,7 @@
 static xmlNodeSetPtr
 xmlXPathNodeSetMergeAndClearNoDupls(xmlNodeSetPtr set1, xmlNodeSetPtr set2,
 				    int hasNullEntries)
-{    
+{
     if (set2 == NULL)
 	return(set1);
     if ((set1 == NULL) && (hasNullEntries == 0)) {
@@ -3962,14 +3968,16 @@
 
 	if (set1 == NULL)
 	    set1 = xmlXPathNodeSetCreate(NULL);
-   
+        if (set1 == NULL)
+            return (NULL);
+
 	for (i = 0;i < set2->nodeNr;i++) {
 	    n2 = set2->nodeTab[i];
 	    /*
 	    * Skip NULLed entries.
 	    */
 	    if (n2 == NULL)
-		continue;	
+		continue;
 	    if (set1->nodeMax == 0) {
 		set1->nodeTab = (xmlNodePtr *) xmlMalloc(
 		    XML_NODESET_DEFAULT * sizeof(xmlNodePtr));
@@ -3982,7 +3990,7 @@
 		set1->nodeMax = XML_NODESET_DEFAULT;
 	    } else if (set1->nodeNr >= set1->nodeMax) {
 		xmlNodePtr *temp;
-		
+
 		set1->nodeMax *= 2;
 		temp = (xmlNodePtr *) xmlRealloc(
 		    set1->nodeTab, set1->nodeMax * sizeof(xmlNodePtr));
@@ -4021,7 +4029,7 @@
 
     if (i >= cur->nodeNr) {	/* not found */
 #ifdef DEBUG
-        xmlGenericError(xmlGenericErrorContext, 
+        xmlGenericError(xmlGenericErrorContext,
 	        "xmlXPathNodeSetDel: Node %s wasn't found in NodeList\n",
 		val->name);
 #endif
@@ -4081,7 +4089,7 @@
 /**
  * xmlXPathNodeSetClear:
  * @set:  the node set to clear
- * 
+ *
  * Clears the list from all temporary XPath objects (e.g. namespace nodes
  * are feed), but does *not* free the list itself. Sets the length of the
  * list to 0.
@@ -4094,13 +4102,13 @@
     else if (hasNsNodes) {
 	int i;
 	xmlNodePtr node;
-	
+
 	for (i = 0; i < set->nodeNr; i++) {
 	    node = set->nodeTab[i];
 	    if ((node != NULL) &&
 		(node->type == XML_NAMESPACE_DECL))
 		xmlXPathNodeSetFreeNs((xmlNsPtr) node);
-	}	
+	}
     }
     set->nodeNr = 0;
 }
@@ -4109,7 +4117,7 @@
  * xmlXPathNodeSetClearFromPos:
  * @set: the node set to be cleared
  * @pos: the start position to clear from
- * 
+ *
  * Clears the list from temporary XPath objects (e.g. namespace nodes
  * are feed) starting with the entry at @pos, but does *not* free the list
  * itself. Sets the length of the list to @pos.
@@ -4122,13 +4130,13 @@
     else if ((hasNsNodes)) {
 	int i;
 	xmlNodePtr node;
-	
+
 	for (i = pos; i < set->nodeNr; i++) {
 	    node = set->nodeTab[i];
 	    if ((node != NULL) &&
 		(node->type == XML_NAMESPACE_DECL))
 		xmlXPathNodeSetFreeNs((xmlNsPtr) node);
-	}	
+	}
     }
     set->nodeNr = pos;
 }
@@ -4281,8 +4289,9 @@
         ret = xmlXPathNewNodeSet(NULL);
     else {
         ret = xmlXPathNewNodeSet(val->nodeTab[0]);
-        for (i = 1; i < val->nodeNr; ++i)
-            xmlXPathNodeSetAddUnique(ret->nodesetval, val->nodeTab[i]);
+        if (ret)
+            for (i = 1; i < val->nodeNr; ++i)
+                xmlXPathNodeSetAddUnique(ret->nodesetval, val->nodeTab[i]);
     }
 
     return (ret);
@@ -4381,6 +4390,8 @@
     int i, l1;
     xmlNodePtr cur;
 
+    if (ret == NULL)
+        return(ret);
     if (xmlXPathNodeSetIsEmpty(nodes1))
 	return(ret);
     if (xmlXPathNodeSetIsEmpty(nodes2))
@@ -4402,7 +4413,7 @@
  *
  * Implements the EXSLT - Sets distinct() function:
  *    node-set set:distinct (node-set)
- * 
+ *
  * Returns a subset of the nodes contained in @nodes, or @nodes if
  *         it is empty
  */
@@ -4418,6 +4429,8 @@
 	return(nodes);
 
     ret = xmlXPathNodeSetCreate(NULL);
+    if (ret == NULL)
+        return(ret);
     l = xmlXPathNodeSetGetLength(nodes);
     hash = xmlHashCreate (l);
     for (i = 0; i < l; i++) {
@@ -4506,6 +4519,8 @@
 	return(nodes);
 
     ret = xmlXPathNodeSetCreate(NULL);
+    if (ret == NULL)
+        return(ret);
     if (xmlXPathNodeSetIsEmpty(nodes) ||
 	(!xmlXPathNodeSetContains(nodes, node)))
 	return(ret);
@@ -4608,6 +4623,8 @@
 	return(nodes);
 
     ret = xmlXPathNodeSetCreate(NULL);
+    if (ret == NULL)
+        return(ret);
     if (xmlXPathNodeSetIsEmpty(nodes) ||
 	(!xmlXPathNodeSetContains(nodes, node)))
 	return(ret);
@@ -4705,7 +4722,7 @@
  *
  * Returns 0 in case of success, -1 in case of error
  */
-int		  
+int
 xmlXPathRegisterFunc(xmlXPathContextPtr ctxt, const xmlChar *name,
 		     xmlXPathFunction f) {
     return(xmlXPathRegisterFuncNS(ctxt, name, NULL, f));
@@ -4799,7 +4816,7 @@
 xmlXPathFunctionLookupNS(xmlXPathContextPtr ctxt, const xmlChar *name,
 			 const xmlChar *ns_uri) {
     xmlXPathFunction ret;
-    
+
     if (ctxt == NULL)
 	return(NULL);
     if (name == NULL)
@@ -4853,7 +4870,7 @@
  *
  * Returns 0 in case of success, -1 in case of error
  */
-int		  
+int
 xmlXPathRegisterVariable(xmlXPathContextPtr ctxt, const xmlChar *name,
 			 xmlXPathObjectPtr value) {
     return(xmlXPathRegisterVariableNS(ctxt, name, NULL, value));
@@ -4885,7 +4902,7 @@
     if (ctxt->varHash == NULL)
 	return(-1);
     if (value == NULL)
-        return(xmlHashRemoveEntry2(ctxt->varHash, name, ns_uri, 
+        return(xmlHashRemoveEntry2(ctxt->varHash, name, ns_uri,
 	                           (xmlHashDeallocator)xmlXPathFreeObject));
     return(xmlHashUpdateEntry2(ctxt->varHash, name, ns_uri,
 			       (void *) value,
@@ -4941,7 +4958,7 @@
  * @ns_uri:  the variable namespace URI
  *
  * Search in the Variable array of the context for the given
- * variable value. 
+ * variable value.
  *
  * Returns the a copy of the value or NULL if not found
  */
@@ -5324,7 +5341,7 @@
 #endif
         case XPATH_USERS:
 	    ret->user = val->user;
-	    break; 
+	    break;
         case XPATH_UNDEFINED:
 	    xmlGenericError(xmlGenericErrorContext,
 		    "xmlXPathObjectCopy: unsupported type %d\n",
@@ -5353,7 +5370,7 @@
 #endif
 	    obj->type = XPATH_XSLT_TREE; /* TODO: Just for debugging. */
 	    if (obj->nodesetval != NULL)
-		xmlXPathFreeValueTree(obj->nodesetval);	
+		xmlXPathFreeValueTree(obj->nodesetval);
 	} else {
 	    if (obj->nodesetval != NULL)
 		xmlXPathFreeNodeSet(obj->nodesetval);
@@ -5370,7 +5387,7 @@
 #ifdef XP_DEBUG_OBJ_USAGE
     xmlXPathDebugObjUsageReleased(NULL, obj->type);
 #endif
-    xmlFree(obj);        
+    xmlFree(obj);
 }
 
 /**
@@ -5393,7 +5410,7 @@
 	return;
     if ((ctxt == NULL) || (ctxt->cache == NULL)) {
 	 xmlXPathFreeObject(obj);
-    } else {       
+    } else {
 	xmlXPathContextCachePtr cache =
 	    (xmlXPathContextCachePtr) ctxt->cache;
 
@@ -5402,7 +5419,7 @@
 	    case XPATH_XSLT_TREE:
 		if (obj->nodesetval != NULL) {
 		    if (obj->boolval) {
-		    	/*
+			/*
 			* It looks like the @boolval is used for
 			* evaluation if this an XSLT Result Tree Fragment.
 			* TODO: Check if this assumption is correct.
@@ -5449,7 +5466,7 @@
 		    xmlXPtrFreeLocationSet(obj->user);
 		}
 		goto free_obj;
-#endif	    
+#endif
 	    default:
 		goto free_obj;
 	}
@@ -5470,7 +5487,7 @@
 
 	if (obj->nodesetval != NULL) {
 	    xmlNodeSetPtr tmpset = obj->nodesetval;
-	    
+
 	    /*
 	    * TODO: Due to those nasty ns-nodes, we need to traverse
 	    *  the list and free the ns-nodes.
@@ -5493,7 +5510,7 @@
 		if ((tmpset->nodeTab[0] != NULL) &&
 		    (tmpset->nodeTab[0]->type == XML_NAMESPACE_DECL))
 		    xmlXPathNodeSetFreeNs((xmlNsPtr) tmpset->nodeTab[0]);
-	    }		
+	    }
 	    tmpset->nodeNr = 0;
 	    memset(obj, 0, sizeof(xmlXPathObject));
 	    obj->nodesetval = tmpset;
@@ -5505,7 +5522,7 @@
 free_obj:
 	/*
 	* Cache is full; free the object.
-	*/    
+	*/
 	if (obj->nodesetval != NULL)
 	    xmlXPathFreeNodeSet(obj->nodesetval);
 #ifdef XP_DEBUG_OBJ_USAGE
@@ -5616,7 +5633,7 @@
  * Converts an existing object to its string() equivalent
  *
  * Returns the allocated string value of the object, NULL in case of error.
- *         It's up to the caller to free the string memory with xmlFree(). 
+ *         It's up to the caller to free the string memory with xmlFree().
  */
 xmlChar *
 xmlXPathCastToString(xmlXPathObjectPtr val) {
@@ -6007,7 +6024,7 @@
     }
 #endif
 
-    xmlXPathRegisterAllFunctions(ret);   
+    xmlXPathRegisterAllFunctions(ret);
 
     return(ret);
 }
@@ -6038,7 +6055,7 @@
  ************************************************************************/
 
 #define CHECK_CTXT(ctxt)						\
-    if (ctxt == NULL) { 						\
+    if (ctxt == NULL) {						\
 	__xmlRaiseError(NULL, NULL, NULL,				\
 		NULL, NULL, XML_FROM_XPATH,				\
 		XML_ERR_INTERNAL_ERROR, XML_ERR_FATAL,			\
@@ -6049,7 +6066,7 @@
     }									\
 
 #define CHECK_CTXT_NEG(ctxt)						\
-    if (ctxt == NULL) { 						\
+    if (ctxt == NULL) {						\
 	__xmlRaiseError(NULL, NULL, NULL,				\
 		NULL, NULL, XML_FROM_XPATH,				\
 		XML_ERR_INTERNAL_ERROR, XML_ERR_FATAL,			\
@@ -6062,7 +6079,7 @@
 
 #define CHECK_CONTEXT(ctxt)						\
     if ((ctxt == NULL) || (ctxt->doc == NULL) ||			\
-        (ctxt->doc->children == NULL)) { 				\
+        (ctxt->doc->children == NULL)) {				\
 	xmlXPatherror(ctxt, __FILE__, __LINE__, XPATH_INVALID_CTXT);	\
 	return(NULL);							\
     }
@@ -6125,7 +6142,7 @@
     memset(ret, 0 , (size_t) sizeof(xmlXPathParserContext));
 
     /* Allocate the value stack */
-    ret->valueTab = (xmlXPathObjectPtr *) 
+    ret->valueTab = (xmlXPathObjectPtr *)
                      xmlMalloc(10 * sizeof(xmlXPathObjectPtr));
     if (ret->valueTab == NULL) {
 	xmlFree(ret);
@@ -6272,7 +6289,7 @@
 	    tmp = tmp->next;
 	    continue;
 	}
-	
+
 	do {
 	    tmp = tmp->parent;
 	    if (tmp == NULL)
@@ -6431,7 +6448,7 @@
  * If both objects to be compared are node-sets, then the comparison
  * will be true if and only if there is a node in the first node-set
  * and a node in the second node-set such that the result of performing
- * the comparison on the string-values of the two nodes is true. 
+ * the comparison on the string-values of the two nodes is true.
  * ....
  * When neither object to be compared is a node-set and the operator
  * is <=, <, >= or >, then the objects are compared by converting both
@@ -6445,7 +6462,7 @@
  *    represented by the string; any other string is converted to NaN
  *
  * Conclusion all nodes need to be converted first to their string value
- * and then the comparison must be done when possible 
+ * and then the comparison must be done when possible
  */
 static int
 xmlXPathCompareNodeSets(int inf, int strict,
@@ -6500,7 +6517,7 @@
 	    }
 	    if (xmlXPathIsNaN(values2[j]))
 		continue;
-	    if (inf && strict) 
+	    if (inf && strict)
 		ret = (val1 < values2[j]);
 	    else if (inf && !strict)
 		ret = (val1 <= values2[j]);
@@ -6840,7 +6857,7 @@
 		case XPATH_STRING:
 		    if ((arg2->stringval == NULL) ||
 			(arg2->stringval[0] == 0)) ret = 0;
-		    else 
+		    else
 			ret = 1;
 		    ret = (arg1->boolval == ret);
 		    break;
@@ -6875,7 +6892,7 @@
 		case XPATH_NUMBER:
 		    /* Hand check NaN and Infinity equalities */
 		    if (xmlXPathIsNaN(arg1->floatval) ||
-		    	    xmlXPathIsNaN(arg2->floatval)) {
+			    xmlXPathIsNaN(arg2->floatval)) {
 		        ret = 0;
 		    } else if (xmlXPathIsInf(arg1->floatval) == 1) {
 		        if (xmlXPathIsInf(arg2->floatval) == 1)
@@ -6923,7 +6940,7 @@
 		case XPATH_BOOLEAN:
 		    if ((arg1->stringval == NULL) ||
 			(arg1->stringval[0] == 0)) ret = 0;
-		    else 
+		    else
 			ret = 1;
 		    ret = (arg2->boolval == ret);
 		    break;
@@ -6936,7 +6953,7 @@
 		    arg1 = valuePop(ctxt);
 		    /* Hand check NaN and Infinity equalities */
 		    if (xmlXPathIsNaN(arg1->floatval) ||
-		    	    xmlXPathIsNaN(arg2->floatval)) {
+			    xmlXPathIsNaN(arg2->floatval)) {
 		        ret = 0;
 		    } else if (xmlXPathIsInf(arg1->floatval) == 1) {
 			if (xmlXPathIsInf(arg2->floatval) == 1)
@@ -7002,7 +7019,7 @@
     int ret = 0;
 
     if ((ctxt == NULL) || (ctxt->context == NULL)) return(0);
-    arg2 = valuePop(ctxt); 
+    arg2 = valuePop(ctxt);
     arg1 = valuePop(ctxt);
     if ((arg1 == NULL) || (arg2 == NULL)) {
 	if (arg1 != NULL)
@@ -7048,7 +7065,7 @@
 	    case XPATH_BOOLEAN:
 		if ((arg1->nodesetval == NULL) ||
 		  (arg1->nodesetval->nodeNr == 0)) ret = 0;
-		else 
+		else
 		    ret = 1;
 		ret = (ret == arg2->boolval);
 		break;
@@ -7087,7 +7104,7 @@
     int ret = 0;
 
     if ((ctxt == NULL) || (ctxt->context == NULL)) return(0);
-    arg2 = valuePop(ctxt); 
+    arg2 = valuePop(ctxt);
     arg1 = valuePop(ctxt);
     if ((arg1 == NULL) || (arg2 == NULL)) {
 	if (arg1 != NULL)
@@ -7133,7 +7150,7 @@
 	    case XPATH_BOOLEAN:
 		if ((arg1->nodesetval == NULL) ||
 		  (arg1->nodesetval->nodeNr == 0)) ret = 0;
-		else 
+		else
 		    ret = 1;
 		ret = (ret != arg2->boolval);
 		break;
@@ -7164,7 +7181,7 @@
  * @inf:  less than (1) or greater than (0)
  * @strict:  is the comparison strict
  *
- * Implement the compare operation on XPath objects: 
+ * Implement the compare operation on XPath objects:
  *     @arg1 < @arg2    (1, 1, ...
  *     @arg1 <= @arg2   (1, 0, ...
  *     @arg1 > @arg2    (0, 1, ...
@@ -7188,7 +7205,7 @@
     xmlXPathObjectPtr arg1, arg2;
 
     if ((ctxt == NULL) || (ctxt->context == NULL)) return(0);
-    arg2 = valuePop(ctxt); 
+    arg2 = valuePop(ctxt);
     arg1 = valuePop(ctxt);
     if ((arg1 == NULL) || (arg2 == NULL)) {
 	if (arg1 != NULL)
@@ -7429,7 +7446,7 @@
 	    ctxt->value->floatval = xmlXPathPINF;
 	else if (ctxt->value->floatval < 0)
 	    ctxt->value->floatval = xmlXPathNINF;
-    } else 
+    } else
 	ctxt->value->floatval /= val;
 }
 
@@ -7664,10 +7681,10 @@
 #ifdef LIBXML_DOCB_ENABLED
 	    case XML_DOCB_DOCUMENT_NODE:
 #endif
-	    case XML_HTML_DOCUMENT_NODE:	    	
+	    case XML_HTML_DOCUMENT_NODE:	    
 		return(contextNode);
 	    default:
-		return(NULL);	    
+		return(NULL);
 	}
 	return(NULL);
     } else {
@@ -7678,7 +7695,7 @@
 		case XML_ELEMENT_NODE:
 		/* TODO: OK to have XInclude here? */
 		case XML_XINCLUDE_START:
-		case XML_DOCUMENT_FRAG_NODE:		
+		case XML_DOCUMENT_FRAG_NODE:
 		    if (cur != start)
 			return(cur);
 		    if (cur->children != NULL) {
@@ -7697,13 +7714,13 @@
 		    return(xmlDocGetRootElement((xmlDocPtr) cur));
 		default:
 		    break;
-	    }	    
-	    
+	    }
+
 next_sibling:
 	    if ((cur == NULL) || (cur == contextNode))
-		return(NULL);	
+		return(NULL);
 	    if (cur->next != NULL) {
-		cur = cur->next;		
+		cur = cur->next;
 	    } else {
 		cur = cur->parent;
 		goto next_sibling;
@@ -7711,7 +7728,7 @@
 	}
     }
     return(NULL);
-}            
+}
 
 /**
  * xmlXPathNextDescendant:
@@ -7743,7 +7760,7 @@
 	/*
 	 * Do not descend on entities declarations
 	 */
-    	if (cur->children->type != XML_ENTITY_DECL) {
+	if (cur->children->type != XML_ENTITY_DECL) {
 	    cur = cur->children;
 	    /*
 	     * Skip DTDs
@@ -7761,7 +7778,7 @@
 	    (cur->type != XML_DTD_NODE))
 	    return(cur);
     }
-    
+
     do {
         cur = cur->parent;
 	if (cur == NULL) break;
@@ -7860,7 +7877,7 @@
                 return(NULL);
 	    case XML_NAMESPACE_DECL: {
 		xmlNsPtr ns = (xmlNsPtr) ctxt->context->node;
-		
+
 		if ((ns->next != NULL) &&
 		    (ns->next->type != XML_NAMESPACE_DECL))
 		    return((xmlNodePtr) ns->next);
@@ -7933,7 +7950,7 @@
                 return(NULL);
 	    case XML_NAMESPACE_DECL: {
 		xmlNsPtr ns = (xmlNsPtr) ctxt->context->node;
-		
+
 		if ((ns->next != NULL) &&
 		    (ns->next->type != XML_NAMESPACE_DECL))
 		    return((xmlNodePtr) ns->next);
@@ -7977,7 +7994,7 @@
 	}
 	case XML_NAMESPACE_DECL: {
 	    xmlNsPtr ns = (xmlNsPtr) ctxt->context->node;
-		
+
 	    if ((ns->next != NULL) &&
 	        (ns->next->type != XML_NAMESPACE_DECL))
 	        return((xmlNodePtr) ns->next);
@@ -8174,7 +8191,7 @@
  * node that are before the context node in document order, excluding any
  * ancestors and excluding attribute nodes and namespace nodes; the nodes are
  * ordered in reverse document order
- * This is a faster implementation but internal only since it requires a 
+ * This is a faster implementation but internal only since it requires a
  * state kept in the parser context: ctxt->ancestor.
  *
  * Returns the next element following that axis
@@ -8231,7 +8248,7 @@
     if (ctxt->context->tmpNsList == NULL && cur != (xmlNodePtr) xmlXPathXMLNamespace) {
         if (ctxt->context->tmpNsList != NULL)
 	    xmlFree(ctxt->context->tmpNsList);
-	ctxt->context->tmpNsList = 
+	ctxt->context->tmpNsList =
 	    xmlGetNsList(ctxt->context->doc, ctxt->context->node);
 	ctxt->context->tmpNsNr = 0;
 	if (ctxt->context->tmpNsList != NULL) {
@@ -8379,7 +8396,7 @@
     xmlXPathObjectPtr cur;
 
     CHECK_ARITY(1);
-    if ((ctxt->value == NULL) || 
+    if ((ctxt->value == NULL) ||
 	((ctxt->value->type != XPATH_NODESET) &&
 	 (ctxt->value->type != XPATH_XSLT_TREE)))
 	XP_ERROR(XPATH_INVALID_TYPE);
@@ -8432,6 +8449,8 @@
     if (ids == NULL) return(NULL);
 
     ret = xmlXPathNodeSetCreate(NULL);
+    if (ret == NULL)
+        return(ret);
 
     while (IS_BLANK_CH(*cur)) cur++;
     while (*cur != 0) {
@@ -8499,6 +8518,11 @@
 	int i;
 
 	ret = xmlXPathNodeSetCreate(NULL);
+        /*
+         * FIXME -- in an out-of-memory condition this will behave badly.
+         * The solution is not clear -- we already popped an item from
+         * ctxt, so the object is in a corrupt state.
+         */
 
 	if (obj->nodesetval != NULL) {
 	    for (i = 0; i < obj->nodesetval->nodeNr; i++) {
@@ -8517,7 +8541,7 @@
     }
     obj = xmlXPathCacheConvertString(ctxt->context, obj);
     ret = xmlXPathGetElementsByIds(ctxt->context->doc, obj->stringval);
-    valuePush(ctxt, xmlXPathCacheWrapNodeSet(ctxt->context, ret));    
+    valuePush(ctxt, xmlXPathCacheWrapNodeSet(ctxt->context, ret));
     xmlXPathReleaseObject(ctxt->context, obj);
     return;
 }
@@ -8548,7 +8572,7 @@
     }
 
     CHECK_ARITY(1);
-    if ((ctxt->value == NULL) || 
+    if ((ctxt->value == NULL) ||
 	((ctxt->value->type != XPATH_NODESET) &&
 	 (ctxt->value->type != XPATH_XSLT_TREE)))
 	XP_ERROR(XPATH_INVALID_TYPE);
@@ -8606,7 +8630,7 @@
 	nargs = 1;
     }
     CHECK_ARITY(1);
-    if ((ctxt->value == NULL) || 
+    if ((ctxt->value == NULL) ||
 	((ctxt->value->type != XPATH_NODESET) &&
 	 (ctxt->value->type != XPATH_XSLT_TREE)))
 	XP_ERROR(XPATH_INVALID_TYPE);
@@ -8690,7 +8714,7 @@
 			    cur->nodesetval->nodeTab[i]->name));
 		} else {
 		    xmlChar *fullname;
-		    
+
 		    fullname = xmlBuildQName(cur->nodesetval->nodeTab[i]->name,
 				     cur->nodesetval->nodeTab[i]->ns->prefix,
 				     NULL, 0);
@@ -8725,11 +8749,11 @@
  *      the node in the node-set that is first in document order.
  *      If the node-set is empty, an empty string is returned.
  *    - A number is converted to a string as follows
- *      + NaN is converted to the string NaN 
- *      + positive zero is converted to the string 0 
- *      + negative zero is converted to the string 0 
- *      + positive infinity is converted to the string Infinity 
- *      + negative infinity is converted to the string -Infinity 
+ *      + NaN is converted to the string NaN
+ *      + positive zero is converted to the string 0
+ *      + negative zero is converted to the string 0
+ *      + positive infinity is converted to the string Infinity
+ *      + negative infinity is converted to the string -Infinity
  *      + if the number is an integer, the number is represented in
  *        decimal form as a Number with no decimal point and no leading
  *        zeros, preceded by a minus sign (-) if the number is negative
@@ -8803,7 +8827,7 @@
     CHECK_TYPE(XPATH_STRING);
     cur = valuePop(ctxt);
     valuePush(ctxt, xmlXPathCacheNewFloat(ctxt->context,
-	xmlUTF8Strlen(cur->stringval)));    
+	xmlUTF8Strlen(cur->stringval)));
     xmlXPathReleaseObject(ctxt->context, cur);
 }
 
@@ -8942,12 +8966,12 @@
  * or equal to the second argument and, if the third argument is specified,
  * less than the sum of the second and third arguments; the comparisons
  * and addition used for the above follow the standard IEEE 754 rules. Thus:
- *  - substring("12345", 1.5, 2.6) returns "234" 
- *  - substring("12345", 0, 3) returns "12" 
- *  - substring("12345", 0 div 0, 3) returns "" 
- *  - substring("12345", 1, 0 div 0) returns "" 
- *  - substring("12345", -42, 1 div 0) returns "12345" 
- *  - substring("12345", -1 div 0, 1 div 0) returns "" 
+ *  - substring("12345", 1.5, 2.6) returns "234"
+ *  - substring("12345", 0, 3) returns "12"
+ *  - substring("12345", 0 div 0, 3) returns ""
+ *  - substring("12345", 1, 0 div 0) returns ""
+ *  - substring("12345", -42, 1 div 0) returns "12345"
+ *  - substring("12345", -1 div 0, 1 div 0) returns ""
  */
 void
 xmlXPathSubstringFunction(xmlXPathParserContextPtr ctxt, int nargs) {
@@ -8988,18 +9012,18 @@
     */
     if (nargs != 3) {
 	le = (double)m;
-	if (in < 1.0) 
+	if (in < 1.0)
 	    in = 1.0;
     }
 
-    /* Need to check for the special cases where either 
+    /* Need to check for the special cases where either
      * the index is NaN, the length is NaN, or both
      * arguments are infinity (relying on Inf + -Inf = NaN)
      */
     if (!xmlXPathIsNaN(in + le) && !xmlXPathIsInf(in)) {
         /*
          * To meet the requirements of the spec, the arguments
-	 * must be converted to integer format before 
+	 * must be converted to integer format before
 	 * initial index calculations are done
          *
          * First we go to integer form, rounding up
@@ -9065,13 +9089,13 @@
   xmlBufferPtr target;
   const xmlChar *point;
   int offset;
-  
+
   CHECK_ARITY(2);
   CAST_TO_STRING;
   find = valuePop(ctxt);
   CAST_TO_STRING;
   str = valuePop(ctxt);
-  
+
   target = xmlBufferCreate();
   if (target) {
     point = xmlStrstr(str->stringval, find->stringval);
@@ -9108,13 +9132,13 @@
   xmlBufferPtr target;
   const xmlChar *point;
   int offset;
-  
+
   CHECK_ARITY(2);
   CAST_TO_STRING;
   find = valuePop(ctxt);
   CAST_TO_STRING;
   str = valuePop(ctxt);
-  
+
   target = xmlBufferCreate();
   if (target) {
     point = xmlStrstr(str->stringval, find->stringval);
@@ -9124,7 +9148,7 @@
 		   xmlStrlen(str->stringval) - offset);
     }
     valuePush(ctxt, xmlXPathCacheNewString(ctxt->context,
-	xmlBufferContent(target)));    
+	xmlBufferContent(target)));
     xmlBufferFree(target);
   }
   xmlXPathReleaseObject(ctxt->context, str);
@@ -9151,7 +9175,7 @@
   xmlChar *source = NULL;
   xmlBufferPtr target;
   xmlChar blank;
-  
+
   if (ctxt == NULL) return;
   if (nargs == 0) {
     /* Use current context node */
@@ -9169,11 +9193,11 @@
 
   target = xmlBufferCreate();
   if (target && source) {
-    
+
     /* Skip leading whitespaces */
     while (IS_BLANK_CH(*source))
       source++;
-  
+
     /* Collapse intermediate whitespaces, and skip trailing whitespaces */
     blank = 0;
     while (*source) {
@@ -9448,7 +9472,7 @@
     double res = 0.0;
 
     CHECK_ARITY(1);
-    if ((ctxt->value == NULL) || 
+    if ((ctxt->value == NULL) ||
 	((ctxt->value->type != XPATH_NODESET) &&
 	 (ctxt->value->type != XPATH_XSLT_TREE)))
 	XP_ERROR(XPATH_INVALID_TYPE);
@@ -9567,14 +9591,14 @@
     if (ctxt->value->floatval < 0) {
 	if (ctxt->value->floatval < f - 0.5)
 	    ctxt->value->floatval = f - 1;
-	else 
+	else
 	    ctxt->value->floatval = f;
 	if (ctxt->value->floatval == 0)
 	    ctxt->value->floatval = xmlXPathNZERO;
     } else {
 	if (ctxt->value->floatval < f + 0.5)
 	    ctxt->value->floatval = f;
-	else 
+	else
 	    ctxt->value->floatval = f + 1;
     }
 }
@@ -9625,7 +9649,7 @@
      * UCS-4 range (hex.)           UTF-8 octet sequence (binary)
      * 0000 0000-0000 007F   0xxxxxxx
      * 0000 0080-0000 07FF   110xxxxx 10xxxxxx
-     * 0000 0800-0000 FFFF   1110xxxx 10xxxxxx 10xxxxxx 
+     * 0000 0800-0000 FFFF   1110xxxx 10xxxxxx 10xxxxxx
      *
      * Check for the 0x110000 limit too
      */
@@ -9662,7 +9686,7 @@
 	}
 	if (!IS_CHAR(val)) {
 	    XP_ERROR0(XPATH_INVALID_CHAR_ERROR);
-	}    
+	}
 	return(val);
     } else {
 	/* 1-byte code */
@@ -9734,7 +9758,7 @@
 /**
  * xmlXPathParseQName:
  * @ctxt:  the XPath Parser context
- * @prefix:  a xmlChar ** 
+ * @prefix:  a xmlChar **
  *
  * parse an XML qualified name
  *
@@ -9754,7 +9778,7 @@
 
     *prefix = NULL;
     ret = xmlXPathParseNCName(ctxt);
-    if (CUR == ':') {
+    if (ret && CUR == ':') {
         *prefix = ret;
 	NEXT;
 	ret = xmlXPathParseNCName(ctxt);
@@ -9828,7 +9852,7 @@
     while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
 	   ((IS_LETTER(c)) || (IS_DIGIT(c)) ||
             (c == '.') || (c == '-') ||
-	    (c == '_') || ((qualified) && (c == ':')) || 
+	    (c == '_') || ((qualified) && (c == ':')) ||
 	    (IS_COMBINING(c)) ||
 	    (IS_EXTENDER(c)))) {
 	COPY_BUF(l,buf,len,c);
@@ -9841,7 +9865,7 @@
 	     */
 	    xmlChar *buffer;
 	    int max = len * 2;
-	    
+
 	    buffer = (xmlChar *) xmlMallocAtomic(max * sizeof(xmlChar));
 	    if (buffer == NULL) {
 		XP_ERRORNULL(XPATH_MEMORY_ERROR);
@@ -9849,7 +9873,7 @@
 	    memcpy(buffer, buf, len);
 	    while ((IS_LETTER(c)) || (IS_DIGIT(c)) || /* test bigname.xml */
 		   (c == '.') || (c == '-') ||
-		   (c == '_') || ((qualified) && (c == ':')) || 
+		   (c == '_') || ((qualified) && (c == ':')) ||
 		   (IS_COMBINING(c)) ||
 		   (IS_EXTENDER(c))) {
 		if (len + 10 > max) {
@@ -9896,7 +9920,7 @@
  *  [30a]  Float  ::= Number ('e' Digits?)?
  *
  *  [30]   Number ::=   Digits ('.' Digits?)?
- *                    | '.' Digits 
+ *                    | '.' Digits
  *  [31]   Digits ::=   [0-9]+
  *
  * Compile a Number in the string
@@ -9995,7 +10019,7 @@
  * @ctxt:  the XPath Parser context
  *
  *  [30]   Number ::=   Digits ('.' Digits?)?
- *                    | '.' Digits 
+ *                    | '.' Digits
  *  [31]   Digits ::=   [0-9]+
  *
  * Compile a Number, then push it on the stack
@@ -10175,9 +10199,9 @@
  *
  * Early evaluation is possible since:
  * The variable bindings [...] used to evaluate a subexpression are
- * always the same as those used to evaluate the containing expression. 
+ * always the same as those used to evaluate the containing expression.
  *
- *  [36]   VariableReference ::=   '$' QName 
+ *  [36]   VariableReference ::=   '$' QName
  */
 static void
 xmlXPathCompVariableReference(xmlXPathParserContextPtr ctxt) {
@@ -10236,7 +10260,7 @@
  * @ctxt:  the XPath Parser context
  *
  *  [16]   FunctionCall ::=   FunctionName '(' ( Argument ( ',' Argument)*)? ')'
- *  [17]   Argument ::=   Expr 
+ *  [17]   Argument ::=   Expr
  *
  * Compile a function call, the evaluation of all arguments are
  * pushed on the stack
@@ -10250,6 +10274,7 @@
 
     name = xmlXPathParseQName(ctxt, &prefix);
     if (name == NULL) {
+	xmlFree(prefix);
 	XP_ERROR(XPATH_EXPR_ERROR);
     }
     SKIP_BLANKS;
@@ -10282,7 +10307,11 @@
 	    int op1 = ctxt->comp->last;
 	    ctxt->comp->last = -1;
 	    xmlXPathCompileExpr(ctxt, sort);
-	    CHECK_ERROR;
+	    if (ctxt->error != XPATH_EXPRESSION_OK) {
+		xmlFree(name);
+		xmlFree(prefix);
+		return;
+	    }
 	    PUSH_BINARY_EXPR(XPATH_OP_ARG, op1, ctxt->comp->last, 0, 0);
 	    nbargs++;
 	    if (CUR == ')') break;
@@ -10303,11 +10332,11 @@
  * xmlXPathCompPrimaryExpr:
  * @ctxt:  the XPath Parser context
  *
- *  [15]   PrimaryExpr ::=   VariableReference 
+ *  [15]   PrimaryExpr ::=   VariableReference
  *                | '(' Expr ')'
- *                | Literal 
- *                | Number 
- *                | FunctionCall 
+ *                | Literal
+ *                | Number
+ *                | FunctionCall
  *
  * Compile a primary expression.
  */
@@ -10339,8 +10368,8 @@
  * xmlXPathCompFilterExpr:
  * @ctxt:  the XPath Parser context
  *
- *  [20]   FilterExpr ::=   PrimaryExpr 
- *               | FilterExpr Predicate 
+ *  [20]   FilterExpr ::=   PrimaryExpr
+ *               | FilterExpr Predicate
  *
  * Compile a filter expression.
  * Square brackets are used to filter expressions in the same way that
@@ -10355,13 +10384,13 @@
     xmlXPathCompPrimaryExpr(ctxt);
     CHECK_ERROR;
     SKIP_BLANKS;
-    
+
     while (CUR == '[') {
 	xmlXPathCompPredicate(ctxt, 1);
 	SKIP_BLANKS;
     }
 
-    
+
 }
 
 /**
@@ -10400,7 +10429,7 @@
     while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
 	   ((IS_LETTER(c)) || (IS_DIGIT(c)) ||
             (c == '.') || (c == '-') ||
-	    (c == '_') || (c == ':') || 
+	    (c == '_') || (c == ':') ||
 	    (IS_COMBINING(c)) ||
 	    (IS_EXTENDER(c)))) {
 	len += l;
@@ -10416,10 +10445,10 @@
  * xmlXPathCompPathExpr:
  * @ctxt:  the XPath Parser context
  *
- *  [19]   PathExpr ::=   LocationPath 
- *               | FilterExpr 
- *               | FilterExpr '/' RelativeLocationPath 
- *               | FilterExpr '//' RelativeLocationPath 
+ *  [19]   PathExpr ::=   LocationPath
+ *               | FilterExpr
+ *               | FilterExpr '/' RelativeLocationPath
+ *               | FilterExpr '//' RelativeLocationPath
  *
  * Compile a path expression.
  * The / operator and // operators combine an arbitrary expression
@@ -10436,8 +10465,8 @@
     xmlChar *name = NULL; /* we may have to preparse a name to find out */
 
     SKIP_BLANKS;
-    if ((CUR == '$') || (CUR == '(') || 
-    	(IS_ASCII_DIGIT(CUR)) ||
+    if ((CUR == '$') || (CUR == '(') ||
+	(IS_ASCII_DIGIT(CUR)) ||
         (CUR == '\'') || (CUR == '"') ||
 	(CUR == '.' && IS_ASCII_DIGIT(NXT(1)))) {
 	lc = 0;
@@ -10477,7 +10506,7 @@
 	} else if (name != NULL) {
 	    int len =xmlStrlen(name);
 
-	    
+
 	    while (NXT(len) != 0) {
 		if (NXT(len) == '/') {
 		    /* element name */
@@ -10544,7 +10573,7 @@
 	    /* make sure all cases are covered explicitly */
 	    XP_ERROR(XPATH_EXPR_ERROR);
 	}
-    } 
+    }
 
     if (lc) {
 	if (CUR == '/') {
@@ -10576,8 +10605,8 @@
  * xmlXPathCompUnionExpr:
  * @ctxt:  the XPath Parser context
  *
- *  [18]   UnionExpr ::=   PathExpr 
- *               | UnionExpr '|' PathExpr 
+ *  [18]   UnionExpr ::=   PathExpr
+ *               | UnionExpr '|' PathExpr
  *
  * Compile an union expression.
  */
@@ -10605,8 +10634,8 @@
  * xmlXPathCompUnaryExpr:
  * @ctxt:  the XPath Parser context
  *
- *  [27]   UnaryExpr ::=   UnionExpr 
- *                   | '-' UnaryExpr 
+ *  [27]   UnaryExpr ::=   UnionExpr
+ *                   | '-' UnaryExpr
  *
  * Compile an unary expression.
  */
@@ -10638,10 +10667,10 @@
  * xmlXPathCompMultiplicativeExpr:
  * @ctxt:  the XPath Parser context
  *
- *  [26]   MultiplicativeExpr ::=   UnaryExpr 
- *                   | MultiplicativeExpr MultiplyOperator UnaryExpr 
- *                   | MultiplicativeExpr 'div' UnaryExpr 
- *                   | MultiplicativeExpr 'mod' UnaryExpr 
+ *  [26]   MultiplicativeExpr ::=   UnaryExpr
+ *                   | MultiplicativeExpr MultiplyOperator UnaryExpr
+ *                   | MultiplicativeExpr 'div' UnaryExpr
+ *                   | MultiplicativeExpr 'mod' UnaryExpr
  *  [34]   MultiplyOperator ::=   '*'
  *
  * Compile an Additive expression.
@@ -10652,7 +10681,7 @@
     xmlXPathCompUnaryExpr(ctxt);
     CHECK_ERROR;
     SKIP_BLANKS;
-    while ((CUR == '*') || 
+    while ((CUR == '*') ||
            ((CUR == 'd') && (NXT(1) == 'i') && (NXT(2) == 'v')) ||
            ((CUR == 'm') && (NXT(1) == 'o') && (NXT(2) == 'd'))) {
 	int op = -1;
@@ -10680,9 +10709,9 @@
  * xmlXPathCompAdditiveExpr:
  * @ctxt:  the XPath Parser context
  *
- *  [25]   AdditiveExpr ::=   MultiplicativeExpr 
- *                   | AdditiveExpr '+' MultiplicativeExpr 
- *                   | AdditiveExpr '-' MultiplicativeExpr 
+ *  [25]   AdditiveExpr ::=   MultiplicativeExpr
+ *                   | AdditiveExpr '+' MultiplicativeExpr
+ *                   | AdditiveExpr '-' MultiplicativeExpr
  *
  * Compile an Additive expression.
  */
@@ -10712,11 +10741,11 @@
  * xmlXPathCompRelationalExpr:
  * @ctxt:  the XPath Parser context
  *
- *  [24]   RelationalExpr ::=   AdditiveExpr 
- *                 | RelationalExpr '<' AdditiveExpr 
- *                 | RelationalExpr '>' AdditiveExpr 
- *                 | RelationalExpr '<=' AdditiveExpr 
- *                 | RelationalExpr '>=' AdditiveExpr 
+ *  [24]   RelationalExpr ::=   AdditiveExpr
+ *                 | RelationalExpr '<' AdditiveExpr
+ *                 | RelationalExpr '>' AdditiveExpr
+ *                 | RelationalExpr '<=' AdditiveExpr
+ *                 | RelationalExpr '>=' AdditiveExpr
  *
  *  A <= B > C is allowed ? Answer from James, yes with
  *  (AdditiveExpr <= AdditiveExpr) > AdditiveExpr
@@ -10756,9 +10785,9 @@
  * xmlXPathCompEqualityExpr:
  * @ctxt:  the XPath Parser context
  *
- *  [23]   EqualityExpr ::=   RelationalExpr 
- *                 | EqualityExpr '=' RelationalExpr 
- *                 | EqualityExpr '!=' RelationalExpr 
+ *  [23]   EqualityExpr ::=   RelationalExpr
+ *                 | EqualityExpr '=' RelationalExpr
+ *                 | EqualityExpr '!=' RelationalExpr
  *
  *  A != B != C is allowed ? Answer from James, yes with
  *  (RelationalExpr = RelationalExpr) = RelationalExpr
@@ -10793,8 +10822,8 @@
  * xmlXPathCompAndExpr:
  * @ctxt:  the XPath Parser context
  *
- *  [22]   AndExpr ::=   EqualityExpr 
- *                 | AndExpr 'and' EqualityExpr 
+ *  [22]   AndExpr ::=   EqualityExpr
+ *                 | AndExpr 'and' EqualityExpr
  *
  * Compile an AND expression.
  *
@@ -10819,9 +10848,9 @@
  * xmlXPathCompileExpr:
  * @ctxt:  the XPath Parser context
  *
- *  [14]   Expr ::=   OrExpr 
- *  [21]   OrExpr ::=   AndExpr 
- *                 | OrExpr 'or' AndExpr 
+ *  [14]   Expr ::=   OrExpr
+ *  [21]   OrExpr ::=   AndExpr
+ *                 | OrExpr 'or' AndExpr
  *
  * Parse and compile an expression
  */
@@ -10857,7 +10886,7 @@
  * @filter:  act as a filter
  *
  *  [8]   Predicate ::=   '[' PredicateExpr ']'
- *  [9]   PredicateExpr ::=   Expr 
+ *  [9]   PredicateExpr ::=   Expr
  *
  * Compile a predicate expression
  */
@@ -10974,7 +11003,7 @@
 	}
 
 	*test = NODE_TEST_TYPE;
-	
+
 	SKIP_BLANKS;
 	if (*type == NODE_TYPE_PI) {
 	    /*
@@ -11110,7 +11139,7 @@
  * @ctxt:  the XPath Parser context
  *
  * [4] Step ::=   AxisSpecifier NodeTest Predicate*
- *                  | AbbreviatedStep 
+ *                  | AbbreviatedStep
  *
  * [12] AbbreviatedStep ::=   '.' | '..'
  *
@@ -11282,10 +11311,10 @@
  * xmlXPathCompRelativeLocationPath:
  * @ctxt:  the XPath Parser context
  *
- *  [3]   RelativeLocationPath ::=   Step 
- *                     | RelativeLocationPath '/' Step 
- *                     | AbbreviatedRelativeLocationPath 
- *  [11]  AbbreviatedRelativeLocationPath ::=   RelativeLocationPath '//' Step 
+ *  [3]   RelativeLocationPath ::=   Step
+ *                     | RelativeLocationPath '/' Step
+ *                     | AbbreviatedRelativeLocationPath
+ *  [11]  AbbreviatedRelativeLocationPath ::=   RelativeLocationPath '//' Step
  *
  * Compile a relative location path.
  */
@@ -11324,12 +11353,12 @@
  * xmlXPathCompLocationPath:
  * @ctxt:  the XPath Parser context
  *
- *  [1]   LocationPath ::=   RelativeLocationPath 
- *                     | AbsoluteLocationPath 
+ *  [1]   LocationPath ::=   RelativeLocationPath
+ *                     | AbsoluteLocationPath
  *  [2]   AbsoluteLocationPath ::=   '/' RelativeLocationPath?
- *                     | AbbreviatedAbsoluteLocationPath 
- *  [10]   AbbreviatedAbsoluteLocationPath ::=   
- *                           '//' RelativeLocationPath 
+ *                     | AbbreviatedAbsoluteLocationPath
+ *  [10]   AbbreviatedAbsoluteLocationPath ::=
+ *                           '//' RelativeLocationPath
  *
  * Compile a location path
  *
@@ -11368,7 +11397,7 @@
 
 /************************************************************************
  *									*
- * 		XPath precompiled expression evaluation			*
+ *		XPath precompiled expression evaluation			*
  *									*
  ************************************************************************/
 
@@ -11377,12 +11406,11 @@
 
 #ifdef DEBUG_STEP
 static void
-xmlXPathDebugDumpStepAxis(xmlXPathAxisVal axis,
-			  xmlXPathTestVal test,
+xmlXPathDebugDumpStepAxis(xmlXPathStepOpPtr op,
 			  int nbNodes)
 {
     xmlGenericError(xmlGenericErrorContext, "new step : ");
-    switch (axis) {
+    switch (op->value) {
         case AXIS_ANCESTOR:
             xmlGenericError(xmlGenericErrorContext, "axis 'ancestors' ");
             break;
@@ -11429,14 +11457,14 @@
     }
     xmlGenericError(xmlGenericErrorContext,
 	" context contains %d nodes\n", nbNodes);
-    switch (test) {
+    switch (op->value2) {
         case NODE_TEST_NONE:
             xmlGenericError(xmlGenericErrorContext,
                             "           searching for none !!!\n");
             break;
         case NODE_TEST_TYPE:
             xmlGenericError(xmlGenericErrorContext,
-                            "           searching for type %d\n", type);
+                            "           searching for type %d\n", op->value3);
             break;
         case NODE_TEST_PI:
             xmlGenericError(xmlGenericErrorContext,
@@ -11449,14 +11477,14 @@
         case NODE_TEST_NS:
             xmlGenericError(xmlGenericErrorContext,
                             "           searching for namespace %s\n",
-                            prefix);
+                            op->value5);
             break;
         case NODE_TEST_NAME:
             xmlGenericError(xmlGenericErrorContext,
-                            "           searching for name %s\n", name);
-            if (prefix != NULL)
+                            "           searching for name %s\n", op->value5);
+            if (op->value4)
                 xmlGenericError(xmlGenericErrorContext,
-                                "           with namespace %s\n", prefix);
+                                "           with namespace %s\n", op->value4);
             break;
     }
     xmlGenericError(xmlGenericErrorContext, "Testing : ");
@@ -11485,7 +11513,7 @@
 	CHECK_ERROR0;
 	if (contextSize <= 0)
 	    return(0);
-    }    
+    }
     if (op->ch2 != -1) {
 	xmlXPathContextPtr xpctxt = ctxt->context;
 	xmlNodePtr contextNode, oldContextNode;
@@ -11529,7 +11557,7 @@
 	/*
 	* Get the expression of this predicate.
 	*/
-	exprOp = &ctxt->comp->steps[op->ch2];	
+	exprOp = &ctxt->comp->steps[op->ch2];
 	newContextSize = 0;
 	for (i = 0; i < set->nodeNr; i++) {
 	    if (set->nodeTab[i] == NULL)
@@ -11539,8 +11567,8 @@
 	    xpctxt->node = contextNode;
 	    xpctxt->contextSize = contextSize;
 	    xpctxt->proximityPosition = ++contextPos;
-	    
-	    /*	   
+
+	    /*
 	    * Also set the xpath document in case things like
 	    * key() are evaluated in the predicate.
 	    */
@@ -11599,7 +11627,7 @@
 	    if (ctxt->value == contextObj)
 		valuePop(ctxt);
 	    xmlXPathReleaseObject(xpctxt, contextObj);
-	}	
+	}
 evaluation_exit:
 	if (exprRes != NULL)
 	    xmlXPathReleaseObject(ctxt->context, exprRes);
@@ -11683,7 +11711,7 @@
 	    xpctxt->node = contextNode;
 	    xpctxt->contextSize = contextSize;
 	    xpctxt->proximityPosition = ++contextPos;
-	    
+
 	    /*
 	    * Initialize the new set.
 	    * Also set the xpath document in case things like
@@ -11705,7 +11733,7 @@
 
 	    valuePush(ctxt, contextObj);
 	    res = xmlXPathCompOpEvalToBoolean(ctxt, exprOp, 1);
-	    
+
 	    if ((ctxt->error != XPATH_EXPRESSION_OK) || (res == -1)) {
 	        xmlXPathObjectPtr tmp;
 		/* pop the result */
@@ -11737,9 +11765,9 @@
 		    }
 		    xmlXPathNodeSetClear(set, hasNsNodes);
 		    set->nodeNr = 1;
-		    set->nodeTab[0] = contextNode;		   
+		    set->nodeTab[0] = contextNode;
 		    goto evaluation_exit;
-		}		
+		}
 		if (pos == maxPos) {
 		    /*
 		    * We are done.
@@ -11803,7 +11831,7 @@
 
 static int
 xmlXPathIsPositionalPredicate(xmlXPathParserContextPtr ctxt,
-			    xmlXPathStepOpPtr op,			    
+			    xmlXPathStepOpPtr op,
 			    int *maxPos)
 {
 
@@ -11812,7 +11840,7 @@
     /*
     * BIG NOTE: This is not intended for XPATH_OP_FILTER yet!
     */
-    
+
     /*
     * If not -1, then ch1 will point to:
     * 1) For predicates (XPATH_OP_PREDICATE):
@@ -11821,13 +11849,13 @@
     *    - an inner filter operater OR
     *    - an expression selecting the node set.
     *      E.g. "key('a', 'b')" or "(//foo | //bar)".
-    */    
+    */
     if ((op->op != XPATH_OP_PREDICATE) && (op->op != XPATH_OP_FILTER))
 	return(0);
 
     if (op->ch2 != -1) {
 	exprOp = &ctxt->comp->steps[op->ch2];
-    } else	
+    } else
 	return(0);
 
     if ((exprOp != NULL) &&
@@ -11846,10 +11874,10 @@
 	* Maybe we could rewrite the AST to ease the optimization.
 	*/
 	*maxPos = (int) ((xmlXPathObjectPtr) exprOp->value4)->floatval;
-	
+
 	if (((xmlXPathObjectPtr) exprOp->value4)->floatval ==
 	    (float) *maxPos)
-	{	    
+	{
 	    return(1);
 	}
     }
@@ -11910,7 +11938,7 @@
     * Used to feed predicate evaluation.
     */
     xmlNodeSetPtr seq;
-    xmlNodePtr cur;    
+    xmlNodePtr cur;
     /* First predicate operator */
     xmlXPathStepOpPtr predOp;
     int maxPos; /* The requested position() (when a "[n]" predicate) */
@@ -11922,7 +11950,7 @@
     xmlXPathTraversalFunctionExt outerNext = NULL;
     void (*addNode) (xmlNodeSetPtr, xmlNodePtr);
     xmlXPathNodeSetMergeFunction mergeAndClear;
-    xmlNodePtr oldContextNode;    
+    xmlNodePtr oldContextNode;
     xmlXPathContextPtr xpctxt = ctxt->context;
 
 
@@ -11937,7 +11965,7 @@
 	    xmlXPathReleaseObject(xpctxt, obj);
             XP_ERROR0(XPATH_UNDEF_PREFIX_ERROR);
 	}
-    }    
+    }
     /*
     * Setup axis.
     *
@@ -11975,8 +12003,8 @@
 		* This iterator will give us only nodes which can
 		* hold element nodes.
 		*/
-		outerNext = xmlXPathNextDescendantOrSelfElemParent;		
-	    }	    
+		outerNext = xmlXPathNextDescendantOrSelfElemParent;
+	    }
 	    if (((test == NODE_TEST_NAME) || (test == NODE_TEST_ALL)) &&
 		(type == NODE_TYPE_NODE))
 	    {
@@ -12031,20 +12059,20 @@
     }
 
 #ifdef DEBUG_STEP
-    xmlXPathDebugDumpStepAxis(axis, test,
-	(obj->nodesetval != NULL) ? obj->nodsetval->nodeNr : 0);
+    xmlXPathDebugDumpStepAxis(op,
+	(obj->nodesetval != NULL) ? obj->nodesetval->nodeNr : 0);
 #endif
 
     if (next == NULL) {
-	xmlXPathReleaseObject(xpctxt, obj); 
+	xmlXPathReleaseObject(xpctxt, obj);
         return(0);
-    }    
+    }
     contextSeq = obj->nodesetval;
     if ((contextSeq == NULL) || (contextSeq->nodeNr <= 0)) {
 	xmlXPathReleaseObject(xpctxt, obj);
         valuePush(ctxt, xmlXPathCacheWrapNodeSet(xpctxt, NULL));
         return(0);
-    }   
+    }
     /*
     * Predicate optimization ---------------------------------------------
     * If this step has a last predicate, which contains a position(),
@@ -12052,7 +12080,7 @@
     * the  short-hand form, i.e., "[n]".
     *
     * Example - expression "/foo[parent::bar][1]":
-    *  
+    *
     * COLLECT 'child' 'name' 'node' foo    -- op (we are here)
     *   ROOT                               -- op->ch1
     *   PREDICATE                          -- op->ch2 (predOp)
@@ -12085,7 +12113,7 @@
 		*/
 		predOp = NULL;
 		hasAxisRange = 1;
-	    }	    
+	    }
 	}
     }
     breakOnFirstHit = ((toBool) && (predOp == NULL)) ? 1 : 0;
@@ -12094,7 +12122,7 @@
     */
     /*
      * 2.3 Node Tests
-     *  - For the attribute axis, the principal node type is attribute. 
+     *  - For the attribute axis, the principal node type is attribute.
      *  - For the namespace axis, the principal node type is namespace.
      *  - For other axes, the principal node type is element.
      *
@@ -12131,8 +12159,8 @@
 	    */
 	    xpctxt->node = contextNode;
 	} else
-	    xpctxt->node = contextSeq->nodeTab[contextIdx++];	
-        
+	    xpctxt->node = contextSeq->nodeTab[contextIdx++];
+
 	if (seq == NULL) {
 	    seq = xmlXPathNodeSetCreate(NULL);
 	    if (seq == NULL) {
@@ -12186,7 +12214,7 @@
 #ifdef DEBUG_STEP
             xmlGenericError(xmlGenericErrorContext, " %s", cur->name);
 #endif
-            
+
 	    switch (test) {
                 case NODE_TEST_NONE:
 		    total = 0;
@@ -12205,7 +12233,7 @@
 #ifdef LIBXML_DOCB_ENABLED
 			    case XML_DOCB_DOCUMENT_NODE:
 #endif
-			    case XML_ELEMENT_NODE:			    
+			    case XML_ELEMENT_NODE:
 			    case XML_ATTRIBUTE_NODE:
 			    case XML_PI_NODE:
 			    case XML_COMMENT_NODE:
@@ -12333,7 +12361,7 @@
 
 	goto apply_predicates;
 
-axis_range_end: /* ----------------------------------------------------- */	
+axis_range_end: /* ----------------------------------------------------- */
 	/*
 	* We have a "/foo[n]", and position() = n was reached.
 	* Note that we can have as well "/foo/::parent::foo[1]", so
@@ -12372,11 +12400,11 @@
 apply_predicates: /* --------------------------------------------------- */
         /*
 	* Apply predicates.
-	*/	
+	*/
         if ((predOp != NULL) && (seq->nodeNr > 0)) {
 	    /*
 	    * E.g. when we have a "/foo[some expression][n]".
-	    */	    	    
+	    */	    
 	    /*
 	    * QUESTION TODO: The old predicate evaluation took into
 	    *  account location-sets.
@@ -12385,7 +12413,7 @@
 	    *  All what I learned now from the evaluation semantics
 	    *  does not indicate that a location-set will be processed
 	    *  here, so this looks OK.
-	    */	    	    
+	    */	    
 	    /*
 	    * Iterate over all predicates, starting with the outermost
 	    * predicate.
@@ -12401,7 +12429,7 @@
 	    *
 	    * For the moment, I'll try to solve this with a recursive
 	    * function: xmlXPathCompOpEvalPredicate().
-	    */	    
+	    */
 	    size = seq->nodeNr;
 	    if (hasPredicateRange != 0)
 		newSize = xmlXPathCompOpEvalPositionalPredicate(ctxt,
@@ -12456,7 +12484,7 @@
 	    } else {
 		outSeq = mergeAndClear(outSeq, seq, 0);
 	    }
-	}	
+	}
     }
 
 error:
@@ -12481,10 +12509,11 @@
 	    outSeq = seq;
 	else
 	    outSeq = xmlXPathNodeSetCreate(NULL);
+        /* XXX what if xmlXPathNodeSetCreate returned NULL here? */
     }
     if ((seq != NULL) && (seq != outSeq)) {
 	 xmlXPathFreeNodeSet(seq);
-    }    
+    }
     /*
     * Hand over the result. Better to push the set also in
     * case of errors.
@@ -12768,9 +12797,9 @@
 			      xmlXPathStepOpPtr op, xmlNodePtr * first)
 {
     int total = 0;
-    xmlXPathCompExprPtr comp;    
+    xmlXPathCompExprPtr comp;
     xmlXPathObjectPtr res;
-    xmlXPathObjectPtr obj;    
+    xmlXPathObjectPtr obj;
     xmlNodeSetPtr oldset;
     xmlNodePtr oldnode;
     xmlDocPtr oldDoc;
@@ -12785,7 +12814,7 @@
 	(comp->steps[op->ch1].op == XPATH_OP_SORT) &&
 	(comp->steps[op->ch2].op == XPATH_OP_SORT)) {
 	int f = comp->steps[op->ch2].ch1;
-	
+
 	if ((f != -1) &&
 	    (comp->steps[f].op == XPATH_OP_FUNCTION) &&
 	    (comp->steps[f].value5 == NULL) &&
@@ -12794,7 +12823,7 @@
 	    (xmlStrEqual
 	    (comp->steps[f].value4, BAD_CAST "last"))) {
 	    xmlNodePtr last = NULL;
-	    
+
 	    total +=
 		xmlXPathCompOpEvalLast(ctxt,
 		    &comp->steps[op->ch1],
@@ -12821,7 +12850,7 @@
 	    return (total);
 	}
     }
-    
+
     if (op->ch1 != -1)
 	total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
     CHECK_ERROR0;
@@ -12829,7 +12858,7 @@
 	return (total);
     if (ctxt->value == NULL)
 	return (total);
-    
+
 #ifdef LIBXML_XPTR_ENABLED
     oldnode = ctxt->context->node;
     /*
@@ -12839,7 +12868,7 @@
 	xmlXPathObjectPtr tmp = NULL;
 	xmlLocationSetPtr newlocset = NULL;
 	xmlLocationSetPtr oldlocset;
-	
+
 	/*
 	* Extract the old locset, and then evaluate the result of the
 	* expression for all the element in the locset. use it to grow
@@ -12849,7 +12878,7 @@
 	obj = valuePop(ctxt);
 	oldlocset = obj->user;
 	ctxt->context->node = NULL;
-	
+
 	if ((oldlocset == NULL) || (oldlocset->locNr == 0)) {
 	    ctxt->context->contextSize = 0;
 	    ctxt->context->proximityPosition = 0;
@@ -12864,7 +12893,7 @@
 	    return (total);
 	}
 	newlocset = xmlXPtrLocationSetCreate(NULL);
-	
+
 	for (i = 0; i < oldlocset->locNr; i++) {
 	    /*
 	    * Run the evaluation with a node list made of a
@@ -12879,7 +12908,7 @@
 	    } else {
 		xmlXPathNodeSetAddUnique(tmp->nodesetval,
 		    ctxt->context->node);
-	    }	    
+	    }
 	    valuePush(ctxt, tmp);
 	    if (op->ch2 != -1)
 		total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
@@ -12905,14 +12934,14 @@
 	    }
 	    if (ctxt->value == tmp) {
 		valuePop(ctxt);
-		xmlXPathNodeSetClear(tmp->nodesetval, 1);		
+		xmlXPathNodeSetClear(tmp->nodesetval, 1);
 		/*
 		* REVISIT TODO: Don't create a temporary nodeset
 		* for everly iteration.
 		*/
 		/* OLD: xmlXPathFreeObject(res); */
 	    } else
-		tmp = NULL;	    
+		tmp = NULL;
 	    ctxt->context->node = NULL;
 	    /*
 	    * Only put the first node in the result, then leave.
@@ -12937,7 +12966,7 @@
 	return (total);
     }
 #endif /* LIBXML_XPTR_ENABLED */
-    
+
     /*
     * Extract the old set, and then evaluate the result of the
     * expression for all the element in the set. use it to grow
@@ -12946,11 +12975,11 @@
     CHECK_TYPE0(XPATH_NODESET);
     obj = valuePop(ctxt);
     oldset = obj->nodesetval;
-    
+
     oldnode = ctxt->context->node;
     oldDoc = ctxt->context->doc;
     ctxt->context->node = NULL;
-    
+
     if ((oldset == NULL) || (oldset->nodeNr == 0)) {
 	ctxt->context->contextSize = 0;
 	ctxt->context->proximityPosition = 0;
@@ -12974,9 +13003,10 @@
 	* Initialize the new set.
 	* Also set the xpath document in case things like
 	* key() evaluation are attempted on the predicate
-	*/	
+	*/
 	newset = xmlXPathNodeSetCreate(NULL);
-	
+        /* XXX what if xmlXPathNodeSetCreate returned NULL? */
+
 	for (i = 0; i < oldset->nodeNr; i++) {
 	    /*
 	    * Run the evaluation with a node list made of
@@ -13002,7 +13032,7 @@
 		xmlXPathFreeNodeSet(newset);
 		xmlXPathFreeObject(obj);
 		return(0);
-	    }	    
+	    }
 	    /*
 	    * The result of the evaluation needs to be tested to
 	    * decide whether the filter succeeded or not
@@ -13010,7 +13040,7 @@
 	    res = valuePop(ctxt);
 	    if (xmlXPathEvaluatePredicateResult(ctxt, res)) {
 		xmlXPathNodeSetAdd(newset, oldset->nodeTab[i]);
-	    }	    
+	    }
 	    /*
 	    * Cleanup
 	    */
@@ -13146,7 +13176,7 @@
             total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
 	    CHECK_ERROR0;
 	    if (op->value)
-        	equal = xmlXPathEqualValues(ctxt);
+		equal = xmlXPathEqualValues(ctxt);
 	    else
 		equal = xmlXPathNotEqualValues(ctxt);
 	    valuePush(ctxt, xmlXPathCacheNewBoolean(ctxt->context, equal));
@@ -13299,8 +13329,8 @@
                     URI = xmlXPathNsLookup(ctxt->context, op->value5);
                     if (URI == NULL) {
                         xmlGenericError(xmlGenericErrorContext,
-                                        "xmlXPathCompOpEval: variable %s bound to undefined prefix %s\n",
-                                        op->value4, op->value5);
+            "xmlXPathCompOpEval: variable %s bound to undefined prefix %s\n",
+                                    (char *) op->value4, (char *)op->value5);
                         return (total);
                     }
 		    val = xmlXPathVariableLookupNS(ctxt->context,
@@ -13347,8 +13377,8 @@
                         URI = xmlXPathNsLookup(ctxt->context, op->value5);
                         if (URI == NULL) {
                             xmlGenericError(xmlGenericErrorContext,
-                                            "xmlXPathCompOpEval: function %s bound to undefined prefix %s\n",
-                                            op->value4, op->value5);
+            "xmlXPathCompOpEval: function %s bound to undefined prefix %s\n",
+                                    (char *)op->value4, (char *)op->value5);
                             return (total);
                         }
                         func = xmlXPathFunctionLookupNS(ctxt->context,
@@ -13356,8 +13386,8 @@
                     }
                     if (func == NULL) {
                         xmlGenericError(xmlGenericErrorContext,
-                                        "xmlXPathCompOpEval: function %s not found\n",
-                                        op->value4);
+                                "xmlXPathCompOpEval: function %s not found\n",
+                                        (char *)op->value4);
                         XP_ERROR0(XPATH_UNKNOWN_FUNC_ERROR);
                     }
                     op->cache = XML_CAST_FPTR(func);
@@ -13555,7 +13585,7 @@
 			tmp = xmlXPathCacheNewNodeSet(ctxt->context,
 			    ctxt->context->node);
                         valuePush(ctxt, tmp);
-			
+
                         if (op->ch2 != -1)
                             total +=
                                 xmlXPathCompOpEval(ctxt,
@@ -13664,7 +13694,7 @@
 		    *    nC         2
 		    *
 		    * removed the first node in the node-set, then
-		    * the context position of the 
+		    * the context position of the
 		    */
                     for (i = 0; i < oldset->nodeNr; i++) {
                         /*
@@ -13721,7 +13751,7 @@
 			}
                         if (ctxt->value == tmp) {
                             valuePop(ctxt);
-			    xmlXPathNodeSetClear(tmp->nodesetval, 1);			    
+			    xmlXPathNodeSetClear(tmp->nodesetval, 1);
 			    /*
 			    * Don't free the temporary nodeset
 			    * in order to avoid massive recreation inside this
@@ -13824,7 +13854,7 @@
 
                         res = valuePop(ctxt);
 			if (res->type == XPATH_LOCATIONSET) {
-			    xmlLocationSetPtr rloc = 
+			    xmlLocationSetPtr rloc =
 			        (xmlLocationSetPtr)res->user;
 			    for (j=0; j<rloc->locNr; j++) {
 			        range = xmlXPtrNewRange(
@@ -13986,7 +14016,7 @@
 	    xmlXPathCompOpEval(ctxt, op);
 	    if (ctxt->error != XPATH_EXPRESSION_OK)
 		return(-1);
-	    
+
 	    resObj = valuePop(ctxt);
 	    if (resObj == NULL)
 		return(-1);
@@ -14007,7 +14037,7 @@
 	    *  to true if the number is equal to the context position
 	    *  and will be converted to false otherwise;"
 	    */
-	    res = xmlXPathEvaluatePredicateResult(ctxt, resObj); 
+	    res = xmlXPathEvaluatePredicateResult(ctxt, resObj);
 	} else {
 	    res = xmlXPathCastToBoolean(resObj);
 	}
@@ -14030,13 +14060,13 @@
 		      xmlXPathObjectPtr *resultSeq, int toBool)
 {
     int max_depth, min_depth;
-    int from_root;    
+    int from_root;
     int ret, depth;
     int eval_all_nodes;
     xmlNodePtr cur = NULL, limit = NULL;
     xmlStreamCtxtPtr patstream = NULL;
-    
-    int nb_nodes = 0;    
+
+    int nb_nodes = 0;
 
     if ((ctxt == NULL) || (comp == NULL))
         return(-1);
@@ -14062,7 +14092,7 @@
 	if (*resultSeq == NULL)
 	    return(-1);
     }
-    
+
     /*
      * handle the special cases of "/" amd "." being matched
      */
@@ -14159,7 +14189,7 @@
 		    ret = xmlStreamPushNode(patstream, NULL, NULL, cur->type);
 		else
 		    break;
-		
+
 		if (ret < 0) {
 		    /* NOP. */
 		} else if (ret == 1) {
@@ -14183,7 +14213,7 @@
 scan_children:
 	if ((cur->children != NULL) && (depth < max_depth)) {
 	    /*
-	     * Do not descend on entities declarations	     
+	     * Do not descend on entities declarations
 	     */
 	    if (cur->children->type != XML_ENTITY_DECL) {
 		cur = cur->children;
@@ -14205,7 +14235,7 @@
 		(cur->type != XML_DTD_NODE))
 		goto next_node;
 	}
-	
+
 	do {
 	    cur = cur->parent;
 	    depth--;
@@ -14264,7 +14294,7 @@
 
     if (ctxt->valueTab == NULL) {
 	/* Allocate the value stack */
-	ctxt->valueTab = (xmlXPathObjectPtr *) 
+	ctxt->valueTab = (xmlXPathObjectPtr *)
 			 xmlMalloc(10 * sizeof(xmlXPathObjectPtr));
 	if (ctxt->valueTab == NULL) {
 	    xmlXPathPErrMemory(ctxt, "creating evaluation context\n");
@@ -14287,7 +14317,7 @@
 	    if (res != -1)
 		return(res);
 	} else {
-	    xmlXPathObjectPtr resObj = NULL;	
+	    xmlXPathObjectPtr resObj = NULL;
 
 	    /*
 	    * Evaluation to a sequence.
@@ -14300,7 +14330,7 @@
 		return(0);
 	    }
 	    if (resObj != NULL)
-		xmlXPathReleaseObject(ctxt->context, resObj);	
+		xmlXPathReleaseObject(ctxt->context, resObj);
 	}
 	/*
 	* QUESTION TODO: This falls back to normal XPath evaluation
@@ -14325,7 +14355,7 @@
 
 /************************************************************************
  *									*
- * 			Public interfaces				*
+ *			Public interfaces				*
  *									*
  ************************************************************************/
 
@@ -14341,7 +14371,7 @@
  * context node in the context node list (as returned by the position
  * function) and will be converted to false otherwise; if the result
  * is not a number, then the result will be converted as if by a call
- * to the boolean function. 
+ * to the boolean function.
  *
  * Returns 1 if predicate is true, 0 otherwise
  */
@@ -14379,12 +14409,12 @@
  * context node in the context node list (as returned by the position
  * function) and will be converted to false otherwise; if the result
  * is not a number, then the result will be converted as if by a call
- * to the boolean function. 
+ * to the boolean function.
  *
  * Returns 1 if predicate is true, 0 otherwise
  */
 int
-xmlXPathEvaluatePredicateResult(xmlXPathParserContextPtr ctxt, 
+xmlXPathEvaluatePredicateResult(xmlXPathParserContextPtr ctxt,
                                 xmlXPathObjectPtr res) {
     if ((ctxt == NULL) || (res == NULL)) return(0);
     switch (res->type) {
@@ -14457,7 +14487,7 @@
 	tmp = xmlStrchr(str, ':');
 	if ((tmp != NULL) &&
 	    ((ctxt == NULL) || (ctxt->nsNr == 0) || (tmp[1] == ':')))
-	    return(NULL);	    
+	    return(NULL);
 
 	if (ctxt != NULL) {
 	    dict = ctxt->dict;
@@ -14481,7 +14511,7 @@
 			&namespaces[0]);
 	if (namespaces != NULL) {
 	    xmlFree((xmlChar **)namespaces);
- 	}
+	}
 	if ((stream != NULL) && (xmlPatternStreamable(stream) == 1)) {
 	    comp = xmlXPathNewCompExpr();
 	    if (comp == NULL) {
@@ -14520,30 +14550,30 @@
     */
     if (op->ch1 != -1) {
 	if ((op->op == XPATH_OP_COLLECT /* 11 */) &&
-	    ((xmlXPathAxisVal) op->value == AXIS_CHILD /* 4 */) &&	    
+	    ((xmlXPathAxisVal) op->value == AXIS_CHILD /* 4 */) &&
 	    ((xmlXPathTestVal) op->value2 == NODE_TEST_NAME /* 5 */) &&
 	    ((xmlXPathTypeVal) op->value3 == NODE_TYPE_NODE /* 0 */))
 	{
 	    /*
 	    * This is a "child::foo"
 	    */
-	    xmlXPathStepOpPtr prevop = &comp->steps[op->ch1];	    
+	    xmlXPathStepOpPtr prevop = &comp->steps[op->ch1];
 
 	    if ((prevop->op == XPATH_OP_COLLECT /* 11 */) &&
-		(prevop->ch1 != -1) &&	    
+		(prevop->ch1 != -1) &&
 		((xmlXPathAxisVal) prevop->value ==
 		    AXIS_DESCENDANT_OR_SELF) &&
 		(prevop->ch2 == -1) &&
 		((xmlXPathTestVal) prevop->value2 == NODE_TEST_TYPE) &&
 		((xmlXPathTypeVal) prevop->value3 == NODE_TYPE_NODE) &&
 		(comp->steps[prevop->ch1].op == XPATH_OP_ROOT))
-	    {		
+	    {
 		/*
 		* This is a "/descendant-or-self::node()" without predicates.
 		* Eliminate it.
 		*/
 		op->ch1 = prevop->ch1;
-		op->rewriteType = XP_REWRITE_DOS_CHILD_ELEM;		
+		op->rewriteType = XP_REWRITE_DOS_CHILD_ELEM;
 	    }
 	}
 	if (op->ch1 != -1)
@@ -14588,7 +14618,7 @@
     }
 
     if (*pctxt->cur != 0) {
-	/* 
+	/*
 	 * aleksey: in some cases this line prints *second* error message
 	 * (see bug #78858) and probably this should be fixed.
 	 * However, we are not sure that all error messages are printed
@@ -14607,7 +14637,7 @@
 #ifdef DEBUG_EVAL_COUNTS
 	comp->string = xmlStrdup(str);
 	comp->nb = 0;
-#endif  
+#endif
 	if ((comp->expr != NULL) &&
 	    (comp->nbStep > 2) &&
 	    (comp->last >= 0) &&
@@ -14652,7 +14682,7 @@
 			     xmlXPathObjectPtr *resObj,
 			     int toBool)
 {
-    xmlXPathParserContextPtr pctxt;    
+    xmlXPathParserContextPtr pctxt;
 #ifndef LIBXML_THREAD_ENABLED
     static int reentance = 0;
 #endif
@@ -14681,15 +14711,15 @@
     res = xmlXPathRunEval(pctxt, toBool);
 
     if (resObj) {
-	if (pctxt->value == NULL) {	    
+	if (pctxt->value == NULL) {
 	    xmlGenericError(xmlGenericErrorContext,
 		"xmlXPathCompiledEval: evaluation failed\n");
-	    *resObj = NULL;	    
+	    *resObj = NULL;
 	} else {
 	    *resObj = valuePop(pctxt);
 	}
     }
-    
+
     /*
     * Pop all remaining objects from the stack.
     */
@@ -14700,7 +14730,7 @@
 	do {
 	    tmp = valuePop(pctxt);
 	    if (tmp != NULL) {
-		stack++; 
+		stack++;
 		xmlXPathReleaseObject(ctxt, tmp);
 	    }
 	} while (tmp != NULL);
@@ -14712,11 +14742,11 @@
 		stack);
 	}
     }
-    
+
     if ((pctxt->error != XPATH_EXPRESSION_OK) && (resObj) && (*resObj)) {
 	xmlXPathFreeObject(*resObj);
 	*resObj = NULL;
-    }        
+    }
     pctxt->comp = NULL;
     xmlXPathFreeParserContext(pctxt);
 #ifndef LIBXML_THREAD_ENABLED
@@ -14777,7 +14807,7 @@
 #endif
 
     if (ctxt == NULL) return;
-    
+
 #ifdef XPATH_STREAMING
     comp = xmlXPathTryStreamCompile(ctxt->context, ctxt->base);
     if (comp != NULL) {
@@ -14805,7 +14835,7 @@
 	}
     }
     CHECK_ERROR;
-    xmlXPathRunEval(ctxt, 0);    
+    xmlXPathRunEval(ctxt, 0);
 }
 
 /**
@@ -14837,7 +14867,7 @@
 	xmlGenericError(xmlGenericErrorContext,
 		"xmlXPathEval: evaluation failed\n");
 	res = NULL;
-    } else if ((*ctxt->cur != 0) && (ctxt->comp != NULL) 
+    } else if ((*ctxt->cur != 0) && (ctxt->comp != NULL)
 #ifdef XPATH_STREAMING
             && (ctxt->comp->stream == NULL)
 #endif
@@ -14950,21 +14980,21 @@
  * If $escape-reserved is false, the behavior differs in that characters
  * referred to in [RFC 2396] as reserved characters are not escaped. These
  * characters are ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ",".
- * 
+ *
  * [RFC 2396] does not define whether escaped URIs should use lower case or
  * upper case for hexadecimal digits. To ensure that escaped URIs can be
  * compared using string comparison functions, this function must always use
  * the upper-case letters A-F.
- * 
+ *
  * Generally, $escape-reserved should be set to true when escaping a string
  * that is to form a single part of a URI, and to false when escaping an
  * entire URI or URI reference.
- * 
- * In the case of non-ascii characters, the string is encoded according to 
+ *
+ * In the case of non-ascii characters, the string is encoded according to
  * utf-8 and then converted according to RFC 2396.
  *
  * Examples
- *  xf:escape-uri ("gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles#ocean"), true()) 
+ *  xf:escape-uri ("gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles#ocean"), true())
  *  returns "gopher%3A%2F%2Fspinaltap.micro.umn.edu%2F00%2FWeather%2FCalifornia%2FLos%20Angeles%23ocean"
  *  xf:escape-uri ("gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles#ocean"), false())
  *  returns "gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles%23ocean"
@@ -14977,28 +15007,28 @@
     xmlBufferPtr target;
     xmlChar *cptr;
     xmlChar escape[4];
-    
+
     CHECK_ARITY(2);
-    
+
     escape_reserved = xmlXPathPopBoolean(ctxt);
-    
+
     CAST_TO_STRING;
     str = valuePop(ctxt);
-    
+
     target = xmlBufferCreate();
-    
+
     escape[0] = '%';
     escape[3] = 0;
-    
+
     if (target) {
 	for (cptr = str->stringval; *cptr; cptr++) {
 	    if ((*cptr >= 'A' && *cptr <= 'Z') ||
 		(*cptr >= 'a' && *cptr <= 'z') ||
 		(*cptr >= '0' && *cptr <= '9') ||
-		*cptr == '-' || *cptr == '_' || *cptr == '.' || 
+		*cptr == '-' || *cptr == '_' || *cptr == '.' ||
 		*cptr == '!' || *cptr == '~' || *cptr == '*' ||
 		*cptr == '\''|| *cptr == '(' || *cptr == ')' ||
-		(*cptr == '%' && 
+		(*cptr == '%' &&
 		 ((cptr[1] >= 'A' && cptr[1] <= 'F') ||
 		  (cptr[1] >= 'a' && cptr[1] <= 'f') ||
 		  (cptr[1] >= '0' && cptr[1] <= '9')) &&
@@ -15020,7 +15050,7 @@
 		    escape[2] = '0' + (*cptr & 0xF);
 		else
 		    escape[2] = 'A' - 10 + (*cptr & 0xF);
-		
+
 		xmlBufferAdd(target, &escape[0], 3);
 	    }
 	}