From f228a843747ef0b6d42cdc3b68d981367e6da191 Mon Sep 17 00:00:00 2001
From: libxml2 Upstream <kwrobot@kitware.com>
Date: Mon, 30 Dec 2019 12:02:08 -0500
Subject: [PATCH] libxml2 2019-12-30 (48fa09ad)

Code extracted from:

    https://gitlab.kitware.com/third-party/libxml2.git

at commit 48fa09ade949de894d892d92894c169f42b3b3c4 (for/vtk-20191230-2.9.10).
---
 HTMLparser.c                        |   31 +-
 HTMLtree.c                          |    2 +-
 README                              |    1 +
 SAX2.c                              |   22 +-
 buf.c                               |   12 +-
 c14n.c                              |   12 +-
 catalog.c                           |    2 +-
 debugXML.c                          |   22 +-
 dict.c                              |   13 +-
 elfgcchack.h                        |   10 +
 enc.h                               |    2 +-
 encoding.c                          |   18 +-
 entities.c                          |    6 +-
 error.c                             |    4 +-
 globals.c                           |    6 +-
 hash.c                              |    9 +-
 include/libxml/c14n.h               |   12 +-
 include/libxml/catalog.h            |    2 +-
 include/libxml/dict.h               |   19 +-
 include/libxml/hash.h               |    4 +-
 include/libxml/parser.h             |    8 +-
 include/libxml/parserInternals.h    |    2 +-
 include/libxml/schemasInternals.h   |   12 +-
 include/libxml/tree.h               |    2 +-
 include/libxml/vtk_libxml2_mangle.h |  387 +++---
 include/libxml/xlink.h              |    2 +-
 include/libxml/xmlIO.h              |    4 +-
 include/libxml/xmlerror.h           |    2 +-
 include/libxml/xmlexports.h         |    9 -
 include/libxml/xmlversion.h.in      |    7 +-
 include/libxml/xpath.h              |   13 +-
 libxml.h                            |   13 +-
 parser.c                            |  574 ++++-----
 parserInternals.c                   |    8 +-
 pattern.c                           |   17 +-
 relaxng.c                           |   90 +-
 save.h                              |    5 +-
 schematron.c                        |    8 +-
 threads.c                           |    4 +-
 timsort.h                           |    7 +-
 tree.c                              |   90 +-
 trionan.c                           |    2 +-
 uri.c                               |   20 +-
 valid.c                             |  193 +--
 xinclude.c                          |   26 +-
 xmlIO.c                             |   59 +-
 xmlmodule.c                         |    4 +-
 xmlreader.c                         |   87 +-
 xmlregexp.c                         |   99 +-
 xmlsave.c                           |   23 +-
 xmlschemas.c                        |  188 ++-
 xmlschemastypes.c                   |   20 +-
 xmlwriter.c                         |    6 +-
 xpath.c                             | 1697 ++++++++++-----------------
 xpointer.c                          |   18 +-
 55 files changed, 1842 insertions(+), 2073 deletions(-)

diff --git a/HTMLparser.c b/HTMLparser.c
index 4a30be5f464..0d6d851d0e6 100644
--- a/HTMLparser.c
+++ b/HTMLparser.c
@@ -317,7 +317,7 @@ htmlNodeInfoPop(htmlParserCtxtPtr ctxt)
 
 #define SKIP_BLANKS htmlSkipBlankChars(ctxt)
 
-/* Inported from XML */
+/* Imported from XML */
 
 /* #define CUR (ctxt->token ? ctxt->token : (int) (*ctxt->input->cur)) */
 #define CUR ((int) (*ctxt->input->cur))
@@ -537,7 +537,7 @@ htmlCurrentChar(xmlParserCtxtPtr ctxt, int *len) {
 encoding_error:
     /*
      * If we detect an UTF8 error that probably mean that the
-     * input encoding didn't get properly advertized in the
+     * input encoding didn't get properly advertised in the
      * declaration header. Report the error and switch the encoding
      * to ISO-Latin-1 (if you don't like this policy, just declare the
      * encoding !)
@@ -602,8 +602,8 @@ htmlSkipBlankChars(xmlParserCtxtPtr ctxt) {
  ************************************************************************/
 
 /*
- *  Start Tag: 1 means the start tag can be ommited
- *  End Tag:   1 means the end tag can be ommited
+ *  Start Tag: 1 means the start tag can be omitted
+ *  End Tag:   1 means the end tag can be omitted
  *             2 means it's forbidden (empty elements)
  *             3 means the tag is stylistic and should be closed easily
  *  Depr:      this element is deprecated
@@ -1342,7 +1342,7 @@ htmlAutoCloseOnClose(htmlParserCtxtPtr ctxt, const xmlChar * newtag)
         if (xmlStrEqual(newtag, ctxt->nameTab[i]))
             break;
         /*
-         * A missplaced endtag can only close elements with lower
+         * A misplaced endtag can only close elements with lower
          * or equal priority, so if we find an element with higher
          * priority before we find an element with
          * matching name, we just ignore this endtag
@@ -2176,6 +2176,7 @@ htmlEncodeEntities(unsigned char* out, int *outlen,
  *									*
  ************************************************************************/
 
+#ifdef LIBXML_PUSH_ENABLED
 /**
  * htmlNewInputStream:
  * @ctxt:  an HTML parser context
@@ -2207,6 +2208,7 @@ htmlNewInputStream(htmlParserCtxtPtr ctxt) {
     input->length = 0;
     return(input);
 }
+#endif
 
 
 /************************************************************************
@@ -2216,9 +2218,9 @@ htmlNewInputStream(htmlParserCtxtPtr ctxt) {
  ************************************************************************/
 /*
  * all tags allowing pc data from the html 4.01 loose dtd
- * NOTE: it might be more apropriate to integrate this information
+ * NOTE: it might be more appropriate to integrate this information
  * into the html40ElementTable array but I don't want to risk any
- * binary incomptibility
+ * binary incompatibility
  */
 static const char *allowPCData[] = {
     "a", "abbr", "acronym", "address", "applet", "b", "bdo", "big",
@@ -2959,6 +2961,7 @@ htmlParseScript(htmlParserCtxtPtr ctxt) {
 	}
 	COPY_BUF(l,buf,nbchar,cur);
 	if (nbchar >= HTML_PARSER_BIG_BUFFER_SIZE) {
+            buf[nbchar] = 0;
 	    if (ctxt->sax->cdataBlock!= NULL) {
 		/*
 		 * Insert as CDATA, which is the same as HTML_PRESERVE_NODE
@@ -2983,6 +2986,7 @@ htmlParseScript(htmlParserCtxtPtr ctxt) {
     }
 
     if ((nbchar != 0) && (ctxt->sax != NULL) && (!ctxt->disableSAX)) {
+        buf[nbchar] = 0;
 	if (ctxt->sax->cdataBlock!= NULL) {
 	    /*
 	     * Insert as CDATA, which is the same as HTML_PRESERVE_NODE
@@ -3028,6 +3032,8 @@ htmlParseCharDataInternal(htmlParserCtxtPtr ctxt, int readahead) {
 	    COPY_BUF(l,buf,nbchar,cur);
 	}
 	if (nbchar >= HTML_PARSER_BIG_BUFFER_SIZE) {
+            buf[nbchar] = 0;
+
 	    /*
 	     * Ok the segment is to be consumed as chars.
 	     */
@@ -5762,13 +5768,13 @@ htmlParseTryOrFinish(htmlParserCtxtPtr ctxt, int terminate) {
                 break;
 	    }
             case XML_PARSER_CONTENT: {
+		xmlChar chr[2] = { 0, 0 };
 		long cons;
+
                 /*
 		 * Handle preparsed entities and charRef
 		 */
 		if (ctxt->token != 0) {
-		    xmlChar chr[2] = { 0 , 0 } ;
-
 		    chr[0] = (xmlChar) ctxt->token;
 		    htmlCheckParagraph(ctxt);
 		    if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL))
@@ -5780,21 +5786,22 @@ htmlParseTryOrFinish(htmlParserCtxtPtr ctxt, int terminate) {
 		    cur = in->cur[0];
 		    if ((cur != '<') && (cur != '&')) {
 			if (ctxt->sax != NULL) {
+                            chr[0] = cur;
 			    if (IS_BLANK_CH(cur)) {
 				if (ctxt->keepBlanks) {
 				    if (ctxt->sax->characters != NULL)
 					ctxt->sax->characters(
-						ctxt->userData, &in->cur[0], 1);
+						ctxt->userData, chr, 1);
 				} else {
 				    if (ctxt->sax->ignorableWhitespace != NULL)
 					ctxt->sax->ignorableWhitespace(
-						ctxt->userData, &in->cur[0], 1);
+						ctxt->userData, chr, 1);
 				}
 			    } else {
 				htmlCheckParagraph(ctxt);
 				if (ctxt->sax->characters != NULL)
 				    ctxt->sax->characters(
-					    ctxt->userData, &in->cur[0], 1);
+					    ctxt->userData, chr, 1);
 			    }
 			}
 			ctxt->token = 0;
diff --git a/HTMLtree.c b/HTMLtree.c
index 21cfcfe591e..db63b371f06 100644
--- a/HTMLtree.c
+++ b/HTMLtree.c
@@ -1048,7 +1048,7 @@ htmlDocContentDumpFormatOutput(xmlOutputBufferPtr buf, xmlDocPtr cur,
  * @cur:  the document
  * @encoding:  the encoding string
  *
- * Dump an HTML document. Formating return/spaces are added.
+ * Dump an HTML document. Formatting return/spaces are added.
  */
 void
 htmlDocContentDumpOutput(xmlOutputBufferPtr buf, xmlDocPtr cur,
diff --git a/README b/README
index 749e671fe5e..5c7bddf8de2 100644
--- a/README
+++ b/README
@@ -8,6 +8,7 @@ This code is released under the MIT Licence see the Copyright file.
 
 To build on an Unixised setup:
    ./configure ; make ; make install
+   if the ./configure file does not exist, run ./autogen.sh instead.
 To build on Windows:
    see instructions on win32/Readme.txt
 
diff --git a/SAX2.c b/SAX2.c
index 7642501a186..5f141f9a3cc 100644
--- a/SAX2.c
+++ b/SAX2.c
@@ -40,7 +40,7 @@
  * TODO:
  *
  * macro to flag unimplemented blocks
- * XML_CATALOG_PREFER user env to select between system/public prefered
+ * XML_CATALOG_PREFER user env to select between system/public preferred
  * option. C.f. Richard Tobin <richard@cogsci.ed.ac.uk>
  *> Just FYI, I am using an environment variable XML_CATALOG_PREFER with
  *> values "system" and "public".  I have made the default be "system" to
@@ -1512,8 +1512,8 @@ process_external_subset:
 	attr = elemDecl->attributes;
 	while (attr != NULL) {
 	    /*
-	     * Make sure that attributes redefinition occuring in the
-	     * internal subset are not overriden by definitions in the
+	     * Make sure that attributes redefinition occurring in the
+	     * internal subset are not overridden by definitions in the
 	     * external subset.
 	     */
 	    if (attr->defaultValue != NULL) {
@@ -1668,6 +1668,8 @@ xmlSAX2StartElement(void *ctx, const xmlChar *fullname, const xmlChar **atts)
     if (nodePush(ctxt, ret) < 0) {
         xmlUnlinkNode(ret);
         xmlFreeNode(ret);
+        if (prefix != NULL)
+            xmlFree(prefix);
         return;
     }
 
@@ -1734,8 +1736,8 @@ xmlSAX2StartElement(void *ctx, const xmlChar *fullname, const xmlChar **atts)
     }
 
     /*
-     * set the namespace node, making sure that if the default namspace
-     * is unbound on a parent we simply kee it NULL
+     * set the namespace node, making sure that if the default namespace
+     * is unbound on a parent we simply keep it NULL
      */
     if ((ns != NULL) && (ns->href != NULL) &&
 	((ns->href[0] != 0) || (ns->prefix != NULL)))
@@ -2010,7 +2012,7 @@ xmlSAX2AttributeNs(xmlParserCtxtPtr ctxt,
 	else
 	    ret->name = xmlStrdup(localname);
 
-        /* link at the end to preserv order, TODO speed up with a last */
+        /* link at the end to preserve order, TODO speed up with a last */
 	if (ctxt->node->properties == NULL) {
 	    ctxt->node->properties = ret;
 	} else {
@@ -2102,7 +2104,7 @@ xmlSAX2AttributeNs(xmlParserCtxtPtr ctxt,
 	    } else {
 	        /*
 		 * dup now contains a string of the flattened attribute
-		 * content with entities substitued. Check if we need to
+		 * content with entities substituted. Check if we need to
 		 * apply an extra layer of normalization.
 		 * It need to be done twice ... it's an extra burden related
 		 * to the ability to keep references in attributes
@@ -2135,7 +2137,7 @@ xmlSAX2AttributeNs(xmlParserCtxtPtr ctxt,
 	    }
 	} else {
 	    /*
-	     * if entities already have been substitued, then
+	     * if entities already have been substituted, then
 	     * the attribute as passed is already normalized
 	     */
 	    dup = xmlStrndup(value, valueend - value);
@@ -2398,7 +2400,7 @@ xmlSAX2StartElementNs(void *ctx,
     if (nb_attributes > 0) {
         for (j = 0,i = 0;i < nb_attributes;i++,j+=5) {
 	    /*
-	     * Handle the rare case of an undefined atribute prefix
+	     * Handle the rare case of an undefined attribute prefix
 	     */
 	    if ((attributes[j+1] != NULL) && (attributes[j+2] == NULL)) {
 		if (ctxt->dictNames) {
@@ -2584,7 +2586,7 @@ xmlSAX2Characters(void *ctx, const xmlChar *ch, int len)
 	     * The whole point of maintaining nodelen and nodemem,
 	     * xmlTextConcat is too costly, i.e. compute length,
 	     * reallocate a new buffer, move data, append ch. Here
-	     * We try to minimaze realloc() uses and avoid copying
+	     * We try to minimize realloc() uses and avoid copying
 	     * and recomputing length over and over.
 	     */
 	    if (lastChild->content == (xmlChar *)&(lastChild->properties)) {
diff --git a/buf.c b/buf.c
index 21cb9d80477..d46da365142 100644
--- a/buf.c
+++ b/buf.c
@@ -1,7 +1,7 @@
 /*
  * buf.c: memory buffers for libxml2
  *
- * new buffer structures and entry points to simplify the maintainance
+ * new buffer structures and entry points to simplify the maintenance
  * of libxml2 and ensure we keep good control over memory allocations
  * and stay 64 bits clean.
  * The new entry point use the xmlBufPtr opaque structure and
@@ -396,7 +396,7 @@ xmlBufShrink(xmlBufPtr buf, size_t len) {
         ((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
+	 * the perceived buffer size has shrunk accordingly
 	 */
         buf->content += len;
 	buf->size -= len;
@@ -958,7 +958,7 @@ xmlBufAddHead(xmlBufPtr buf, const xmlChar *str, int len) {
 
 	if (start_buf > (unsigned int) len) {
 	    /*
-	     * We can add it in the space previously shrinked
+	     * We can add it in the space previously shrunk
 	     */
 	    buf->content -= len;
             memmove(&buf->content[0], str, len);
@@ -1204,10 +1204,10 @@ xmlBufferPtr
 xmlBufBackToBuffer(xmlBufPtr buf) {
     xmlBufferPtr ret;
 
-    if ((buf == NULL) || (buf->error))
+    if (buf == NULL)
         return(NULL);
     CHECK_COMPAT(buf)
-    if (buf->buffer == NULL) {
+    if ((buf->error) || (buf->buffer == NULL)) {
         xmlBufFree(buf);
         return(NULL);
     }
@@ -1307,7 +1307,7 @@ xmlBufGetInputBase(xmlBufPtr buf, xmlParserInputPtr input) {
     CHECK_COMPAT(buf)
     base = input->base - buf->content;
     /*
-     * We could do some pointer arythmetic checks but that's probably
+     * We could do some pointer arithmetic checks but that's probably
      * sufficient.
      */
     if (base > buf->size) {
diff --git a/c14n.c b/c14n.c
index d80ae8b7a82..5b3fbe70c6c 100644
--- a/c14n.c
+++ b/c14n.c
@@ -43,7 +43,7 @@ typedef enum {
 
 typedef struct _xmlC14NVisibleNsStack {
     int nsCurEnd;           /* number of nodes in the set */
-    int nsPrevStart;        /* the begginning of the stack for previous visible node */
+    int nsPrevStart;        /* the beginning of the stack for previous visible node */
     int nsPrevEnd;          /* the end of the stack for previous visible node */
     int nsMax;              /* size of the array as allocated */
     xmlNsPtr	*nsTab;	    /* array of ns in no particular order */
@@ -226,7 +226,7 @@ xmlC14NErrRelativeNamespace(const char *ns_uri)
  * xmlC14NErr:
  * @ctxt:  a C14N evaluation context
  * @node:  the context node
- * @error:  the erorr code
+ * @error:  the error code
  * @msg:  the message
  * @extra:  extra informations
  *
@@ -1827,7 +1827,7 @@ xmlC14NNewCtx(xmlDocPtr doc,
     }
 
     /*
-     * Set "mode" flag and remember list of incluseve prefixes
+     * Set "mode" flag and remember list of inclusive prefixes
      * for exclusive c14n
      */
     ctx->mode = mode;
@@ -2039,7 +2039,7 @@ xmlC14NDocDumpMemory(xmlDocPtr doc, xmlNodeSetPtr nodes,
     (void) xmlOutputBufferClose(buf);
 
     if ((*doc_txt_ptr == NULL) && (ret > 0)) {
-        xmlC14NErrMemory("coping canonicanized document");
+        xmlC14NErrMemory("coping canonicalized document");
         return (-1);
     }
     return (ret);
@@ -2057,7 +2057,7 @@ xmlC14NDocDumpMemory(xmlDocPtr doc, xmlNodeSetPtr nodes,
  *			canonicalization, ignored otherwise)
  * @with_comments:	include comments in the result (!=0) or not (==0)
  * @filename:		the filename to store canonical XML image
- * @compression:	the compression level (zlib requred):
+ * @compression:	the compression level (zlib required):
  *				-1 - libxml default,
  *				 0 - uncompressed,
  *				>0 - compression level
@@ -2100,7 +2100,7 @@ xmlC14NDocSave(xmlDocPtr doc, xmlNodeSetPtr nodes,
     ret = xmlC14NDocSaveTo(doc, nodes, mode, inclusive_ns_prefixes,
                            with_comments, buf);
     if (ret < 0) {
-        xmlC14NErrInternal("cannicanize document to buffer");
+        xmlC14NErrInternal("canonize document to buffer");
         (void) xmlOutputBufferClose(buf);
         return (-1);
     }
diff --git a/catalog.c b/catalog.c
index f814121ce82..7328fd319c0 100644
--- a/catalog.c
+++ b/catalog.c
@@ -56,7 +56,7 @@
  * TODO:
  *
  * macro to flag unimplemented blocks
- * XML_CATALOG_PREFER user env to select between system/public prefered
+ * XML_CATALOG_PREFER user env to select between system/public preferred
  * option. C.f. Richard Tobin <richard@cogsci.ed.ac.uk>
  *> Just FYI, I am using an environment variable XML_CATALOG_PREFER with
  *> values "system" and "public".  I have made the default be "system" to
diff --git a/debugXML.c b/debugXML.c
index c98db0bcc77..d855555861d 100644
--- a/debugXML.c
+++ b/debugXML.c
@@ -289,7 +289,7 @@ xmlCtxtGenericNodeCheck(xmlDebugCtxtPtr ctxt, xmlNodePtr node) {
 	dict = doc->dict;
 	if ((dict == NULL) && (ctxt->nodict == 0)) {
 #if 0
-            /* desactivated right now as it raises too many errors */
+            /* deactivated right now as it raises too many errors */
 	    if (doc->type == XML_DOCUMENT_NODE)
 		xmlDebugErr(ctxt, XML_CHECK_NO_DICT,
 			    "Document has no dictionary\n");
@@ -1168,7 +1168,7 @@ xmlCtxtDumpDocHead(xmlDebugCtxtPtr ctxt, xmlDocPtr doc)
  * @output:  the FILE * for the output
  * @doc:  the document
  *
- * Dumps debug information cncerning the document, not recursive
+ * Dumps debug information concerning the document, not recursive
  */
 static void
 xmlCtxtDumpDocumentHead(xmlDebugCtxtPtr ctxt, xmlDocPtr doc)
@@ -1498,7 +1498,7 @@ xmlDebugDumpNodeList(FILE * output, xmlNodePtr node, int depth)
  * @output:  the FILE * for the output
  * @doc:  the document
  *
- * Dumps debug information cncerning the document, not recursive
+ * Dumps debug information concerning the document, not recursive
  */
 void
 xmlDebugDumpDocumentHead(FILE * output, xmlDocPtr doc)
@@ -2363,10 +2363,7 @@ xmlShellRNGValidate(xmlShellCtxtPtr sctxt, char *schemas,
     int ret;
 
     ctxt = xmlRelaxNGNewParserCtxt(schemas);
-    xmlRelaxNGSetParserErrors(ctxt,
-	    (xmlRelaxNGValidityErrorFunc) fprintf,
-	    (xmlRelaxNGValidityWarningFunc) fprintf,
-	    stderr);
+    xmlRelaxNGSetParserErrors(ctxt, xmlGenericError, xmlGenericError, NULL);
     relaxngschemas = xmlRelaxNGParse(ctxt);
     xmlRelaxNGFreeParserCtxt(ctxt);
     if (relaxngschemas == NULL) {
@@ -2375,10 +2372,7 @@ xmlShellRNGValidate(xmlShellCtxtPtr sctxt, char *schemas,
 	return(-1);
     }
     vctxt = xmlRelaxNGNewValidCtxt(relaxngschemas);
-    xmlRelaxNGSetValidErrors(vctxt,
-	    (xmlRelaxNGValidityErrorFunc) fprintf,
-	    (xmlRelaxNGValidityWarningFunc) fprintf,
-	    stderr);
+    xmlRelaxNGSetValidErrors(vctxt, xmlGenericError, xmlGenericError, NULL);
     ret = xmlRelaxNGValidateDoc(vctxt, sctxt->doc);
     if (ret == 0) {
 	fprintf(stderr, "%s validates\n", sctxt->filename);
@@ -2647,9 +2641,9 @@ xmlShellValidate(xmlShellCtxtPtr ctxt, char *dtd,
     int res = -1;
 
     if ((ctxt == NULL) || (ctxt->doc == NULL)) return(-1);
-    vctxt.userData = stderr;
-    vctxt.error = (xmlValidityErrorFunc) fprintf;
-    vctxt.warning = (xmlValidityWarningFunc) fprintf;
+    vctxt.userData = NULL;
+    vctxt.error = xmlGenericError;
+    vctxt.warning = xmlGenericError;
 
     if ((dtd == NULL) || (dtd[0] == 0)) {
         res = xmlValidateDocument(&vctxt, ctxt->doc);
diff --git a/dict.c b/dict.c
index 0ef3718da28..336e046aecf 100644
--- a/dict.c
+++ b/dict.c
@@ -38,7 +38,8 @@
  *  list we will use the BigKey algo as soon as the hash size grows
  *  over MIN_DICT_SIZE so this actually works
  */
-#if defined(HAVE_RAND) && defined(HAVE_SRAND) && defined(HAVE_TIME)
+#if defined(HAVE_RAND) && defined(HAVE_SRAND) && defined(HAVE_TIME) && \
+    !defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
 #define DICT_RANDOMIZATION
 #endif
 
@@ -371,6 +372,9 @@ found_pool:
  * http://burtleburtle.net/bob/hash/doobs.html
  */
 
+#ifdef __clang__
+ATTRIBUTE_NO_SANITIZE("unsigned-integer-overflow")
+#endif
 static uint32_t
 xmlDictComputeBigKey(const xmlChar* data, int namelen, int seed) {
     uint32_t hash;
@@ -403,6 +407,9 @@ xmlDictComputeBigKey(const xmlChar* data, int namelen, int seed) {
  *
  * Neither of the two strings must be NULL.
  */
+#ifdef __clang__
+ATTRIBUTE_NO_SANITIZE("unsigned-integer-overflow")
+#endif
 static unsigned long
 xmlDictComputeBigQKey(const xmlChar *prefix, int plen,
                       const xmlChar *name, int len, int seed)
@@ -727,7 +734,7 @@ xmlDictGrow(xmlDictPtr dict, size_t size) {
 		dict->dict[key].next = entry;
 	    } else {
 	        /*
-		 * we don't have much ways to alert from herei
+		 * we don't have much ways to alert from here
 		 * result is losing an entry and unicity guarantee
 		 */
 	        ret = -1;
@@ -1202,7 +1209,7 @@ xmlDictQLookup(xmlDictPtr dict, const xmlChar *prefix, const xmlChar *name) {
  * @dict: the dictionary
  * @str: the string
  *
- * check if a string is owned by the disctionary
+ * check if a string is owned by the dictionary
  *
  * Returns 1 if true, 0 if false and -1 in case of error
  * -1 in case of error
diff --git a/elfgcchack.h b/elfgcchack.h
index 5ac93bfb9f4..af8ad1148d2 100644
--- a/elfgcchack.h
+++ b/elfgcchack.h
@@ -4311,6 +4311,16 @@ extern __typeof (xmlHashCreateDict) xmlHashCreateDict__internal_alias __attribut
 #endif
 #endif
 
+#ifdef bottom_hash
+#undef xmlHashDefaultDeallocator
+extern __typeof (xmlHashDefaultDeallocator) xmlHashDefaultDeallocator __attribute((alias("xmlHashDefaultDeallocator__internal_alias")));
+#else
+#ifndef xmlHashDefaultDeallocator
+extern __typeof (xmlHashDefaultDeallocator) xmlHashDefaultDeallocator__internal_alias __attribute((visibility("hidden")));
+#define xmlHashDefaultDeallocator xmlHashDefaultDeallocator__internal_alias
+#endif
+#endif
+
 #ifdef bottom_hash
 #undef xmlHashFree
 extern __typeof (xmlHashFree) xmlHashFree __attribute((alias("xmlHashFree__internal_alias")));
diff --git a/enc.h b/enc.h
index 057d206df8a..a69a5d03c85 100644
--- a/enc.h
+++ b/enc.h
@@ -1,7 +1,7 @@
 /*
  * Summary: Internal Interfaces for encoding in libxml2
  * Description: this module describes a few interfaces which were
- *              addded along with the API changes in 2.9.0
+ *              added along with the API changes in 2.9.0
  *              those are private routines at this point
  *
  * Copy: See Copyright for the status of this software.
diff --git a/encoding.c b/encoding.c
index a3aaf10ec1b..ad4d8a63a31 100644
--- a/encoding.c
+++ b/encoding.c
@@ -1795,7 +1795,7 @@ xmlFindCharEncodingHandler(const char *name) {
  *
  * The value of @inlen after return is the number of octets consumed
  *     as the return value is positive, else unpredictable.
- * The value of @outlen after return is the number of ocetes consumed.
+ * The value of @outlen after return is the number of octets consumed.
  */
 static int
 xmlIconvWrapper(iconv_t cd, unsigned char *out, int *outlen,
@@ -1863,7 +1863,7 @@ xmlIconvWrapper(iconv_t cd, unsigned char *out, int *outlen,
  *
  * The value of @inlen after return is the number of octets consumed
  *     as the return value is positive, else unpredictable.
- * The value of @outlen after return is the number of ocetes consumed.
+ * The value of @outlen after return is the number of octets consumed.
  */
 static int
 xmlUconvWrapper(uconv_t *cd, int toUnicode, unsigned char *out, int *outlen,
@@ -1972,7 +1972,7 @@ xmlEncOutputChunk(xmlCharEncodingHandler *handler, unsigned char *out,
 
 /**
  * xmlCharEncFirstLineInt:
- * @handler:	char enconding transformation data structure
+ * @handler:	char encoding transformation data structure
  * @out:  an xmlBuffer for the output.
  * @in:  an xmlBuffer for the input
  * @len:  number of bytes to convert for the first line, or -1
@@ -2059,7 +2059,7 @@ xmlCharEncFirstLineInt(xmlCharEncodingHandler *handler, xmlBufferPtr out,
 
 /**
  * xmlCharEncFirstLine:
- * @handler:	char enconding transformation data structure
+ * @handler:	char encoding transformation data structure
  * @out:  an xmlBuffer for the output.
  * @in:  an xmlBuffer for the input
  *
@@ -2546,7 +2546,7 @@ retry:
 
 /**
  * xmlCharEncOutFunc:
- * @handler:	char enconding transformation data structure
+ * @handler:	char encoding transformation data structure
  * @out:  an xmlBuffer for the output.
  * @in:  an xmlBuffer for the input
  *
@@ -2710,7 +2710,7 @@ retry:
 
 /**
  * xmlCharEncCloseFunc:
- * @handler:	char enconding transformation data structure
+ * @handler:	char encoding transformation data structure
  *
  * Generic front-end for encoding handler close function
  *
@@ -2811,7 +2811,7 @@ xmlByteConsumed(xmlParserCtxtPtr ctxt) {
 	xmlCharEncodingHandler * handler = in->buf->encoder;
         /*
 	 * Encoding conversion, compute the number of unused original
-	 * bytes from the input not consumed and substract that from
+	 * bytes from the input not consumed and subtract that from
 	 * the raw consumed value, this is not a cheap operation
 	 */
         if (in->end - in->cur > 0) {
@@ -2860,7 +2860,7 @@ xmlByteConsumed(xmlParserCtxtPtr ctxt) {
  * Returns 0 if success, -2 if the transcoding fails, or -1 otherwise
  * The value of @inlen after return is the number of octets consumed
  *     as the return value is positive, else unpredictable.
- * The value of @outlen after return is the number of ocetes consumed.
+ * The value of @outlen after return is the number of octets consumed.
  */
 static int
 UTF8ToISO8859x(unsigned char* out, int *outlen,
@@ -2976,7 +2976,7 @@ UTF8ToISO8859x(unsigned char* out, int *outlen,
  * block of chars out.
  * Returns 0 if success, or -1 otherwise
  * The value of @inlen after return is the number of octets consumed
- * The value of @outlen after return is the number of ocetes produced.
+ * The value of @outlen after return is the number of octets produced.
  */
 static int
 ISO8859xToUTF8(unsigned char* out, int *outlen,
diff --git a/entities.c b/entities.c
index 43549bc5def..d575e9d177b 100644
--- a/entities.c
+++ b/entities.c
@@ -148,7 +148,7 @@ xmlFreeEntity(xmlEntityPtr entity)
 /*
  * xmlCreateEntity:
  *
- * internal routine doing the entity node strutures allocations
+ * internal routine doing the entity node structures allocations
  */
 static xmlEntityPtr
 xmlCreateEntity(xmlDictPtr dict, const xmlChar *name, int type,
@@ -398,7 +398,7 @@ xmlAddDocEntity(xmlDocPtr doc, const xmlChar *name, int type,
  *
  * 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
+ * unlinked entity structure will be returned, it is then the responsibility
  * of the caller to link it to the document later or free it when not needed
  * anymore.
  *
@@ -548,7 +548,7 @@ xmlGetDocEntity(const xmlDoc *doc, const xmlChar *name) {
  * xmlEncodeEntitiesInternal:
  * @doc:  the document containing the string
  * @input:  A string to convert to XML.
- * @attr: are we handling an atrbute value
+ * @attr: are we handling an attribute value
  *
  * Do a global encoding of a string, replacing the predefined entities
  * and non ASCII values with their entities and CharRef counterparts.
diff --git a/error.c b/error.c
index 50e9e6f8603..b7d5b36bc79 100644
--- a/error.c
+++ b/error.c
@@ -238,7 +238,7 @@ xmlParserPrintFileContext(xmlParserInputPtr input) {
  * @ctx: the parser context or NULL
  * @str: the formatted error message
  *
- * Report an erro with its context, replace the 4 old error/warning
+ * Report an error with its context, replace the 4 old error/warning
  * routines.
  */
 static void
@@ -631,7 +631,7 @@ __xmlRaiseError(xmlStructuredErrorFunc schannel,
 	(channel == xmlParserValidityError) ||
 	(channel == xmlParserValidityWarning))
 	xmlReportError(to, ctxt, str, NULL, NULL);
-    else if ((channel == (xmlGenericErrorFunc) fprintf) ||
+    else if (((void(*)(void)) channel == (void(*)(void)) fprintf) ||
              (channel == xmlGenericErrorDefaultFunc))
 	xmlReportError(to, ctxt, str, channel, data);
     else
diff --git a/globals.c b/globals.c
index 20b430880ab..7bf985f487a 100644
--- a/globals.c
+++ b/globals.c
@@ -107,7 +107,7 @@ xmlMallocFunc xmlMalloc = malloc;
  * @size:  the size requested in bytes
  *
  * The variable holding the libxml malloc() implementation for atomic
- * data (i.e. blocks not containings pointers), useful when using a
+ * data (i.e. blocks not containing pointers), useful when using a
  * garbage collecting allocator.
  *
  * Returns a pointer to the newly allocated block or NULL in case of error
@@ -260,7 +260,7 @@ static int xmlPedanticParserDefaultValueThrDef = 0;
  * Global setting, indicate that the parser should store the line number
  * in the content field of elements in the DOM tree.
  * Disabled by default since this may not be safe for old classes of
- * applicaton.
+ * application.
  */
 int xmlLineNumbersDefaultValue = 0;
 static int xmlLineNumbersDefaultValueThrDef = 0;
@@ -361,7 +361,7 @@ static const char *xmlTreeIndentStringThrDef = "  ";
  * xmlSaveNoEmptyTags:
  *
  * Global setting, asking the serializer to not output empty tags
- * as <empty/> but <empty></empty>. those two forms are undistinguishable
+ * as <empty/> but <empty></empty>. those two forms are indistinguishable
  * once parsed.
  * Disabled by default
  */
diff --git a/hash.c b/hash.c
index b0b4abc92e4..a83d979b64a 100644
--- a/hash.c
+++ b/hash.c
@@ -33,7 +33,8 @@
  * it seems that having hash randomization might be a good idea
  * when using XML with untrusted data
  */
-#if defined(HAVE_RAND) && defined(HAVE_SRAND) && defined(HAVE_TIME)
+#if defined(HAVE_RAND) && defined(HAVE_SRAND) && defined(HAVE_TIME) && \
+    !defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION)
 #define HASH_RANDOMIZATION
 #endif
 
@@ -78,6 +79,9 @@ struct _xmlHashTable {
  * xmlHashComputeKey:
  * Calculate the hash key
  */
+#ifdef __clang__
+ATTRIBUTE_NO_SANITIZE("unsigned-integer-overflow")
+#endif
 static unsigned long
 xmlHashComputeKey(xmlHashTablePtr table, const xmlChar *name,
 	          const xmlChar *name2, const xmlChar *name3) {
@@ -108,6 +112,9 @@ xmlHashComputeKey(xmlHashTablePtr table, const xmlChar *name,
     return (value % table->size);
 }
 
+#ifdef __clang__
+ATTRIBUTE_NO_SANITIZE("unsigned-integer-overflow")
+#endif
 static unsigned long
 xmlHashComputeQKey(xmlHashTablePtr table,
 		   const xmlChar *prefix, const xmlChar *name,
diff --git a/include/libxml/c14n.h b/include/libxml/c14n.h
index b8971d92046..d74847df842 100644
--- a/include/libxml/c14n.h
+++ b/include/libxml/c14n.h
@@ -28,17 +28,17 @@ extern "C" {
 #include <libxml/xpath.h>
 
 /*
- * XML Canonicazation
+ * XML Canonicalization
  * http://www.w3.org/TR/xml-c14n
  *
- * Exclusive XML Canonicazation
+ * Exclusive XML Canonicalization
  * http://www.w3.org/TR/xml-exc-c14n
  *
  * 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
- * following global setings:
+ * In order to achieve this in libxml2 the document MUST be loaded with
+ * following global settings:
  *
  *    xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS;
  *    xmlSubstituteEntitiesDefault(1);
@@ -59,7 +59,7 @@ extern "C" {
  *
  */
 typedef enum {
-    XML_C14N_1_0            = 0,    /* Origianal C14N 1.0 spec */
+    XML_C14N_1_0            = 0,    /* Original C14N 1.0 spec */
     XML_C14N_EXCLUSIVE_1_0  = 1,    /* Exclusive C14N 1.0 spec */
     XML_C14N_1_1            = 2     /* C14N 1.1 spec */
 } xmlC14NMode;
@@ -96,7 +96,7 @@ XMLPUBFUN int XMLCALL
 /**
  * xmlC14NIsVisibleCallback:
  * @user_data: user data
- * @node: the curent node
+ * @node: the current node
  * @parent: the parent node
  *
  * Signature for a C14N callback on visible nodes
diff --git a/include/libxml/catalog.h b/include/libxml/catalog.h
index 5a13f51b6c6..26b178dbbc9 100644
--- a/include/libxml/catalog.h
+++ b/include/libxml/catalog.h
@@ -39,7 +39,7 @@ extern "C" {
 /**
  * XML_CATALOG_PI:
  *
- * The specific XML Catalog Processing Instuction name.
+ * The specific XML Catalog Processing Instruction name.
  */
 #define XML_CATALOG_PI						\
     (const xmlChar *) "oasis-xml-catalog"
diff --git a/include/libxml/dict.h b/include/libxml/dict.h
index b83db59a126..cf54af1f252 100644
--- a/include/libxml/dict.h
+++ b/include/libxml/dict.h
@@ -11,25 +11,18 @@
 #ifndef __XML_DICT_H__
 #define __XML_DICT_H__
 
+#include <stddef.h>
+#include <libxml/xmlversion.h>
+
 #ifdef __cplusplus
-#define __XML_EXTERNC	extern "C"
-#else
-#define __XML_EXTERNC
+extern "C" {
 #endif
 
 /*
  * The dictionary.
  */
-__XML_EXTERNC typedef struct _xmlDict xmlDict;
-__XML_EXTERNC typedef xmlDict *xmlDictPtr;
-
-#include <limits.h>
-#include <libxml/xmlversion.h>
-#include <libxml/tree.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
+typedef struct _xmlDict xmlDict;
+typedef xmlDict *xmlDictPtr;
 
 /*
  * Initializer
diff --git a/include/libxml/hash.h b/include/libxml/hash.h
index 6352874ef26..b682b6b9403 100644
--- a/include/libxml/hash.h
+++ b/include/libxml/hash.h
@@ -80,7 +80,7 @@ typedef void *(*xmlHashCopier)(void *payload, const xmlChar *name);
 /**
  * xmlHashScanner:
  * @payload:  the data in the hash
- * @data:  extra scannner data
+ * @data:  extra scanner data
  * @name:  the name associated
  *
  * Callback when scanning data in a hash with the simple scanner.
@@ -89,7 +89,7 @@ typedef void (*xmlHashScanner)(void *payload, void *data, const xmlChar *name);
 /**
  * xmlHashScannerFull:
  * @payload:  the data in the hash
- * @data:  extra scannner data
+ * @data:  extra scanner data
  * @name:  the name associated
  * @name2:  the second name associated
  * @name3:  the third name associated
diff --git a/include/libxml/parser.h b/include/libxml/parser.h
index 47fbec03f7e..c295554f36a 100644
--- a/include/libxml/parser.h
+++ b/include/libxml/parser.h
@@ -283,11 +283,11 @@ struct _xmlParserCtxt {
     void *            *pushTab;       /* array of data for push */
     xmlHashTablePtr    attsDefault;   /* defaulted attributes if any */
     xmlHashTablePtr    attsSpecial;   /* non-CDATA attributes if any */
-    int                nsWellFormed;  /* is the document XML Nanespace okay */
+    int                nsWellFormed;  /* is the document XML Namespace okay */
     int                options;       /* Extra options */
 
     /*
-     * Those fields are needed only for treaming parsing so far
+     * Those fields are needed only for streaming parsing so far
      */
     int               dictNames;    /* Use dictionary names for the tree */
     int               freeElemsNr;  /* number of freed element nodes */
@@ -1097,7 +1097,7 @@ typedef enum {
     XML_PARSE_PEDANTIC	= 1<<7,	/* pedantic error reporting */
     XML_PARSE_NOBLANKS	= 1<<8,	/* remove blank nodes */
     XML_PARSE_SAX1	= 1<<9,	/* use the SAX1 interface internally */
-    XML_PARSE_XINCLUDE	= 1<<10,/* Implement XInclude substitition  */
+    XML_PARSE_XINCLUDE	= 1<<10,/* Implement XInclude substitution  */
     XML_PARSE_NONET	= 1<<11,/* Forbid network access */
     XML_PARSE_NODICT	= 1<<12,/* Do not reuse the context dictionary */
     XML_PARSE_NSCLEAN	= 1<<13,/* remove redundant namespaces declarations */
@@ -1191,7 +1191,7 @@ XMLPUBFUN xmlDocPtr XMLCALL
 /**
  * xmlFeature:
  *
- * Used to examine the existance of features that can be enabled
+ * Used to examine the existence of features that can be enabled
  * or disabled at compile-time.
  * They used to be called XML_FEATURE_xxx but this clashed with Expat
  */
diff --git a/include/libxml/parserInternals.h b/include/libxml/parserInternals.h
index f30fc6876d6..1f26ce20810 100644
--- a/include/libxml/parserInternals.h
+++ b/include/libxml/parserInternals.h
@@ -43,7 +43,7 @@ XMLPUBVAR unsigned int xmlParserMaxDepth;
 /**
  * XML_MAX_NAME_LENGTH:
  *
- * Maximum size allowed for a markup identitier
+ * Maximum size allowed for a markup identifier.
  * This is not a limitation of the parser but a safety boundary feature,
  * use XML_PARSE_HUGE option to override it.
  * Note that with the use of parsing dictionaries overriding the limit
diff --git a/include/libxml/schemasInternals.h b/include/libxml/schemasInternals.h
index 6fb71139ce9..c521d1c184c 100644
--- a/include/libxml/schemasInternals.h
+++ b/include/libxml/schemasInternals.h
@@ -321,13 +321,13 @@ struct _xmlSchemaWildcard {
 /**
  * XML_SCHEMAS_ATTRGROUP_WILDCARD_BUILDED:
  *
- * The attribute wildcard has been already builded.
+ * The attribute wildcard has been built.
  */
 #define XML_SCHEMAS_ATTRGROUP_WILDCARD_BUILDED 1 << 0
 /**
  * XML_SCHEMAS_ATTRGROUP_GLOBAL:
  *
- * The attribute wildcard has been already builded.
+ * The attribute group has been defined.
  */
 #define XML_SCHEMAS_ATTRGROUP_GLOBAL 1 << 1
 /**
@@ -725,7 +725,7 @@ struct _xmlSchemaType {
 /**
  * XML_SCHEMAS_ELEM_BLOCK_SUBSTITUTION:
  *
- * disallowed substitutions: "substituion"
+ * disallowed substitutions: "substitution"
  */
 #define XML_SCHEMAS_ELEM_BLOCK_SUBSTITUTION        1 << 13
 /**
@@ -789,7 +789,7 @@ struct _xmlSchemaElement {
     xmlRegexpPtr contModel; /* Obsolete for WXS, maybe used for RelaxNG */
     xmlSchemaContentType contentType;
     const xmlChar *refPrefix; /* Deprecated; not used */
-    xmlSchemaValPtr defVal; /* The compiled value contraint. */
+    xmlSchemaValPtr defVal; /* The compiled value constraint. */
     void *idcs; /* The identity-constraint defs */
 };
 
@@ -881,7 +881,7 @@ struct _xmlSchemaNotation {
 /**
  * XML_SCHEMAS_FINAL_DEFAULT_LIST:
  *
- * the cshema has "list" in the set of finalDefault.
+ * the schema has "list" in the set of finalDefault.
  */
 #define XML_SCHEMAS_FINAL_DEFAULT_LIST            1 << 4
 /**
@@ -942,7 +942,7 @@ struct _xmlSchema {
     xmlDictPtr      dict;
     void *includes;     /* the includes, this is opaque for now */
     int preserve;        /* whether to free the document */
-    int counter; /* used to give ononymous components unique names */
+    int counter; /* used to give anonymous components unique names */
     xmlHashTablePtr idcDef; /* All identity-constraint defs. */
     void *volatiles; /* Obsolete */
 };
diff --git a/include/libxml/tree.h b/include/libxml/tree.h
index 626ed6ae384..6cfd73188cf 100644
--- a/include/libxml/tree.h
+++ b/include/libxml/tree.h
@@ -527,7 +527,7 @@ struct _xmlNode {
  * xmlDocProperty
  *
  * Set of properties of the document as found by the parser
- * Some of them are linked to similary named xmlParserOption
+ * Some of them are linked to similarly named xmlParserOption
  */
 typedef enum {
     XML_DOC_WELLFORMED		= 1<<0, /* document is XML well formed */
diff --git a/include/libxml/vtk_libxml2_mangle.h b/include/libxml/vtk_libxml2_mangle.h
index 709317ac0aa..bc2dad319f2 100644
--- a/include/libxml/vtk_libxml2_mangle.h
+++ b/include/libxml/vtk_libxml2_mangle.h
@@ -1,9 +1,55 @@
 #ifndef vtk_libxml2_mangle_h
 #define vtk_libxml2_mangle_h
 
+#define UTF8ToHtml vtklibxml2_UTF8ToHtml
+#define UTF8Toisolat1 vtklibxml2_UTF8Toisolat1
+#define __docbDefaultSAXHandler vtklibxml2___docbDefaultSAXHandler
+#define __htmlDefaultSAXHandler vtklibxml2___htmlDefaultSAXHandler
+#define __htmlParseContent vtklibxml2___htmlParseContent
+#define __oldXMLWDcompatibility vtklibxml2___oldXMLWDcompatibility
+#define __xmlBufferAllocScheme vtklibxml2___xmlBufferAllocScheme
+#define __xmlDefaultBufferSize vtklibxml2___xmlDefaultBufferSize
+#define __xmlDefaultSAXHandler vtklibxml2___xmlDefaultSAXHandler
+#define __xmlDefaultSAXLocator vtklibxml2___xmlDefaultSAXLocator
+#define __xmlDeregisterNodeDefaultValue vtklibxml2___xmlDeregisterNodeDefaultValue
+#define __xmlDoValidityCheckingDefaultValue vtklibxml2___xmlDoValidityCheckingDefaultValue
+#define __xmlErrEncoding vtklibxml2___xmlErrEncoding
+#define __xmlFree vtklibxml2___xmlFree
+#define __xmlGenericError vtklibxml2___xmlGenericError
+#define __xmlGenericErrorContext vtklibxml2___xmlGenericErrorContext
+#define __xmlGetWarningsDefaultValue vtklibxml2___xmlGetWarningsDefaultValue
+#define __xmlGlobalInitMutexDestroy vtklibxml2___xmlGlobalInitMutexDestroy
+#define __xmlGlobalInitMutexLock vtklibxml2___xmlGlobalInitMutexLock
+#define __xmlGlobalInitMutexUnlock vtklibxml2___xmlGlobalInitMutexUnlock
+#define __xmlIOErr vtklibxml2___xmlIOErr
+#define __xmlIndentTreeOutput vtklibxml2___xmlIndentTreeOutput
+#define __xmlInitializeDict vtklibxml2___xmlInitializeDict
+#define __xmlKeepBlanksDefaultValue vtklibxml2___xmlKeepBlanksDefaultValue
+#define __xmlLastError vtklibxml2___xmlLastError
+#define __xmlLineNumbersDefaultValue vtklibxml2___xmlLineNumbersDefaultValue
+#define __xmlLoadExtDtdDefaultValue vtklibxml2___xmlLoadExtDtdDefaultValue
+#define __xmlLoaderErr vtklibxml2___xmlLoaderErr
+#define __xmlMalloc vtklibxml2___xmlMalloc
+#define __xmlMallocAtomic vtklibxml2___xmlMallocAtomic
+#define __xmlMemStrdup vtklibxml2___xmlMemStrdup
+#define __xmlOutputBufferCreateFilename vtklibxml2___xmlOutputBufferCreateFilename
+#define __xmlOutputBufferCreateFilenameValue vtklibxml2___xmlOutputBufferCreateFilenameValue
+#define __xmlParserDebugEntities vtklibxml2___xmlParserDebugEntities
+#define __xmlParserInputBufferCreateFilename vtklibxml2___xmlParserInputBufferCreateFilename
+#define __xmlParserInputBufferCreateFilenameValue vtklibxml2___xmlParserInputBufferCreateFilenameValue
+#define __xmlParserVersion vtklibxml2___xmlParserVersion
+#define __xmlPedanticParserDefaultValue vtklibxml2___xmlPedanticParserDefaultValue
+#define __xmlRaiseError vtklibxml2___xmlRaiseError
+#define __xmlRealloc vtklibxml2___xmlRealloc
+#define __xmlRegisterNodeDefaultValue vtklibxml2___xmlRegisterNodeDefaultValue
+#define __xmlSaveNoEmptyTags vtklibxml2___xmlSaveNoEmptyTags
+#define __xmlSimpleError vtklibxml2___xmlSimpleError
+#define __xmlStructuredError vtklibxml2___xmlStructuredError
+#define __xmlStructuredErrorContext vtklibxml2___xmlStructuredErrorContext
+#define __xmlSubstituteEntitiesDefaultValue vtklibxml2___xmlSubstituteEntitiesDefaultValue
+#define __xmlTreeIndentString vtklibxml2___xmlTreeIndentString
 #define docbCreateFileParserCtxt vtklibxml2_docbCreateFileParserCtxt
 #define docbCreatePushParserCtxt vtklibxml2_docbCreatePushParserCtxt
-#define __docbDefaultSAXHandler vtklibxml2___docbDefaultSAXHandler
 #define docbDefaultSAXHandlerInit vtklibxml2_docbDefaultSAXHandlerInit
 #define docbEncodeEntities vtklibxml2_docbEncodeEntities
 #define docbFreeParserCtxt vtklibxml2_docbFreeParserCtxt
@@ -25,7 +71,6 @@
 #define htmlCtxtReadMemory vtklibxml2_htmlCtxtReadMemory
 #define htmlCtxtReset vtklibxml2_htmlCtxtReset
 #define htmlCtxtUseOptions vtklibxml2_htmlCtxtUseOptions
-#define __htmlDefaultSAXHandler vtklibxml2___htmlDefaultSAXHandler
 #define htmlDefaultSAXHandlerInit vtklibxml2_htmlDefaultSAXHandlerInit
 #define htmlDocContentDumpFormatOutput vtklibxml2_htmlDocContentDumpFormatOutput
 #define htmlDocContentDumpOutput vtklibxml2_htmlDocContentDumpOutput
@@ -55,7 +100,6 @@
 #define htmlNodeStatus vtklibxml2_htmlNodeStatus
 #define htmlParseCharRef vtklibxml2_htmlParseCharRef
 #define htmlParseChunk vtklibxml2_htmlParseChunk
-#define __htmlParseContent vtklibxml2___htmlParseContent
 #define htmlParseDoc vtklibxml2_htmlParseDoc
 #define htmlParseDocument vtklibxml2_htmlParseDocument
 #define htmlParseElement vtklibxml2_htmlParseElement
@@ -66,11 +110,11 @@
 #define htmlReadFile vtklibxml2_htmlReadFile
 #define htmlReadIO vtklibxml2_htmlReadIO
 #define htmlReadMemory vtklibxml2_htmlReadMemory
+#define htmlSAXParseDoc vtklibxml2_htmlSAXParseDoc
+#define htmlSAXParseFile vtklibxml2_htmlSAXParseFile
 #define htmlSaveFile vtklibxml2_htmlSaveFile
 #define htmlSaveFileEnc vtklibxml2_htmlSaveFileEnc
 #define htmlSaveFileFormat vtklibxml2_htmlSaveFileFormat
-#define htmlSAXParseDoc vtklibxml2_htmlSAXParseDoc
-#define htmlSAXParseFile vtklibxml2_htmlSAXParseFile
 #define htmlSetMetaEncoding vtklibxml2_htmlSetMetaEncoding
 #define htmlTagLookup vtklibxml2_htmlTagLookup
 #define initGenericErrorDefaultFunc vtklibxml2_initGenericErrorDefaultFunc
@@ -83,9 +127,6 @@
 #define namePush vtklibxml2_namePush
 #define nodePop vtklibxml2_nodePop
 #define nodePush vtklibxml2_nodePush
-#define __oldXMLWDcompatibility vtklibxml2___oldXMLWDcompatibility
-#define UTF8ToHtml vtklibxml2_UTF8ToHtml
-#define UTF8Toisolat1 vtklibxml2_UTF8Toisolat1
 #define valuePop vtklibxml2_valuePop
 #define valuePush vtklibxml2_valuePush
 #define xlinkGetDefaultDetect vtklibxml2_xlinkGetDefaultDetect
@@ -121,11 +162,11 @@
 #define xmlAutomataGetInitState vtklibxml2_xmlAutomataGetInitState
 #define xmlAutomataIsDeterminist vtklibxml2_xmlAutomataIsDeterminist
 #define xmlAutomataNewAllTrans vtklibxml2_xmlAutomataNewAllTrans
+#define xmlAutomataNewCountTrans vtklibxml2_xmlAutomataNewCountTrans
+#define xmlAutomataNewCountTrans2 vtklibxml2_xmlAutomataNewCountTrans2
 #define xmlAutomataNewCountedTrans vtklibxml2_xmlAutomataNewCountedTrans
 #define xmlAutomataNewCounter vtklibxml2_xmlAutomataNewCounter
 #define xmlAutomataNewCounterTrans vtklibxml2_xmlAutomataNewCounterTrans
-#define xmlAutomataNewCountTrans vtklibxml2_xmlAutomataNewCountTrans
-#define xmlAutomataNewCountTrans2 vtklibxml2_xmlAutomataNewCountTrans2
 #define xmlAutomataNewEpsilon vtklibxml2_xmlAutomataNewEpsilon
 #define xmlAutomataNewNegTrans vtklibxml2_xmlAutomataNewNegTrans
 #define xmlAutomataNewOnceTrans vtklibxml2_xmlAutomataNewOnceTrans
@@ -141,8 +182,8 @@
 #define xmlBufAttrSerializeTxtContent vtklibxml2_xmlBufAttrSerializeTxtContent
 #define xmlBufAvail vtklibxml2_xmlBufAvail
 #define xmlBufBackToBuffer vtklibxml2_xmlBufBackToBuffer
-#define xmlBufCat vtklibxml2_xmlBufCat
 #define xmlBufCCat vtklibxml2_xmlBufCCat
+#define xmlBufCat vtklibxml2_xmlBufCat
 #define xmlBufContent vtklibxml2_xmlBufContent
 #define xmlBufCreate vtklibxml2_xmlBufCreate
 #define xmlBufCreateSize vtklibxml2_xmlBufCreateSize
@@ -156,27 +197,6 @@
 #define xmlBufEmpty vtklibxml2_xmlBufEmpty
 #define xmlBufEnd vtklibxml2_xmlBufEnd
 #define xmlBufErase vtklibxml2_xmlBufErase
-#define xmlBufferAdd vtklibxml2_xmlBufferAdd
-#define xmlBufferAddHead vtklibxml2_xmlBufferAddHead
-#define __xmlBufferAllocScheme vtklibxml2___xmlBufferAllocScheme
-#define xmlBufferCat vtklibxml2_xmlBufferCat
-#define xmlBufferCCat vtklibxml2_xmlBufferCCat
-#define xmlBufferContent vtklibxml2_xmlBufferContent
-#define xmlBufferCreate vtklibxml2_xmlBufferCreate
-#define xmlBufferCreateSize vtklibxml2_xmlBufferCreateSize
-#define xmlBufferCreateStatic vtklibxml2_xmlBufferCreateStatic
-#define xmlBufferDetach vtklibxml2_xmlBufferDetach
-#define xmlBufferDump vtklibxml2_xmlBufferDump
-#define xmlBufferEmpty vtklibxml2_xmlBufferEmpty
-#define xmlBufferFree vtklibxml2_xmlBufferFree
-#define xmlBufferGrow vtklibxml2_xmlBufferGrow
-#define xmlBufferLength vtklibxml2_xmlBufferLength
-#define xmlBufferResize vtklibxml2_xmlBufferResize
-#define xmlBufferSetAllocationScheme vtklibxml2_xmlBufferSetAllocationScheme
-#define xmlBufferShrink vtklibxml2_xmlBufferShrink
-#define xmlBufferWriteChar vtklibxml2_xmlBufferWriteChar
-#define xmlBufferWriteCHAR vtklibxml2_xmlBufferWriteCHAR
-#define xmlBufferWriteQuotedString vtklibxml2_xmlBufferWriteQuotedString
 #define xmlBufFree vtklibxml2_xmlBufFree
 #define xmlBufFromBuffer vtklibxml2_xmlBufFromBuffer
 #define xmlBufGetAllocationScheme vtklibxml2_xmlBufGetAllocationScheme
@@ -194,9 +214,29 @@
 #define xmlBufSetInputBaseCur vtklibxml2_xmlBufSetInputBaseCur
 #define xmlBufShrink vtklibxml2_xmlBufShrink
 #define xmlBufUse vtklibxml2_xmlBufUse
-#define xmlBufWriteChar vtklibxml2_xmlBufWriteChar
 #define xmlBufWriteCHAR vtklibxml2_xmlBufWriteCHAR
+#define xmlBufWriteChar vtklibxml2_xmlBufWriteChar
 #define xmlBufWriteQuotedString vtklibxml2_xmlBufWriteQuotedString
+#define xmlBufferAdd vtklibxml2_xmlBufferAdd
+#define xmlBufferAddHead vtklibxml2_xmlBufferAddHead
+#define xmlBufferCCat vtklibxml2_xmlBufferCCat
+#define xmlBufferCat vtklibxml2_xmlBufferCat
+#define xmlBufferContent vtklibxml2_xmlBufferContent
+#define xmlBufferCreate vtklibxml2_xmlBufferCreate
+#define xmlBufferCreateSize vtklibxml2_xmlBufferCreateSize
+#define xmlBufferCreateStatic vtklibxml2_xmlBufferCreateStatic
+#define xmlBufferDetach vtklibxml2_xmlBufferDetach
+#define xmlBufferDump vtklibxml2_xmlBufferDump
+#define xmlBufferEmpty vtklibxml2_xmlBufferEmpty
+#define xmlBufferFree vtklibxml2_xmlBufferFree
+#define xmlBufferGrow vtklibxml2_xmlBufferGrow
+#define xmlBufferLength vtklibxml2_xmlBufferLength
+#define xmlBufferResize vtklibxml2_xmlBufferResize
+#define xmlBufferSetAllocationScheme vtklibxml2_xmlBufferSetAllocationScheme
+#define xmlBufferShrink vtklibxml2_xmlBufferShrink
+#define xmlBufferWriteCHAR vtklibxml2_xmlBufferWriteCHAR
+#define xmlBufferWriteChar vtklibxml2_xmlBufferWriteChar
+#define xmlBufferWriteQuotedString vtklibxml2_xmlBufferWriteQuotedString
 #define xmlBuildQName vtklibxml2_xmlBuildQName
 #define xmlBuildRelativeURI vtklibxml2_xmlBuildRelativeURI
 #define xmlBuildURI vtklibxml2_xmlBuildURI
@@ -277,8 +317,8 @@
 #define xmlCreateEntityParserCtxt vtklibxml2_xmlCreateEntityParserCtxt
 #define xmlCreateEnumeration vtklibxml2_xmlCreateEnumeration
 #define xmlCreateFileParserCtxt vtklibxml2_xmlCreateFileParserCtxt
-#define xmlCreateIntSubset vtklibxml2_xmlCreateIntSubset
 #define xmlCreateIOParserCtxt vtklibxml2_xmlCreateIOParserCtxt
+#define xmlCreateIntSubset vtklibxml2_xmlCreateIntSubset
 #define xmlCreateMemoryParserCtxt vtklibxml2_xmlCreateMemoryParserCtxt
 #define xmlCreatePushParserCtxt vtklibxml2_xmlCreatePushParserCtxt
 #define xmlCreateURI vtklibxml2_xmlCreateURI
@@ -294,13 +334,15 @@
 #define xmlCtxtResetPush vtklibxml2_xmlCtxtResetPush
 #define xmlCtxtUseOptions vtklibxml2_xmlCtxtUseOptions
 #define xmlCurrentChar vtklibxml2_xmlCurrentChar
-#define __xmlDefaultBufferSize vtklibxml2___xmlDefaultBufferSize
-#define __xmlDefaultSAXHandler vtklibxml2___xmlDefaultSAXHandler
+#define xmlDOMWrapAdoptNode vtklibxml2_xmlDOMWrapAdoptNode
+#define xmlDOMWrapCloneNode vtklibxml2_xmlDOMWrapCloneNode
+#define xmlDOMWrapFreeCtxt vtklibxml2_xmlDOMWrapFreeCtxt
+#define xmlDOMWrapNewCtxt vtklibxml2_xmlDOMWrapNewCtxt
+#define xmlDOMWrapReconcileNamespaces vtklibxml2_xmlDOMWrapReconcileNamespaces
+#define xmlDOMWrapRemoveNode vtklibxml2_xmlDOMWrapRemoveNode
 #define xmlDefaultSAXHandlerInit vtklibxml2_xmlDefaultSAXHandlerInit
-#define __xmlDefaultSAXLocator vtklibxml2___xmlDefaultSAXLocator
 #define xmlDelEncodingAlias vtklibxml2_xmlDelEncodingAlias
 #define xmlDeregisterNodeDefault vtklibxml2_xmlDeregisterNodeDefault
-#define __xmlDeregisterNodeDefaultValue vtklibxml2___xmlDeregisterNodeDefaultValue
 #define xmlDetectCharEncoding vtklibxml2_xmlDetectCharEncoding
 #define xmlDictCleanup vtklibxml2_xmlDictCleanup
 #define xmlDictCreate vtklibxml2_xmlDictCreate
@@ -324,13 +366,6 @@
 #define xmlDocFormatDump vtklibxml2_xmlDocFormatDump
 #define xmlDocGetRootElement vtklibxml2_xmlDocGetRootElement
 #define xmlDocSetRootElement vtklibxml2_xmlDocSetRootElement
-#define xmlDOMWrapAdoptNode vtklibxml2_xmlDOMWrapAdoptNode
-#define xmlDOMWrapCloneNode vtklibxml2_xmlDOMWrapCloneNode
-#define xmlDOMWrapFreeCtxt vtklibxml2_xmlDOMWrapFreeCtxt
-#define xmlDOMWrapNewCtxt vtklibxml2_xmlDOMWrapNewCtxt
-#define xmlDOMWrapReconcileNamespaces vtklibxml2_xmlDOMWrapReconcileNamespaces
-#define xmlDOMWrapRemoveNode vtklibxml2_xmlDOMWrapRemoveNode
-#define __xmlDoValidityCheckingDefaultValue vtklibxml2___xmlDoValidityCheckingDefaultValue
 #define xmlDumpAttributeDecl vtklibxml2_xmlDumpAttributeDecl
 #define xmlDumpAttributeTable vtklibxml2_xmlDumpAttributeTable
 #define xmlDumpElementDecl vtklibxml2_xmlDumpElementDecl
@@ -343,7 +378,6 @@
 #define xmlEncodeAttributeEntities vtklibxml2_xmlEncodeAttributeEntities
 #define xmlEncodeEntitiesReentrant vtklibxml2_xmlEncodeEntitiesReentrant
 #define xmlEncodeSpecialChars vtklibxml2_xmlEncodeSpecialChars
-#define __xmlErrEncoding vtklibxml2___xmlErrEncoding
 #define xmlErrMemory vtklibxml2_xmlErrMemory
 #define xmlEscapeFormatString vtklibxml2_xmlEscapeFormatString
 #define xmlExpCtxtNbCons vtklibxml2_xmlExpCtxtNbCons
@@ -371,7 +405,6 @@
 #define xmlFileRead vtklibxml2_xmlFileRead
 #define xmlFindCharEncodingHandler vtklibxml2_xmlFindCharEncodingHandler
 #define xmlFirstElementChild vtklibxml2_xmlFirstElementChild
-#define __xmlFree vtklibxml2___xmlFree
 #define xmlFreeAttributeTable vtklibxml2_xmlFreeAttributeTable
 #define xmlFreeAutomata vtklibxml2_xmlFreeAutomata
 #define xmlFreeCatalog vtklibxml2_xmlFreeCatalog
@@ -396,8 +429,8 @@
 #define xmlFreePatternList vtklibxml2_xmlFreePatternList
 #define xmlFreeProp vtklibxml2_xmlFreeProp
 #define xmlFreePropList vtklibxml2_xmlFreePropList
-#define xmlFreeRefTable vtklibxml2_xmlFreeRefTable
 #define xmlFreeRMutex vtklibxml2_xmlFreeRMutex
+#define xmlFreeRefTable vtklibxml2_xmlFreeRefTable
 #define xmlFreeStreamCtxt vtklibxml2_xmlFreeStreamCtxt
 #define xmlFreeTextReader vtklibxml2_xmlFreeTextReader
 #define xmlFreeTextWriter vtklibxml2_xmlFreeTextWriter
@@ -405,8 +438,6 @@
 #define xmlFreeValidCtxt vtklibxml2_xmlFreeValidCtxt
 #define xmlGcMemGet vtklibxml2_xmlGcMemGet
 #define xmlGcMemSetup vtklibxml2_xmlGcMemSetup
-#define __xmlGenericError vtklibxml2___xmlGenericError
-#define __xmlGenericErrorContext vtklibxml2___xmlGenericErrorContext
 #define xmlGenericErrorDefaultFunc vtklibxml2_xmlGenericErrorDefaultFunc
 #define xmlGetBufferAllocationScheme vtklibxml2_xmlGetBufferAllocationScheme
 #define xmlGetCharEncodingHandler vtklibxml2_xmlGetCharEncodingHandler
@@ -428,8 +459,8 @@
 #define xmlGetLastChild vtklibxml2_xmlGetLastChild
 #define xmlGetLastError vtklibxml2_xmlGetLastError
 #define xmlGetLineNo vtklibxml2_xmlGetLineNo
-#define xmlGetNodePath vtklibxml2_xmlGetNodePath
 #define xmlGetNoNsProp vtklibxml2_xmlGetNoNsProp
+#define xmlGetNodePath vtklibxml2_xmlGetNodePath
 #define xmlGetNsList vtklibxml2_xmlGetNsList
 #define xmlGetNsProp vtklibxml2_xmlGetNsProp
 #define xmlGetParameterEntity vtklibxml2_xmlGetParameterEntity
@@ -438,17 +469,16 @@
 #define xmlGetRefs vtklibxml2_xmlGetRefs
 #define xmlGetThreadId vtklibxml2_xmlGetThreadId
 #define xmlGetUTF8Char vtklibxml2_xmlGetUTF8Char
-#define __xmlGetWarningsDefaultValue vtklibxml2___xmlGetWarningsDefaultValue
-#define __xmlGlobalInitMutexDestroy vtklibxml2___xmlGlobalInitMutexDestroy
-#define __xmlGlobalInitMutexLock vtklibxml2___xmlGlobalInitMutexLock
-#define __xmlGlobalInitMutexUnlock vtklibxml2___xmlGlobalInitMutexUnlock
 #define xmlHasFeature vtklibxml2_xmlHasFeature
+#define xmlHasNsProp vtklibxml2_xmlHasNsProp
+#define xmlHasProp vtklibxml2_xmlHasProp
 #define xmlHashAddEntry vtklibxml2_xmlHashAddEntry
 #define xmlHashAddEntry2 vtklibxml2_xmlHashAddEntry2
 #define xmlHashAddEntry3 vtklibxml2_xmlHashAddEntry3
 #define xmlHashCopy vtklibxml2_xmlHashCopy
 #define xmlHashCreate vtklibxml2_xmlHashCreate
 #define xmlHashCreateDict vtklibxml2_xmlHashCreateDict
+#define xmlHashDefaultDeallocator vtklibxml2_xmlHashDefaultDeallocator
 #define xmlHashFree vtklibxml2_xmlHashFree
 #define xmlHashLookup vtklibxml2_xmlHashLookup
 #define xmlHashLookup2 vtklibxml2_xmlHashLookup2
@@ -467,22 +497,18 @@
 #define xmlHashUpdateEntry vtklibxml2_xmlHashUpdateEntry
 #define xmlHashUpdateEntry2 vtklibxml2_xmlHashUpdateEntry2
 #define xmlHashUpdateEntry3 vtklibxml2_xmlHashUpdateEntry3
-#define xmlHasNsProp vtklibxml2_xmlHasNsProp
-#define xmlHasProp vtklibxml2_xmlHasProp
-#define __xmlIndentTreeOutput vtklibxml2___xmlIndentTreeOutput
+#define xmlIOParseDTD vtklibxml2_xmlIOParseDTD
 #define xmlInitCharEncodingHandlers vtklibxml2_xmlInitCharEncodingHandlers
 #define xmlInitGlobals vtklibxml2_xmlInitGlobals
-#define xmlInitializeCatalog vtklibxml2_xmlInitializeCatalog
-#define xmlInitializeDict vtklibxml2_xmlInitializeDict
-#define __xmlInitializeDict vtklibxml2___xmlInitializeDict
-#define xmlInitializeGlobalState vtklibxml2_xmlInitializeGlobalState
 #define xmlInitMemory vtklibxml2_xmlInitMemory
 #define xmlInitNodeInfoSeq vtklibxml2_xmlInitNodeInfoSeq
 #define xmlInitParser vtklibxml2_xmlInitParser
 #define xmlInitParserCtxt vtklibxml2_xmlInitParserCtxt
 #define xmlInitThreads vtklibxml2_xmlInitThreads
-#define __xmlIOErr vtklibxml2___xmlIOErr
-#define xmlIOParseDTD vtklibxml2_xmlIOParseDTD
+#define xmlInitializeCatalog vtklibxml2_xmlInitializeCatalog
+#define xmlInitializeDict vtklibxml2_xmlInitializeDict
+#define xmlInitializeGlobalState vtklibxml2_xmlInitializeGlobalState
+#define xmlInputReadCallbackNop vtklibxml2_xmlInputReadCallbackNop
 #define xmlIsBaseChar vtklibxml2_xmlIsBaseChar
 #define xmlIsBlank vtklibxml2_xmlIsBlank
 #define xmlIsBlankNode vtklibxml2_xmlIsBlankNode
@@ -499,11 +525,8 @@
 #define xmlIsRef vtklibxml2_xmlIsRef
 #define xmlIsXHTML vtklibxml2_xmlIsXHTML
 #define xmlKeepBlanksDefault vtklibxml2_xmlKeepBlanksDefault
-#define __xmlKeepBlanksDefaultValue vtklibxml2___xmlKeepBlanksDefaultValue
 #define xmlLastElementChild vtklibxml2_xmlLastElementChild
-#define __xmlLastError vtklibxml2___xmlLastError
 #define xmlLineNumbersDefault vtklibxml2_xmlLineNumbersDefault
-#define __xmlLineNumbersDefaultValue vtklibxml2___xmlLineNumbersDefaultValue
 #define xmlLinkGetData vtklibxml2_xmlLinkGetData
 #define xmlListAppend vtklibxml2_xmlListAppend
 #define xmlListClear vtklibxml2_xmlListClear
@@ -533,13 +556,9 @@
 #define xmlLoadACatalog vtklibxml2_xmlLoadACatalog
 #define xmlLoadCatalog vtklibxml2_xmlLoadCatalog
 #define xmlLoadCatalogs vtklibxml2_xmlLoadCatalogs
-#define __xmlLoaderErr vtklibxml2___xmlLoaderErr
-#define __xmlLoadExtDtdDefaultValue vtklibxml2___xmlLoadExtDtdDefaultValue
 #define xmlLoadExternalEntity vtklibxml2_xmlLoadExternalEntity
 #define xmlLoadSGMLSuperCatalog vtklibxml2_xmlLoadSGMLSuperCatalog
 #define xmlLockLibrary vtklibxml2_xmlLockLibrary
-#define __xmlMalloc vtklibxml2___xmlMalloc
-#define __xmlMallocAtomic vtklibxml2___xmlMallocAtomic
 #define xmlMallocAtomicLoc vtklibxml2_xmlMallocAtomicLoc
 #define xmlMallocBreakpoint vtklibxml2_xmlMallocBreakpoint
 #define xmlMallocLoc vtklibxml2_xmlMallocLoc
@@ -549,14 +568,13 @@
 #define xmlMemFree vtklibxml2_xmlMemFree
 #define xmlMemGet vtklibxml2_xmlMemGet
 #define xmlMemMalloc vtklibxml2_xmlMemMalloc
-#define xmlMemoryDump vtklibxml2_xmlMemoryDump
-#define xmlMemoryStrdup vtklibxml2_xmlMemoryStrdup
 #define xmlMemRealloc vtklibxml2_xmlMemRealloc
 #define xmlMemSetup vtklibxml2_xmlMemSetup
 #define xmlMemShow vtklibxml2_xmlMemShow
-#define __xmlMemStrdup vtklibxml2___xmlMemStrdup
 #define xmlMemStrdupLoc vtklibxml2_xmlMemStrdupLoc
 #define xmlMemUsed vtklibxml2_xmlMemUsed
+#define xmlMemoryDump vtklibxml2_xmlMemoryDump
+#define xmlMemoryStrdup vtklibxml2_xmlMemoryStrdup
 #define xmlModuleClose vtklibxml2_xmlModuleClose
 #define xmlModuleFree vtklibxml2_xmlModuleFree
 #define xmlModuleOpen vtklibxml2_xmlModuleOpen
@@ -564,8 +582,8 @@
 #define xmlMutexLock vtklibxml2_xmlMutexLock
 #define xmlMutexUnlock vtklibxml2_xmlMutexUnlock
 #define xmlNewAutomata vtklibxml2_xmlNewAutomata
-#define xmlNewCatalog vtklibxml2_xmlNewCatalog
 #define xmlNewCDataBlock vtklibxml2_xmlNewCDataBlock
+#define xmlNewCatalog vtklibxml2_xmlNewCatalog
 #define xmlNewCharEncodingHandler vtklibxml2_xmlNewCharEncodingHandler
 #define xmlNewCharRef vtklibxml2_xmlNewCharRef
 #define xmlNewChild vtklibxml2_xmlNewChild
@@ -585,20 +603,20 @@
 #define xmlNewElementContent vtklibxml2_xmlNewElementContent
 #define xmlNewEntity vtklibxml2_xmlNewEntity
 #define xmlNewEntityInputStream vtklibxml2_xmlNewEntityInputStream
+#define xmlNewIOInputStream vtklibxml2_xmlNewIOInputStream
 #define xmlNewInputFromFile vtklibxml2_xmlNewInputFromFile
 #define xmlNewInputStream vtklibxml2_xmlNewInputStream
-#define xmlNewIOInputStream vtklibxml2_xmlNewIOInputStream
 #define xmlNewMutex vtklibxml2_xmlNewMutex
 #define xmlNewNode vtklibxml2_xmlNewNode
 #define xmlNewNodeEatName vtklibxml2_xmlNewNodeEatName
 #define xmlNewNs vtklibxml2_xmlNewNs
 #define xmlNewNsProp vtklibxml2_xmlNewNsProp
 #define xmlNewNsPropEatName vtklibxml2_xmlNewNsPropEatName
-#define xmlNewParserCtxt vtklibxml2_xmlNewParserCtxt
 #define xmlNewPI vtklibxml2_xmlNewPI
+#define xmlNewParserCtxt vtklibxml2_xmlNewParserCtxt
 #define xmlNewProp vtklibxml2_xmlNewProp
-#define xmlNewReference vtklibxml2_xmlNewReference
 #define xmlNewRMutex vtklibxml2_xmlNewRMutex
+#define xmlNewReference vtklibxml2_xmlNewReference
 #define xmlNewStringInputStream vtklibxml2_xmlNewStringInputStream
 #define xmlNewText vtklibxml2_xmlNewText
 #define xmlNewTextChild vtklibxml2_xmlNewTextChild
@@ -614,6 +632,7 @@
 #define xmlNewValidCtxt vtklibxml2_xmlNewValidCtxt
 #define xmlNextChar vtklibxml2_xmlNextChar
 #define xmlNextElementSibling vtklibxml2_xmlNextElementSibling
+#define xmlNoNetExternalEntityLoader vtklibxml2_xmlNoNetExternalEntityLoader
 #define xmlNodeAddContent vtklibxml2_xmlNodeAddContent
 #define xmlNodeAddContentLen vtklibxml2_xmlNodeAddContentLen
 #define xmlNodeBufGetContent vtklibxml2_xmlNodeBufGetContent
@@ -632,7 +651,6 @@
 #define xmlNodeSetLang vtklibxml2_xmlNodeSetLang
 #define xmlNodeSetName vtklibxml2_xmlNodeSetName
 #define xmlNodeSetSpacePreserve vtklibxml2_xmlNodeSetSpacePreserve
-#define xmlNoNetExternalEntityLoader vtklibxml2_xmlNoNetExternalEntityLoader
 #define xmlNop vtklibxml2_xmlNop
 #define xmlNormalizeURIPath vtklibxml2_xmlNormalizeURIPath
 #define xmlNormalizeWindowsPath vtklibxml2_xmlNormalizeWindowsPath
@@ -642,9 +660,7 @@
 #define xmlOutputBufferCreateFd vtklibxml2_xmlOutputBufferCreateFd
 #define xmlOutputBufferCreateFile vtklibxml2_xmlOutputBufferCreateFile
 #define xmlOutputBufferCreateFilename vtklibxml2_xmlOutputBufferCreateFilename
-#define __xmlOutputBufferCreateFilename vtklibxml2___xmlOutputBufferCreateFilename
 #define xmlOutputBufferCreateFilenameDefault vtklibxml2_xmlOutputBufferCreateFilenameDefault
-#define __xmlOutputBufferCreateFilenameValue vtklibxml2___xmlOutputBufferCreateFilenameValue
 #define xmlOutputBufferCreateIO vtklibxml2_xmlOutputBufferCreateIO
 #define xmlOutputBufferFlush vtklibxml2_xmlOutputBufferFlush
 #define xmlOutputBufferGetContent vtklibxml2_xmlOutputBufferGetContent
@@ -652,14 +668,14 @@
 #define xmlOutputBufferWrite vtklibxml2_xmlOutputBufferWrite
 #define xmlOutputBufferWriteEscape vtklibxml2_xmlOutputBufferWriteEscape
 #define xmlOutputBufferWriteString vtklibxml2_xmlOutputBufferWriteString
+#define xmlParseAttValue vtklibxml2_xmlParseAttValue
 #define xmlParseAttribute vtklibxml2_xmlParseAttribute
 #define xmlParseAttributeListDecl vtklibxml2_xmlParseAttributeListDecl
 #define xmlParseAttributeType vtklibxml2_xmlParseAttributeType
-#define xmlParseAttValue vtklibxml2_xmlParseAttValue
 #define xmlParseBalancedChunkMemory vtklibxml2_xmlParseBalancedChunkMemory
 #define xmlParseBalancedChunkMemoryRecover vtklibxml2_xmlParseBalancedChunkMemoryRecover
-#define xmlParseCatalogFile vtklibxml2_xmlParseCatalogFile
 #define xmlParseCDSect vtklibxml2_xmlParseCDSect
+#define xmlParseCatalogFile vtklibxml2_xmlParseCatalogFile
 #define xmlParseCharData vtklibxml2_xmlParseCharData
 #define xmlParseCharEncoding vtklibxml2_xmlParseCharEncoding
 #define xmlParseCharRef vtklibxml2_xmlParseCharRef
@@ -667,11 +683,11 @@
 #define xmlParseComment vtklibxml2_xmlParseComment
 #define xmlParseContent vtklibxml2_xmlParseContent
 #define xmlParseCtxtExternalEntity vtklibxml2_xmlParseCtxtExternalEntity
+#define xmlParseDTD vtklibxml2_xmlParseDTD
 #define xmlParseDefaultDecl vtklibxml2_xmlParseDefaultDecl
 #define xmlParseDoc vtklibxml2_xmlParseDoc
 #define xmlParseDocTypeDecl vtklibxml2_xmlParseDocTypeDecl
 #define xmlParseDocument vtklibxml2_xmlParseDocument
-#define xmlParseDTD vtklibxml2_xmlParseDTD
 #define xmlParseElement vtklibxml2_xmlParseElement
 #define xmlParseElementChildrenContentDecl vtklibxml2_xmlParseElementChildrenContentDecl
 #define xmlParseElementContentDecl vtklibxml2_xmlParseElementContentDecl
@@ -686,10 +702,10 @@
 #define xmlParseEntityValue vtklibxml2_xmlParseEntityValue
 #define xmlParseEnumeratedType vtklibxml2_xmlParseEnumeratedType
 #define xmlParseEnumerationType vtklibxml2_xmlParseEnumerationType
+#define xmlParseExtParsedEnt vtklibxml2_xmlParseExtParsedEnt
 #define xmlParseExternalEntity vtklibxml2_xmlParseExternalEntity
 #define xmlParseExternalID vtklibxml2_xmlParseExternalID
 #define xmlParseExternalSubset vtklibxml2_xmlParseExternalSubset
-#define xmlParseExtParsedEnt vtklibxml2_xmlParseExtParsedEnt
 #define xmlParseFile vtklibxml2_xmlParseFile
 #define xmlParseInNodeContext vtklibxml2_xmlParseInNodeContext
 #define xmlParseMarkupDecl vtklibxml2_xmlParseMarkupDecl
@@ -703,9 +719,18 @@
 #define xmlParsePI vtklibxml2_xmlParsePI
 #define xmlParsePITarget vtklibxml2_xmlParsePITarget
 #define xmlParsePubidLiteral vtklibxml2_xmlParsePubidLiteral
-#define xmlParserAddNodeInfo vtklibxml2_xmlParserAddNodeInfo
-#define __xmlParserDebugEntities vtklibxml2___xmlParserDebugEntities
 #define xmlParseReference vtklibxml2_xmlParseReference
+#define xmlParseSDDecl vtklibxml2_xmlParseSDDecl
+#define xmlParseStartTag vtklibxml2_xmlParseStartTag
+#define xmlParseSystemLiteral vtklibxml2_xmlParseSystemLiteral
+#define xmlParseTextDecl vtklibxml2_xmlParseTextDecl
+#define xmlParseURI vtklibxml2_xmlParseURI
+#define xmlParseURIRaw vtklibxml2_xmlParseURIRaw
+#define xmlParseURIReference vtklibxml2_xmlParseURIReference
+#define xmlParseVersionInfo vtklibxml2_xmlParseVersionInfo
+#define xmlParseVersionNum vtklibxml2_xmlParseVersionNum
+#define xmlParseXMLDecl vtklibxml2_xmlParseXMLDecl
+#define xmlParserAddNodeInfo vtklibxml2_xmlParserAddNodeInfo
 #define xmlParserError vtklibxml2_xmlParserError
 #define xmlParserFindNodeInfo vtklibxml2_xmlParserFindNodeInfo
 #define xmlParserFindNodeInfoIndex vtklibxml2_xmlParserFindNodeInfoIndex
@@ -714,9 +739,7 @@
 #define xmlParserInputBufferCreateFd vtklibxml2_xmlParserInputBufferCreateFd
 #define xmlParserInputBufferCreateFile vtklibxml2_xmlParserInputBufferCreateFile
 #define xmlParserInputBufferCreateFilename vtklibxml2_xmlParserInputBufferCreateFilename
-#define __xmlParserInputBufferCreateFilename vtklibxml2___xmlParserInputBufferCreateFilename
 #define xmlParserInputBufferCreateFilenameDefault vtklibxml2_xmlParserInputBufferCreateFilenameDefault
-#define __xmlParserInputBufferCreateFilenameValue vtklibxml2___xmlParserInputBufferCreateFilenameValue
 #define xmlParserInputBufferCreateIO vtklibxml2_xmlParserInputBufferCreateIO
 #define xmlParserInputBufferCreateMem vtklibxml2_xmlParserInputBufferCreateMem
 #define xmlParserInputBufferCreateStatic vtklibxml2_xmlParserInputBufferCreateStatic
@@ -730,35 +753,28 @@
 #define xmlParserPrintFileInfo vtklibxml2_xmlParserPrintFileInfo
 #define xmlParserValidityError vtklibxml2_xmlParserValidityError
 #define xmlParserValidityWarning vtklibxml2_xmlParserValidityWarning
-#define __xmlParserVersion vtklibxml2___xmlParserVersion
 #define xmlParserWarning vtklibxml2_xmlParserWarning
-#define xmlParseSDDecl vtklibxml2_xmlParseSDDecl
-#define xmlParseStartTag vtklibxml2_xmlParseStartTag
-#define xmlParseSystemLiteral vtklibxml2_xmlParseSystemLiteral
-#define xmlParseTextDecl vtklibxml2_xmlParseTextDecl
-#define xmlParseURI vtklibxml2_xmlParseURI
-#define xmlParseURIRaw vtklibxml2_xmlParseURIRaw
-#define xmlParseURIReference vtklibxml2_xmlParseURIReference
-#define xmlParseVersionInfo vtklibxml2_xmlParseVersionInfo
-#define xmlParseVersionNum vtklibxml2_xmlParseVersionNum
-#define xmlParseXMLDecl vtklibxml2_xmlParseXMLDecl
 #define xmlPathToURI vtklibxml2_xmlPathToURI
-#define xmlPatterncompile vtklibxml2_xmlPatterncompile
 #define xmlPatternFromRoot vtklibxml2_xmlPatternFromRoot
 #define xmlPatternGetStreamCtxt vtklibxml2_xmlPatternGetStreamCtxt
 #define xmlPatternMatch vtklibxml2_xmlPatternMatch
 #define xmlPatternMaxDepth vtklibxml2_xmlPatternMaxDepth
 #define xmlPatternMinDepth vtklibxml2_xmlPatternMinDepth
 #define xmlPatternStreamable vtklibxml2_xmlPatternStreamable
+#define xmlPatterncompile vtklibxml2_xmlPatterncompile
 #define xmlPedanticParserDefault vtklibxml2_xmlPedanticParserDefault
-#define __xmlPedanticParserDefaultValue vtklibxml2___xmlPedanticParserDefaultValue
 #define xmlPopInput vtklibxml2_xmlPopInput
 #define xmlPopInputCallbacks vtklibxml2_xmlPopInputCallbacks
 #define xmlPreviousElementSibling vtklibxml2_xmlPreviousElementSibling
 #define xmlPrintURI vtklibxml2_xmlPrintURI
 #define xmlPushInput vtklibxml2_xmlPushInput
-#define __xmlRaiseError vtklibxml2___xmlRaiseError
+#define xmlRMutexLock vtklibxml2_xmlRMutexLock
+#define xmlRMutexUnlock vtklibxml2_xmlRMutexUnlock
 #define xmlReadDoc vtklibxml2_xmlReadDoc
+#define xmlReadFd vtklibxml2_xmlReadFd
+#define xmlReadFile vtklibxml2_xmlReadFile
+#define xmlReadIO vtklibxml2_xmlReadIO
+#define xmlReadMemory vtklibxml2_xmlReadMemory
 #define xmlReaderForDoc vtklibxml2_xmlReaderForDoc
 #define xmlReaderForFd vtklibxml2_xmlReaderForFd
 #define xmlReaderForFile vtklibxml2_xmlReaderForFile
@@ -771,11 +787,6 @@
 #define xmlReaderNewMemory vtklibxml2_xmlReaderNewMemory
 #define xmlReaderNewWalker vtklibxml2_xmlReaderNewWalker
 #define xmlReaderWalker vtklibxml2_xmlReaderWalker
-#define xmlReadFd vtklibxml2_xmlReadFd
-#define xmlReadFile vtklibxml2_xmlReadFile
-#define xmlReadIO vtklibxml2_xmlReadIO
-#define xmlReadMemory vtklibxml2_xmlReadMemory
-#define __xmlRealloc vtklibxml2___xmlRealloc
 #define xmlReallocLoc vtklibxml2_xmlReallocLoc
 #define xmlReconciliateNs vtklibxml2_xmlReconciliateNs
 #define xmlRecoverDoc vtklibxml2_xmlRecoverDoc
@@ -785,20 +796,19 @@
 #define xmlRegExecNextValues vtklibxml2_xmlRegExecNextValues
 #define xmlRegExecPushString vtklibxml2_xmlRegExecPushString
 #define xmlRegExecPushString2 vtklibxml2_xmlRegExecPushString2
+#define xmlRegFreeExecCtxt vtklibxml2_xmlRegFreeExecCtxt
+#define xmlRegFreeRegexp vtklibxml2_xmlRegFreeRegexp
+#define xmlRegNewExecCtxt vtklibxml2_xmlRegNewExecCtxt
 #define xmlRegexpCompile vtklibxml2_xmlRegexpCompile
 #define xmlRegexpExec vtklibxml2_xmlRegexpExec
 #define xmlRegexpIsDeterminist vtklibxml2_xmlRegexpIsDeterminist
 #define xmlRegexpPrint vtklibxml2_xmlRegexpPrint
-#define xmlRegFreeExecCtxt vtklibxml2_xmlRegFreeExecCtxt
-#define xmlRegFreeRegexp vtklibxml2_xmlRegFreeRegexp
 #define xmlRegisterCharEncodingHandler vtklibxml2_xmlRegisterCharEncodingHandler
 #define xmlRegisterDefaultInputCallbacks vtklibxml2_xmlRegisterDefaultInputCallbacks
 #define xmlRegisterDefaultOutputCallbacks vtklibxml2_xmlRegisterDefaultOutputCallbacks
 #define xmlRegisterInputCallbacks vtklibxml2_xmlRegisterInputCallbacks
 #define xmlRegisterNodeDefault vtklibxml2_xmlRegisterNodeDefault
-#define __xmlRegisterNodeDefaultValue vtklibxml2___xmlRegisterNodeDefaultValue
 #define xmlRegisterOutputCallbacks vtklibxml2_xmlRegisterOutputCallbacks
-#define xmlRegNewExecCtxt vtklibxml2_xmlRegNewExecCtxt
 #define xmlRelaxNGCleanupTypes vtklibxml2_xmlRelaxNGCleanupTypes
 #define xmlRelaxNGDump vtklibxml2_xmlRelaxNGDump
 #define xmlRelaxNGDumpTree vtklibxml2_xmlRelaxNGDumpTree
@@ -829,32 +839,13 @@
 #define xmlReplaceNode vtklibxml2_xmlReplaceNode
 #define xmlResetError vtklibxml2_xmlResetError
 #define xmlResetLastError vtklibxml2_xmlResetLastError
-#define xmlRMutexLock vtklibxml2_xmlRMutexLock
-#define xmlRMutexUnlock vtklibxml2_xmlRMutexUnlock
-#define xmlSaveClose vtklibxml2_xmlSaveClose
-#define xmlSaveDoc vtklibxml2_xmlSaveDoc
-#define xmlSaveFile vtklibxml2_xmlSaveFile
-#define xmlSaveFileEnc vtklibxml2_xmlSaveFileEnc
-#define xmlSaveFileTo vtklibxml2_xmlSaveFileTo
-#define xmlSaveFlush vtklibxml2_xmlSaveFlush
-#define xmlSaveFormatFile vtklibxml2_xmlSaveFormatFile
-#define xmlSaveFormatFileEnc vtklibxml2_xmlSaveFormatFileEnc
-#define xmlSaveFormatFileTo vtklibxml2_xmlSaveFormatFileTo
-#define __xmlSaveNoEmptyTags vtklibxml2___xmlSaveNoEmptyTags
-#define xmlSaveSetAttrEscape vtklibxml2_xmlSaveSetAttrEscape
-#define xmlSaveSetEscape vtklibxml2_xmlSaveSetEscape
-#define xmlSaveToBuffer vtklibxml2_xmlSaveToBuffer
-#define xmlSaveToFd vtklibxml2_xmlSaveToFd
-#define xmlSaveToFilename vtklibxml2_xmlSaveToFilename
-#define xmlSaveToIO vtklibxml2_xmlSaveToIO
-#define xmlSaveTree vtklibxml2_xmlSaveTree
-#define xmlSaveUri vtklibxml2_xmlSaveUri
 #define xmlSAX2AttributeDecl vtklibxml2_xmlSAX2AttributeDecl
 #define xmlSAX2CDataBlock vtklibxml2_xmlSAX2CDataBlock
 #define xmlSAX2Characters vtklibxml2_xmlSAX2Characters
 #define xmlSAX2Comment vtklibxml2_xmlSAX2Comment
 #define xmlSAX2ElementDecl vtklibxml2_xmlSAX2ElementDecl
 #define xmlSAX2EndDocument vtklibxml2_xmlSAX2EndDocument
+#define xmlSAX2EndElement vtklibxml2_xmlSAX2EndElement
 #define xmlSAX2EndElementNs vtklibxml2_xmlSAX2EndElementNs
 #define xmlSAX2EntityDecl vtklibxml2_xmlSAX2EntityDecl
 #define xmlSAX2ExternalSubset vtklibxml2_xmlSAX2ExternalSubset
@@ -878,11 +869,12 @@
 #define xmlSAX2ResolveEntity vtklibxml2_xmlSAX2ResolveEntity
 #define xmlSAX2SetDocumentLocator vtklibxml2_xmlSAX2SetDocumentLocator
 #define xmlSAX2StartDocument vtklibxml2_xmlSAX2StartDocument
+#define xmlSAX2StartElement vtklibxml2_xmlSAX2StartElement
 #define xmlSAX2StartElementNs vtklibxml2_xmlSAX2StartElementNs
 #define xmlSAX2UnparsedEntityDecl vtklibxml2_xmlSAX2UnparsedEntityDecl
 #define xmlSAXDefaultVersion vtklibxml2_xmlSAXDefaultVersion
-#define xmlSAXParseDoc vtklibxml2_xmlSAXParseDoc
 #define xmlSAXParseDTD vtklibxml2_xmlSAXParseDTD
+#define xmlSAXParseDoc vtklibxml2_xmlSAXParseDoc
 #define xmlSAXParseEntity vtklibxml2_xmlSAXParseEntity
 #define xmlSAXParseFile vtklibxml2_xmlSAXParseFile
 #define xmlSAXParseFileWithData vtklibxml2_xmlSAXParseFileWithData
@@ -891,6 +883,23 @@
 #define xmlSAXUserParseFile vtklibxml2_xmlSAXUserParseFile
 #define xmlSAXUserParseMemory vtklibxml2_xmlSAXUserParseMemory
 #define xmlSAXVersion vtklibxml2_xmlSAXVersion
+#define xmlSaveClose vtklibxml2_xmlSaveClose
+#define xmlSaveDoc vtklibxml2_xmlSaveDoc
+#define xmlSaveFile vtklibxml2_xmlSaveFile
+#define xmlSaveFileEnc vtklibxml2_xmlSaveFileEnc
+#define xmlSaveFileTo vtklibxml2_xmlSaveFileTo
+#define xmlSaveFlush vtklibxml2_xmlSaveFlush
+#define xmlSaveFormatFile vtklibxml2_xmlSaveFormatFile
+#define xmlSaveFormatFileEnc vtklibxml2_xmlSaveFormatFileEnc
+#define xmlSaveFormatFileTo vtklibxml2_xmlSaveFormatFileTo
+#define xmlSaveSetAttrEscape vtklibxml2_xmlSaveSetAttrEscape
+#define xmlSaveSetEscape vtklibxml2_xmlSaveSetEscape
+#define xmlSaveToBuffer vtklibxml2_xmlSaveToBuffer
+#define xmlSaveToFd vtklibxml2_xmlSaveToFd
+#define xmlSaveToFilename vtklibxml2_xmlSaveToFilename
+#define xmlSaveToIO vtklibxml2_xmlSaveToIO
+#define xmlSaveTree vtklibxml2_xmlSaveTree
+#define xmlSaveUri vtklibxml2_xmlSaveUri
 #define xmlSchemaCheckFacet vtklibxml2_xmlSchemaCheckFacet
 #define xmlSchemaCleanupTypes vtklibxml2_xmlSchemaCleanupTypes
 #define xmlSchemaCollapseString vtklibxml2_xmlSchemaCollapseString
@@ -912,8 +921,8 @@
 #define xmlSchemaGetFacetValueAsULong vtklibxml2_xmlSchemaGetFacetValueAsULong
 #define xmlSchemaGetParserErrors vtklibxml2_xmlSchemaGetParserErrors
 #define xmlSchemaGetPredefinedType vtklibxml2_xmlSchemaGetPredefinedType
-#define xmlSchemaGetValidErrors vtklibxml2_xmlSchemaGetValidErrors
 #define xmlSchemaGetValType vtklibxml2_xmlSchemaGetValType
+#define xmlSchemaGetValidErrors vtklibxml2_xmlSchemaGetValidErrors
 #define xmlSchemaInitTypes vtklibxml2_xmlSchemaInitTypes
 #define xmlSchemaIsBuiltInTypeFacet vtklibxml2_xmlSchemaIsBuiltInTypeFacet
 #define xmlSchemaIsValid vtklibxml2_xmlSchemaIsValid
@@ -933,16 +942,10 @@
 #define xmlSchemaSetValidErrors vtklibxml2_xmlSchemaSetValidErrors
 #define xmlSchemaSetValidOptions vtklibxml2_xmlSchemaSetValidOptions
 #define xmlSchemaSetValidStructuredErrors vtklibxml2_xmlSchemaSetValidStructuredErrors
-#define xmlSchematronFree vtklibxml2_xmlSchematronFree
-#define xmlSchematronFreeParserCtxt vtklibxml2_xmlSchematronFreeParserCtxt
-#define xmlSchematronFreeValidCtxt vtklibxml2_xmlSchematronFreeValidCtxt
-#define xmlSchematronNewDocParserCtxt vtklibxml2_xmlSchematronNewDocParserCtxt
-#define xmlSchematronNewMemParserCtxt vtklibxml2_xmlSchematronNewMemParserCtxt
-#define xmlSchematronNewParserCtxt vtklibxml2_xmlSchematronNewParserCtxt
-#define xmlSchematronNewValidCtxt vtklibxml2_xmlSchematronNewValidCtxt
-#define xmlSchematronParse vtklibxml2_xmlSchematronParse
-#define xmlSchematronSetValidStructuredErrors vtklibxml2_xmlSchematronSetValidStructuredErrors
-#define xmlSchematronValidateDoc vtklibxml2_xmlSchematronValidateDoc
+#define xmlSchemaValPredefTypeNode vtklibxml2_xmlSchemaValPredefTypeNode
+#define xmlSchemaValPredefTypeNodeNoNorm vtklibxml2_xmlSchemaValPredefTypeNodeNoNorm
+#define xmlSchemaValidCtxtGetOptions vtklibxml2_xmlSchemaValidCtxtGetOptions
+#define xmlSchemaValidCtxtGetParserCtxt vtklibxml2_xmlSchemaValidCtxtGetParserCtxt
 #define xmlSchemaValidateDoc vtklibxml2_xmlSchemaValidateDoc
 #define xmlSchemaValidateFacet vtklibxml2_xmlSchemaValidateFacet
 #define xmlSchemaValidateFacetWhtsp vtklibxml2_xmlSchemaValidateFacetWhtsp
@@ -955,15 +958,21 @@
 #define xmlSchemaValidateSetFilename vtklibxml2_xmlSchemaValidateSetFilename
 #define xmlSchemaValidateSetLocator vtklibxml2_xmlSchemaValidateSetLocator
 #define xmlSchemaValidateStream vtklibxml2_xmlSchemaValidateStream
-#define xmlSchemaValidCtxtGetOptions vtklibxml2_xmlSchemaValidCtxtGetOptions
-#define xmlSchemaValidCtxtGetParserCtxt vtklibxml2_xmlSchemaValidCtxtGetParserCtxt
-#define xmlSchemaValPredefTypeNode vtklibxml2_xmlSchemaValPredefTypeNode
-#define xmlSchemaValPredefTypeNodeNoNorm vtklibxml2_xmlSchemaValPredefTypeNodeNoNorm
 #define xmlSchemaValueAppend vtklibxml2_xmlSchemaValueAppend
 #define xmlSchemaValueGetAsBoolean vtklibxml2_xmlSchemaValueGetAsBoolean
 #define xmlSchemaValueGetAsString vtklibxml2_xmlSchemaValueGetAsString
 #define xmlSchemaValueGetNext vtklibxml2_xmlSchemaValueGetNext
 #define xmlSchemaWhiteSpaceReplace vtklibxml2_xmlSchemaWhiteSpaceReplace
+#define xmlSchematronFree vtklibxml2_xmlSchematronFree
+#define xmlSchematronFreeParserCtxt vtklibxml2_xmlSchematronFreeParserCtxt
+#define xmlSchematronFreeValidCtxt vtklibxml2_xmlSchematronFreeValidCtxt
+#define xmlSchematronNewDocParserCtxt vtklibxml2_xmlSchematronNewDocParserCtxt
+#define xmlSchematronNewMemParserCtxt vtklibxml2_xmlSchematronNewMemParserCtxt
+#define xmlSchematronNewParserCtxt vtklibxml2_xmlSchematronNewParserCtxt
+#define xmlSchematronNewValidCtxt vtklibxml2_xmlSchematronNewValidCtxt
+#define xmlSchematronParse vtklibxml2_xmlSchematronParse
+#define xmlSchematronSetValidStructuredErrors vtklibxml2_xmlSchematronSetValidStructuredErrors
+#define xmlSchematronValidateDoc vtklibxml2_xmlSchematronValidateDoc
 #define xmlSearchNs vtklibxml2_xmlSearchNs
 #define xmlSearchNsByHref vtklibxml2_xmlSearchNsByHref
 #define xmlSetBufferAllocationScheme vtklibxml2_xmlSetBufferAllocationScheme
@@ -978,7 +987,6 @@
 #define xmlSetStructuredErrorFunc vtklibxml2_xmlSetStructuredErrorFunc
 #define xmlSetTreeDoc vtklibxml2_xmlSetTreeDoc
 #define xmlSetupParserForBuffer vtklibxml2_xmlSetupParserForBuffer
-#define __xmlSimpleError vtklibxml2___xmlSimpleError
 #define xmlSkipBlankChars vtklibxml2_xmlSkipBlankChars
 #define xmlSnprintfElementContent vtklibxml2_xmlSnprintfElementContent
 #define xmlSplitQName vtklibxml2_xmlSplitQName
@@ -986,6 +994,10 @@
 #define xmlSplitQName3 vtklibxml2_xmlSplitQName3
 #define xmlSprintfElementContent vtklibxml2_xmlSprintfElementContent
 #define xmlStopParser vtklibxml2_xmlStopParser
+#define xmlStrEqual vtklibxml2_xmlStrEqual
+#define xmlStrPrintf vtklibxml2_xmlStrPrintf
+#define xmlStrQEqual vtklibxml2_xmlStrQEqual
+#define xmlStrVPrintf vtklibxml2_xmlStrVPrintf
 #define xmlStrcasecmp vtklibxml2_xmlStrcasecmp
 #define xmlStrcasestr vtklibxml2_xmlStrcasestr
 #define xmlStrcat vtklibxml2_xmlStrcat
@@ -997,7 +1009,6 @@
 #define xmlStreamPushAttr vtklibxml2_xmlStreamPushAttr
 #define xmlStreamPushNode vtklibxml2_xmlStreamPushNode
 #define xmlStreamWantsAnyNode vtklibxml2_xmlStreamWantsAnyNode
-#define xmlStrEqual vtklibxml2_xmlStrEqual
 #define xmlStringCurrentChar vtklibxml2_xmlStringCurrentChar
 #define xmlStringDecodeEntities vtklibxml2_xmlStringDecodeEntities
 #define xmlStringGetNodeList vtklibxml2_xmlStringGetNodeList
@@ -1009,15 +1020,9 @@
 #define xmlStrncatNew vtklibxml2_xmlStrncatNew
 #define xmlStrncmp vtklibxml2_xmlStrncmp
 #define xmlStrndup vtklibxml2_xmlStrndup
-#define xmlStrPrintf vtklibxml2_xmlStrPrintf
-#define xmlStrQEqual vtklibxml2_xmlStrQEqual
 #define xmlStrstr vtklibxml2_xmlStrstr
 #define xmlStrsub vtklibxml2_xmlStrsub
-#define __xmlStructuredError vtklibxml2___xmlStructuredError
-#define __xmlStructuredErrorContext vtklibxml2___xmlStructuredErrorContext
-#define xmlStrVPrintf vtklibxml2_xmlStrVPrintf
 #define xmlSubstituteEntitiesDefault vtklibxml2_xmlSubstituteEntitiesDefault
-#define __xmlSubstituteEntitiesDefaultValue vtklibxml2___xmlSubstituteEntitiesDefaultValue
 #define xmlSwitchEncoding vtklibxml2_xmlSwitchEncoding
 #define xmlSwitchInputEncoding vtklibxml2_xmlSwitchInputEncoding
 #define xmlSwitchToEncoding vtklibxml2_xmlSwitchToEncoding
@@ -1097,11 +1102,11 @@
 #define xmlTextWriterEndAttribute vtklibxml2_xmlTextWriterEndAttribute
 #define xmlTextWriterEndCDATA vtklibxml2_xmlTextWriterEndCDATA
 #define xmlTextWriterEndComment vtklibxml2_xmlTextWriterEndComment
-#define xmlTextWriterEndDocument vtklibxml2_xmlTextWriterEndDocument
 #define xmlTextWriterEndDTD vtklibxml2_xmlTextWriterEndDTD
 #define xmlTextWriterEndDTDAttlist vtklibxml2_xmlTextWriterEndDTDAttlist
 #define xmlTextWriterEndDTDElement vtklibxml2_xmlTextWriterEndDTDElement
 #define xmlTextWriterEndDTDEntity vtklibxml2_xmlTextWriterEndDTDEntity
+#define xmlTextWriterEndDocument vtklibxml2_xmlTextWriterEndDocument
 #define xmlTextWriterEndElement vtklibxml2_xmlTextWriterEndElement
 #define xmlTextWriterEndPI vtklibxml2_xmlTextWriterEndPI
 #define xmlTextWriterFlush vtklibxml2_xmlTextWriterFlush
@@ -1113,11 +1118,11 @@
 #define xmlTextWriterStartAttributeNS vtklibxml2_xmlTextWriterStartAttributeNS
 #define xmlTextWriterStartCDATA vtklibxml2_xmlTextWriterStartCDATA
 #define xmlTextWriterStartComment vtklibxml2_xmlTextWriterStartComment
-#define xmlTextWriterStartDocument vtklibxml2_xmlTextWriterStartDocument
 #define xmlTextWriterStartDTD vtklibxml2_xmlTextWriterStartDTD
 #define xmlTextWriterStartDTDAttlist vtklibxml2_xmlTextWriterStartDTDAttlist
 #define xmlTextWriterStartDTDElement vtklibxml2_xmlTextWriterStartDTDElement
 #define xmlTextWriterStartDTDEntity vtklibxml2_xmlTextWriterStartDTDEntity
+#define xmlTextWriterStartDocument vtklibxml2_xmlTextWriterStartDocument
 #define xmlTextWriterStartElement vtklibxml2_xmlTextWriterStartElement
 #define xmlTextWriterStartElementNS vtklibxml2_xmlTextWriterStartElementNS
 #define xmlTextWriterStartPI vtklibxml2_xmlTextWriterStartPI
@@ -1186,7 +1191,6 @@
 #define xmlThrDefSetStructuredErrorFunc vtklibxml2_xmlThrDefSetStructuredErrorFunc
 #define xmlThrDefSubstituteEntitiesDefaultValue vtklibxml2_xmlThrDefSubstituteEntitiesDefaultValue
 #define xmlThrDefTreeIndentString vtklibxml2_xmlThrDefTreeIndentString
-#define __xmlTreeIndentString vtklibxml2___xmlTreeIndentString
 #define xmlUCSIsAegeanNumbers vtklibxml2_xmlUCSIsAegeanNumbers
 #define xmlUCSIsAlphabeticPresentationForms vtklibxml2_xmlUCSIsAlphabeticPresentationForms
 #define xmlUCSIsArabic vtklibxml2_xmlUCSIsArabic
@@ -1204,6 +1208,15 @@
 #define xmlUCSIsBraillePatterns vtklibxml2_xmlUCSIsBraillePatterns
 #define xmlUCSIsBuhid vtklibxml2_xmlUCSIsBuhid
 #define xmlUCSIsByzantineMusicalSymbols vtklibxml2_xmlUCSIsByzantineMusicalSymbols
+#define xmlUCSIsCJKCompatibility vtklibxml2_xmlUCSIsCJKCompatibility
+#define xmlUCSIsCJKCompatibilityForms vtklibxml2_xmlUCSIsCJKCompatibilityForms
+#define xmlUCSIsCJKCompatibilityIdeographs vtklibxml2_xmlUCSIsCJKCompatibilityIdeographs
+#define xmlUCSIsCJKCompatibilityIdeographsSupplement vtklibxml2_xmlUCSIsCJKCompatibilityIdeographsSupplement
+#define xmlUCSIsCJKRadicalsSupplement vtklibxml2_xmlUCSIsCJKRadicalsSupplement
+#define xmlUCSIsCJKSymbolsandPunctuation vtklibxml2_xmlUCSIsCJKSymbolsandPunctuation
+#define xmlUCSIsCJKUnifiedIdeographs vtklibxml2_xmlUCSIsCJKUnifiedIdeographs
+#define xmlUCSIsCJKUnifiedIdeographsExtensionA vtklibxml2_xmlUCSIsCJKUnifiedIdeographsExtensionA
+#define xmlUCSIsCJKUnifiedIdeographsExtensionB vtklibxml2_xmlUCSIsCJKUnifiedIdeographsExtensionB
 #define xmlUCSIsCat vtklibxml2_xmlUCSIsCat
 #define xmlUCSIsCatC vtklibxml2_xmlUCSIsCatC
 #define xmlUCSIsCatCc vtklibxml2_xmlUCSIsCatCc
@@ -1242,15 +1255,6 @@
 #define xmlUCSIsCatZp vtklibxml2_xmlUCSIsCatZp
 #define xmlUCSIsCatZs vtklibxml2_xmlUCSIsCatZs
 #define xmlUCSIsCherokee vtklibxml2_xmlUCSIsCherokee
-#define xmlUCSIsCJKCompatibility vtklibxml2_xmlUCSIsCJKCompatibility
-#define xmlUCSIsCJKCompatibilityForms vtklibxml2_xmlUCSIsCJKCompatibilityForms
-#define xmlUCSIsCJKCompatibilityIdeographs vtklibxml2_xmlUCSIsCJKCompatibilityIdeographs
-#define xmlUCSIsCJKCompatibilityIdeographsSupplement vtklibxml2_xmlUCSIsCJKCompatibilityIdeographsSupplement
-#define xmlUCSIsCJKRadicalsSupplement vtklibxml2_xmlUCSIsCJKRadicalsSupplement
-#define xmlUCSIsCJKSymbolsandPunctuation vtklibxml2_xmlUCSIsCJKSymbolsandPunctuation
-#define xmlUCSIsCJKUnifiedIdeographs vtklibxml2_xmlUCSIsCJKUnifiedIdeographs
-#define xmlUCSIsCJKUnifiedIdeographsExtensionA vtklibxml2_xmlUCSIsCJKUnifiedIdeographsExtensionA
-#define xmlUCSIsCJKUnifiedIdeographsExtensionB vtklibxml2_xmlUCSIsCJKUnifiedIdeographsExtensionB
 #define xmlUCSIsCombiningDiacriticalMarks vtklibxml2_xmlUCSIsCombiningDiacriticalMarks
 #define xmlUCSIsCombiningDiacriticalMarksforSymbols vtklibxml2_xmlUCSIsCombiningDiacriticalMarksforSymbols
 #define xmlUCSIsCombiningHalfMarks vtklibxml2_xmlUCSIsCombiningHalfMarks
@@ -1271,8 +1275,8 @@
 #define xmlUCSIsGeorgian vtklibxml2_xmlUCSIsGeorgian
 #define xmlUCSIsGothic vtklibxml2_xmlUCSIsGothic
 #define xmlUCSIsGreek vtklibxml2_xmlUCSIsGreek
-#define xmlUCSIsGreekandCoptic vtklibxml2_xmlUCSIsGreekandCoptic
 #define xmlUCSIsGreekExtended vtklibxml2_xmlUCSIsGreekExtended
+#define xmlUCSIsGreekandCoptic vtklibxml2_xmlUCSIsGreekandCoptic
 #define xmlUCSIsGujarati vtklibxml2_xmlUCSIsGujarati
 #define xmlUCSIsGurmukhi vtklibxml2_xmlUCSIsGurmukhi
 #define xmlUCSIsHalfwidthandFullwidthForms vtklibxml2_xmlUCSIsHalfwidthandFullwidthForms
@@ -1284,8 +1288,8 @@
 #define xmlUCSIsHighPrivateUseSurrogates vtklibxml2_xmlUCSIsHighPrivateUseSurrogates
 #define xmlUCSIsHighSurrogates vtklibxml2_xmlUCSIsHighSurrogates
 #define xmlUCSIsHiragana vtklibxml2_xmlUCSIsHiragana
-#define xmlUCSIsIdeographicDescriptionCharacters vtklibxml2_xmlUCSIsIdeographicDescriptionCharacters
 #define xmlUCSIsIPAExtensions vtklibxml2_xmlUCSIsIPAExtensions
+#define xmlUCSIsIdeographicDescriptionCharacters vtklibxml2_xmlUCSIsIdeographicDescriptionCharacters
 #define xmlUCSIsKanbun vtklibxml2_xmlUCSIsKanbun
 #define xmlUCSIsKangxiRadicals vtklibxml2_xmlUCSIsKangxiRadicals
 #define xmlUCSIsKannada vtklibxml2_xmlUCSIsKannada
@@ -1350,13 +1354,9 @@
 #define xmlUCSIsUnifiedCanadianAboriginalSyllabics vtklibxml2_xmlUCSIsUnifiedCanadianAboriginalSyllabics
 #define xmlUCSIsVariationSelectors vtklibxml2_xmlUCSIsVariationSelectors
 #define xmlUCSIsVariationSelectorsSupplement vtklibxml2_xmlUCSIsVariationSelectorsSupplement
-#define xmlUCSIsYijingHexagramSymbols vtklibxml2_xmlUCSIsYijingHexagramSymbols
 #define xmlUCSIsYiRadicals vtklibxml2_xmlUCSIsYiRadicals
 #define xmlUCSIsYiSyllables vtklibxml2_xmlUCSIsYiSyllables
-#define xmlUnlinkNode vtklibxml2_xmlUnlinkNode
-#define xmlUnlockLibrary vtklibxml2_xmlUnlockLibrary
-#define xmlUnsetNsProp vtklibxml2_xmlUnsetNsProp
-#define xmlUnsetProp vtklibxml2_xmlUnsetProp
+#define xmlUCSIsYijingHexagramSymbols vtklibxml2_xmlUCSIsYijingHexagramSymbols
 #define xmlURIEscape vtklibxml2_xmlURIEscape
 #define xmlURIEscapeStr vtklibxml2_xmlURIEscapeStr
 #define xmlURIUnescapeString vtklibxml2_xmlURIUnescapeString
@@ -1368,6 +1368,15 @@
 #define xmlUTF8Strpos vtklibxml2_xmlUTF8Strpos
 #define xmlUTF8Strsize vtklibxml2_xmlUTF8Strsize
 #define xmlUTF8Strsub vtklibxml2_xmlUTF8Strsub
+#define xmlUnlinkNode vtklibxml2_xmlUnlinkNode
+#define xmlUnlockLibrary vtklibxml2_xmlUnlockLibrary
+#define xmlUnsetNsProp vtklibxml2_xmlUnsetNsProp
+#define xmlUnsetProp vtklibxml2_xmlUnsetProp
+#define xmlValidBuildContentModel vtklibxml2_xmlValidBuildContentModel
+#define xmlValidCtxtNormalizeAttributeValue vtklibxml2_xmlValidCtxtNormalizeAttributeValue
+#define xmlValidGetPotentialChildren vtklibxml2_xmlValidGetPotentialChildren
+#define xmlValidGetValidElements vtklibxml2_xmlValidGetValidElements
+#define xmlValidNormalizeAttributeValue vtklibxml2_xmlValidNormalizeAttributeValue
 #define xmlValidateAttributeDecl vtklibxml2_xmlValidateAttributeDecl
 #define xmlValidateAttributeValue vtklibxml2_xmlValidateAttributeValue
 #define xmlValidateDocument vtklibxml2_xmlValidateDocument
@@ -1376,12 +1385,13 @@
 #define xmlValidateDtdFinal vtklibxml2_xmlValidateDtdFinal
 #define xmlValidateElement vtklibxml2_xmlValidateElement
 #define xmlValidateElementDecl vtklibxml2_xmlValidateElementDecl
+#define xmlValidateNCName vtklibxml2_xmlValidateNCName
+#define xmlValidateNMToken vtklibxml2_xmlValidateNMToken
 #define xmlValidateName vtklibxml2_xmlValidateName
-#define xmlValidateNamesValue vtklibxml2_xmlValidateNamesValue
 #define xmlValidateNameValue vtklibxml2_xmlValidateNameValue
-#define xmlValidateNMToken vtklibxml2_xmlValidateNMToken
-#define xmlValidateNmtokensValue vtklibxml2_xmlValidateNmtokensValue
+#define xmlValidateNamesValue vtklibxml2_xmlValidateNamesValue
 #define xmlValidateNmtokenValue vtklibxml2_xmlValidateNmtokenValue
+#define xmlValidateNmtokensValue vtklibxml2_xmlValidateNmtokensValue
 #define xmlValidateNotationDecl vtklibxml2_xmlValidateNotationDecl
 #define xmlValidateNotationUse vtklibxml2_xmlValidateNotationUse
 #define xmlValidateOneAttribute vtklibxml2_xmlValidateOneAttribute
@@ -1392,11 +1402,6 @@
 #define xmlValidatePushElement vtklibxml2_xmlValidatePushElement
 #define xmlValidateQName vtklibxml2_xmlValidateQName
 #define xmlValidateRoot vtklibxml2_xmlValidateRoot
-#define xmlValidBuildContentModel vtklibxml2_xmlValidBuildContentModel
-#define xmlValidCtxtNormalizeAttributeValue vtklibxml2_xmlValidCtxtNormalizeAttributeValue
-#define xmlValidGetPotentialChildren vtklibxml2_xmlValidGetPotentialChildren
-#define xmlValidGetValidElements vtklibxml2_xmlValidGetValidElements
-#define xmlValidNormalizeAttributeValue vtklibxml2_xmlValidNormalizeAttributeValue
 #define xmlXIncludeFreeContext vtklibxml2_xmlXIncludeFreeContext
 #define xmlXIncludeNewContext vtklibxml2_xmlXIncludeNewContext
 #define xmlXIncludeProcess vtklibxml2_xmlXIncludeProcess
@@ -1443,7 +1448,6 @@
 #define xmlXPathDivValues vtklibxml2_xmlXPathDivValues
 #define xmlXPathEqualValues vtklibxml2_xmlXPathEqualValues
 #define xmlXPathErr vtklibxml2_xmlXPathErr
-#define xmlXPatherror vtklibxml2_xmlXPatherror
 #define xmlXPathEval vtklibxml2_xmlXPathEval
 #define xmlXPathEvalExpr vtklibxml2_xmlXPathEvalExpr
 #define xmlXPathEvalExpression vtklibxml2_xmlXPathEvalExpression
@@ -1475,8 +1479,8 @@
 #define xmlXPathMultValues vtklibxml2_xmlXPathMultValues
 #define xmlXPathNamespaceURIFunction vtklibxml2_xmlXPathNamespaceURIFunction
 #define xmlXPathNewBoolean vtklibxml2_xmlXPathNewBoolean
-#define xmlXPathNewContext vtklibxml2_xmlXPathNewContext
 #define xmlXPathNewCString vtklibxml2_xmlXPathNewCString
+#define xmlXPathNewContext vtklibxml2_xmlXPathNewContext
 #define xmlXPathNewFloat vtklibxml2_xmlXPathNewFloat
 #define xmlXPathNewNodeSet vtklibxml2_xmlXPathNewNodeSet
 #define xmlXPathNewNodeSetList vtklibxml2_xmlXPathNewNodeSetList
@@ -1518,8 +1522,8 @@
 #define xmlXPathNumberFunction vtklibxml2_xmlXPathNumberFunction
 #define xmlXPathObjectCopy vtklibxml2_xmlXPathObjectCopy
 #define xmlXPathOrderDocElems vtklibxml2_xmlXPathOrderDocElems
-#define xmlXPathParseName vtklibxml2_xmlXPathParseName
 #define xmlXPathParseNCName vtklibxml2_xmlXPathParseNCName
+#define xmlXPathParseName vtklibxml2_xmlXPathParseName
 #define xmlXPathPopBoolean vtklibxml2_xmlXPathPopBoolean
 #define xmlXPathPopExternal vtklibxml2_xmlXPathPopExternal
 #define xmlXPathPopNodeSet vtklibxml2_xmlXPathPopNodeSet
@@ -1527,9 +1531,6 @@
 #define xmlXPathPopString vtklibxml2_xmlXPathPopString
 #define xmlXPathPositionFunction vtklibxml2_xmlXPathPositionFunction
 #define xmlXPathRegisterAllFunctions vtklibxml2_xmlXPathRegisterAllFunctions
-#define xmlXPathRegisteredFuncsCleanup vtklibxml2_xmlXPathRegisteredFuncsCleanup
-#define xmlXPathRegisteredNsCleanup vtklibxml2_xmlXPathRegisteredNsCleanup
-#define xmlXPathRegisteredVariablesCleanup vtklibxml2_xmlXPathRegisteredVariablesCleanup
 #define xmlXPathRegisterFunc vtklibxml2_xmlXPathRegisterFunc
 #define xmlXPathRegisterFuncLookup vtklibxml2_xmlXPathRegisterFuncLookup
 #define xmlXPathRegisterFuncNS vtklibxml2_xmlXPathRegisterFuncNS
@@ -1537,6 +1538,9 @@
 #define xmlXPathRegisterVariable vtklibxml2_xmlXPathRegisterVariable
 #define xmlXPathRegisterVariableLookup vtklibxml2_xmlXPathRegisterVariableLookup
 #define xmlXPathRegisterVariableNS vtklibxml2_xmlXPathRegisterVariableNS
+#define xmlXPathRegisteredFuncsCleanup vtklibxml2_xmlXPathRegisteredFuncsCleanup
+#define xmlXPathRegisteredNsCleanup vtklibxml2_xmlXPathRegisteredNsCleanup
+#define xmlXPathRegisteredVariablesCleanup vtklibxml2_xmlXPathRegisteredVariablesCleanup
 #define xmlXPathRoot vtklibxml2_xmlXPathRoot
 #define xmlXPathRoundFunction vtklibxml2_xmlXPathRoundFunction
 #define xmlXPathSetContextNode vtklibxml2_xmlXPathSetContextNode
@@ -1544,10 +1548,10 @@
 #define xmlXPathStringEvalNumber vtklibxml2_xmlXPathStringEvalNumber
 #define xmlXPathStringFunction vtklibxml2_xmlXPathStringFunction
 #define xmlXPathStringLengthFunction vtklibxml2_xmlXPathStringLengthFunction
+#define xmlXPathSubValues vtklibxml2_xmlXPathSubValues
 #define xmlXPathSubstringAfterFunction vtklibxml2_xmlXPathSubstringAfterFunction
 #define xmlXPathSubstringBeforeFunction vtklibxml2_xmlXPathSubstringBeforeFunction
 #define xmlXPathSubstringFunction vtklibxml2_xmlXPathSubstringFunction
-#define xmlXPathSubValues vtklibxml2_xmlXPathSubValues
 #define xmlXPathSumFunction vtklibxml2_xmlXPathSumFunction
 #define xmlXPathTrailing vtklibxml2_xmlXPathTrailing
 #define xmlXPathTrailingSorted vtklibxml2_xmlXPathTrailingSorted
@@ -1560,6 +1564,7 @@
 #define xmlXPathWrapExternal vtklibxml2_xmlXPathWrapExternal
 #define xmlXPathWrapNodeSet vtklibxml2_xmlXPathWrapNodeSet
 #define xmlXPathWrapString vtklibxml2_xmlXPathWrapString
+#define xmlXPatherror vtklibxml2_xmlXPatherror
 #define xmlXPtrAdvanceNode vtklibxml2_xmlXPtrAdvanceNode
 #define xmlXPtrBuildNodeList vtklibxml2_xmlXPtrBuildNodeList
 #define xmlXPtrEval vtklibxml2_xmlXPtrEval
@@ -1572,8 +1577,8 @@
 #define xmlXPtrLocationSetRemove vtklibxml2_xmlXPtrLocationSetRemove
 #define xmlXPtrNewCollapsedRange vtklibxml2_xmlXPtrNewCollapsedRange
 #define xmlXPtrNewContext vtklibxml2_xmlXPtrNewContext
-#define xmlXPtrNewLocationSetNodes vtklibxml2_xmlXPtrNewLocationSetNodes
 #define xmlXPtrNewLocationSetNodeSet vtklibxml2_xmlXPtrNewLocationSetNodeSet
+#define xmlXPtrNewLocationSetNodes vtklibxml2_xmlXPtrNewLocationSetNodes
 #define xmlXPtrNewRange vtklibxml2_xmlXPtrNewRange
 #define xmlXPtrNewRangeNodeObject vtklibxml2_xmlXPtrNewRangeNodeObject
 #define xmlXPtrNewRangeNodePoint vtklibxml2_xmlXPtrNewRangeNodePoint
diff --git a/include/libxml/xlink.h b/include/libxml/xlink.h
index a209a9976d8..04e4b32c015 100644
--- a/include/libxml/xlink.h
+++ b/include/libxml/xlink.h
@@ -26,7 +26,7 @@ extern "C" {
  *       of namespaces. If "foo" is the prefix for "http://foo.com/"
  *       then the link detection layer will expand role="foo:myrole"
  *       to "http://foo.com/:myrole".
- * NOTE: the link detection layer will expand URI-Refences found on
+ * NOTE: the link detection layer will expand URI-References found on
  *       href attributes by using the base mechanism if found.
  */
 typedef xmlChar *xlinkHRef;
diff --git a/include/libxml/xmlIO.h b/include/libxml/xmlIO.h
index 3e41744deb0..8690d668c25 100644
--- a/include/libxml/xmlIO.h
+++ b/include/libxml/xmlIO.h
@@ -27,7 +27,7 @@ extern "C" {
  * @filename: the filename or URI
  *
  * Callback used in the I/O Input API to detect if the current handler
- * can provide input fonctionnalities for this resource.
+ * can provide input functionality for this resource.
  *
  * Returns 1 if yes and 0 if another Input module should be used
  */
@@ -73,7 +73,7 @@ typedef int (XMLCALL *xmlInputCloseCallback) (void * context);
  * @filename: the filename or URI
  *
  * Callback used in the I/O Output API to detect if the current handler
- * can provide output fonctionnalities for this resource.
+ * can provide output functionality for this resource.
  *
  * Returns 1 if yes and 0 if another Output module should be used
  */
diff --git a/include/libxml/xmlerror.h b/include/libxml/xmlerror.h
index 037c16d5704..c1019971f24 100644
--- a/include/libxml/xmlerror.h
+++ b/include/libxml/xmlerror.h
@@ -837,7 +837,7 @@ typedef enum {
  * xmlGenericErrorFunc:
  * @ctx:  a parsing context
  * @msg:  the message
- * @...:  the extra arguments of the varags to format the message
+ * @...:  the extra arguments of the varargs to format the message
  *
  * Signature of the function to use when there is an error and
  * no parsing or validity context available .
diff --git a/include/libxml/xmlexports.h b/include/libxml/xmlexports.h
index 40ca5ad5b21..3e1d2d7f4df 100644
--- a/include/libxml/xmlexports.h
+++ b/include/libxml/xmlexports.h
@@ -75,9 +75,6 @@
     #define XMLCALL __cdecl
   #endif
   #define XMLCDECL __cdecl
-  #if !defined _REENTRANT
-    #define _REENTRANT
-  #endif
 #endif
 
 /* Windows platform with Borland compiler */
@@ -99,9 +96,6 @@
   #endif
   #define XMLCALL __cdecl
   #define XMLCDECL __cdecl
-  #if !defined _REENTRANT
-    #define _REENTRANT
-  #endif
 #endif
 
 /* Windows platform with GNU compiler (Mingw) */
@@ -128,9 +122,6 @@
   #endif
   #define XMLCALL __cdecl
   #define XMLCDECL __cdecl
-  #if !defined _REENTRANT
-    #define _REENTRANT
-  #endif
 #endif
 
 /* Cygwin platform (does not define _WIN32), GNU compiler */
diff --git a/include/libxml/xmlversion.h.in b/include/libxml/xmlversion.h.in
index d10f9754eac..964f10d81ab 100644
--- a/include/libxml/xmlversion.h.in
+++ b/include/libxml/xmlversion.h.in
@@ -91,11 +91,8 @@ XMLPUBFUN void XMLCALL xmlCheckVersion(int version);
  * Whether the thread support is configured in
  */
 #if @WITH_THREADS@
-#if defined(_REENTRANT) || defined(__MT__) || \
-    (defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE - 0 >= 199506L))
 #define LIBXML_THREAD_ENABLED
 #endif
-#endif
 
 /**
  * LIBXML_THREAD_ALLOC_ENABLED:
@@ -353,8 +350,10 @@ XMLPUBFUN void XMLCALL xmlCheckVersion(int version);
  * LIBXML_EXPR_ENABLED:
  *
  * Whether the formal expressions interfaces are compiled in
+ *
+ * This code is unused and disabled unconditionally for now.
  */
-#if @WITH_SCHEMAS@
+#if 0
 #define LIBXML_EXPR_ENABLED
 #endif
 
diff --git a/include/libxml/xpath.h b/include/libxml/xpath.h
index d96776c5183..4ef3909b409 100644
--- a/include/libxml/xpath.h
+++ b/include/libxml/xpath.h
@@ -70,7 +70,9 @@ typedef enum {
     XPATH_INVALID_CHAR_ERROR,
     XPATH_INVALID_CTXT,
     XPATH_STACK_ERROR,
-    XPATH_FORBID_VARIABLE_ERROR
+    XPATH_FORBID_VARIABLE_ERROR,
+    XPATH_OP_LIMIT_EXCEEDED,
+    XPATH_RECURSION_LIMIT_EXCEEDED
 } xmlXPathError;
 
 /*
@@ -82,7 +84,7 @@ struct _xmlNodeSet {
     int nodeNr;			/* number of nodes in the set */
     int nodeMax;		/* size of the array as allocated */
     xmlNodePtr *nodeTab;	/* array of nodes in no particular order */
-    /* @@ with_ns to check wether namespace nodes should be looked at @@ */
+    /* @@ with_ns to check whether namespace nodes should be looked at @@ */
 };
 
 /*
@@ -352,6 +354,13 @@ struct _xmlXPathContext {
 
     /* Cache for reusal of XPath objects */
     void *cache;
+
+    /* Resource limits */
+    unsigned long opLimit;
+    unsigned long opCount;
+    int depth;
+    int maxDepth;
+    int maxParserDepth;
 };
 
 /*
diff --git a/libxml.h b/libxml.h
index 64e30f77046..1090729c65e 100644
--- a/libxml.h
+++ b/libxml.h
@@ -34,7 +34,7 @@
 /*
  * Currently supported platforms use either autoconf or
  * copy to config.h own "preset" configuration file.
- * As result ifdef HAVE_CONFIG_H is omited here.
+ * As result ifdef HAVE_CONFIG_H is omitted here.
  */
 #include "config.h"
 #include <libxml/xmlversion.h>
@@ -53,7 +53,7 @@ int vfprintf(FILE *, const char *, va_list);
 /**
  * TRIO_REPLACE_STDIO:
  *
- * This macro is defined if teh trio string formatting functions are to
+ * This macro is defined if the trio string formatting functions are to
  * be used instead of the default stdio ones.
  */
 #define TRIO_REPLACE_STDIO
@@ -72,6 +72,13 @@ int vfprintf(FILE *, const char *, va_list);
 #define XML_POP_WARNINGS
 #endif
 
+#if defined(__clang__) || \
+    (defined(__GNUC__) && (__GNUC__ >= 8))
+#define ATTRIBUTE_NO_SANITIZE(arg) __attribute__((no_sanitize(arg)))
+#else
+#define ATTRIBUTE_NO_SANITIZE(arg)
+#endif
+
 /*
  * Internal variable indicating if a callback has been registered for
  * node creation/destruction. It avoids spending a lot of time in locking
@@ -79,7 +86,7 @@ int vfprintf(FILE *, const char *, va_list);
  */
 extern int __xmlRegisterCallbacks;
 /*
- * internal error reporting routines, shared but not partof the API.
+ * internal error reporting routines, shared but not part of the API.
  */
 void __xmlIOErr(int domain, int code, const char *extra);
 void __xmlLoaderErr(void *ctx, const char *msg, const char *filename) LIBXML_ATTR_FORMAT(2,0);
diff --git a/parser.c b/parser.c
index 5813a6643e1..d1c319631fc 100644
--- a/parser.c
+++ b/parser.c
@@ -96,6 +96,12 @@ xmlCreateEntityParserCtxtInternal(const xmlChar *URL, const xmlChar *ID,
 
 static void xmlHaltParser(xmlParserCtxtPtr ctxt);
 
+static int
+xmlParseElementStart(xmlParserCtxtPtr ctxt);
+
+static void
+xmlParseElementEnd(xmlParserCtxtPtr ctxt);
+
 /************************************************************************
  *									*
  *	Arbitrary limits set in the parser. See XML_PARSE_HUGE		*
@@ -108,7 +114,7 @@ static void xmlHaltParser(xmlParserCtxtPtr ctxt);
 /*
  * 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
+ *    and exponential behaviour. A value of 10 correspond to at least 3 entity
  *    replacement per byte of input.
  */
 #define XML_PARSER_NON_LINEAR 10
@@ -140,7 +146,7 @@ xmlParserEntityCheck(xmlParserCtxtPtr ctxt, size_t size,
     if ((ent != NULL) && (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) &&
 	(ent->content != NULL) && (ent->checked == 0) &&
 	(ctxt->errNo != XML_ERR_ENTITY_LOOP)) {
-	unsigned long oldnbent = ctxt->nbentities;
+	unsigned long oldnbent = ctxt->nbentities, diff;
 	xmlChar *rep;
 
 	ent->checked = 1;
@@ -153,7 +159,10 @@ xmlParserEntityCheck(xmlParserCtxtPtr ctxt, size_t size,
 	    ent->content[0] = 0;
 	}
 
-	ent->checked = (ctxt->nbentities - oldnbent + 1) * 2;
+        diff = ctxt->nbentities - oldnbent + 1;
+        if (diff > INT_MAX / 2)
+            diff = INT_MAX / 2;
+	ent->checked = diff * 2;
 	if (rep != NULL) {
 	    if (xmlStrchr(rep, '<'))
 		ent->checked |= 1;
@@ -1060,7 +1069,7 @@ xmlHasFeature(xmlFeature feature)
  * xmlDetectSAX2:
  * @ctxt:  an XML parser context
  *
- * Do the SAX2 detection and specific intialization
+ * Do the SAX2 detection and specific initialization
  */
 static void
 xmlDetectSAX2(xmlParserCtxtPtr ctxt) {
@@ -1392,7 +1401,7 @@ xmlCleanSpecialAttr(xmlParserCtxtPtr ctxt)
  * [37] UserCode ::= ('x' | 'X') '-' ([a-z] | [A-Z])+
  * [38] Subcode ::= ([a-z] | [A-Z])+
  *
- * The current REC reference the sucessors of RFC 1766, currently 5646
+ * The current REC reference the successors of RFC 1766, currently 5646
  *
  * http://www.rfc-editor.org/rfc/rfc5646.txt
  * langtag       = language
@@ -1819,7 +1828,6 @@ nodePop(xmlParserCtxtPtr ctxt)
     return (ret);
 }
 
-#ifdef LIBXML_PUSH_ENABLED
 /**
  * nameNsPush:
  * @ctxt:  an XML parser context
@@ -1855,6 +1863,11 @@ nameNsPush(xmlParserCtxtPtr ctxt, const xmlChar * value,
 	    goto mem_error;
         }
 	ctxt->pushTab = tmp2;
+    } else if (ctxt->pushTab == NULL) {
+        ctxt->pushTab = (void **) xmlMalloc(ctxt->nameMax * 3 *
+                                            sizeof(ctxt->pushTab[0]));
+        if (ctxt->pushTab == NULL)
+            goto mem_error;
     }
     ctxt->nameTab[ctxt->nameNr] = value;
     ctxt->name = value;
@@ -1866,6 +1879,7 @@ mem_error:
     xmlErrMemory(ctxt, NULL);
     return (-1);
 }
+#ifdef LIBXML_PUSH_ENABLED
 /**
  * nameNsPop:
  * @ctxt: an XML parser context
@@ -2075,11 +2089,11 @@ static void xmlSHRINK (xmlParserCtxtPtr ctxt) {
 	xmlGROW (ctxt);
 
 static void xmlGROW (xmlParserCtxtPtr ctxt) {
-    unsigned long curEnd = ctxt->input->end - ctxt->input->cur;
-    unsigned long curBase = ctxt->input->cur - ctxt->input->base;
+    ptrdiff_t curEnd = ctxt->input->end - ctxt->input->cur;
+    ptrdiff_t curBase = ctxt->input->cur - ctxt->input->base;
 
-    if (((curEnd > (unsigned long) XML_MAX_LOOKUP_LIMIT) ||
-         (curBase > (unsigned long) XML_MAX_LOOKUP_LIMIT)) &&
+    if (((curEnd > XML_MAX_LOOKUP_LIMIT) ||
+         (curBase > XML_MAX_LOOKUP_LIMIT)) &&
          ((ctxt->input->buf) &&
           (ctxt->input->buf->readcallback != xmlInputReadCallbackNop)) &&
         ((ctxt->options & XML_PARSE_HUGE) == 0)) {
@@ -2281,9 +2295,8 @@ xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) {
  */
 int
 xmlParseCharRef(xmlParserCtxtPtr ctxt) {
-    unsigned int val = 0;
+    int val = 0;
     int count = 0;
-    unsigned int outofrange = 0;
 
     /*
      * Using RAW/CUR/NEXT is okay since we are working on ASCII range here
@@ -2310,8 +2323,8 @@ xmlParseCharRef(xmlParserCtxtPtr ctxt) {
 		val = 0;
 		break;
 	    }
-	    if (val > 0x10FFFF)
-	        outofrange = val;
+	    if (val > 0x110000)
+	        val = 0x110000;
 
 	    NEXT;
 	    count++;
@@ -2339,8 +2352,8 @@ xmlParseCharRef(xmlParserCtxtPtr ctxt) {
 		val = 0;
 		break;
 	    }
-	    if (val > 0x10FFFF)
-	        outofrange = val;
+	    if (val > 0x110000)
+	        val = 0x110000;
 
 	    NEXT;
 	    count++;
@@ -2360,7 +2373,11 @@ xmlParseCharRef(xmlParserCtxtPtr ctxt) {
      * Characters referred to using character references must match the
      * production for Char.
      */
-    if ((IS_CHAR(val) && (outofrange == 0))) {
+    if (val >= 0x110000) {
+        xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
+                "xmlParseCharRef: character reference out of bounds\n",
+	        val);
+    } else if (IS_CHAR(val)) {
         return(val);
     } else {
         xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
@@ -2392,8 +2409,7 @@ static int
 xmlParseStringCharRef(xmlParserCtxtPtr ctxt, const xmlChar **str) {
     const xmlChar *ptr;
     xmlChar cur;
-    unsigned int val = 0;
-    unsigned int outofrange = 0;
+    int val = 0;
 
     if ((str == NULL) || (*str == NULL)) return(0);
     ptr = *str;
@@ -2413,8 +2429,8 @@ xmlParseStringCharRef(xmlParserCtxtPtr ctxt, const xmlChar **str) {
 		val = 0;
 		break;
 	    }
-	    if (val > 0x10FFFF)
-	        outofrange = val;
+	    if (val > 0x110000)
+	        val = 0x110000;
 
 	    ptr++;
 	    cur = *ptr;
@@ -2432,8 +2448,8 @@ xmlParseStringCharRef(xmlParserCtxtPtr ctxt, const xmlChar **str) {
 		val = 0;
 		break;
 	    }
-	    if (val > 0x10FFFF)
-	        outofrange = val;
+	    if (val > 0x110000)
+	        val = 0x110000;
 
 	    ptr++;
 	    cur = *ptr;
@@ -2451,7 +2467,11 @@ xmlParseStringCharRef(xmlParserCtxtPtr ctxt, const xmlChar **str) {
      * Characters referred to using character references must match the
      * production for Char.
      */
-    if ((IS_CHAR(val) && (outofrange == 0))) {
+    if (val >= 0x110000) {
+        xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
+                "xmlParseStringCharRef: character reference out of bounds\n",
+                val);
+    } else if (IS_CHAR(val)) {
         return(val);
     } else {
         xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR,
@@ -2702,7 +2722,7 @@ xmlStringLenDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int len,
 		    /*
 		     * Note: external parsed entities will not be loaded,
 		     * it is not required for a non-validating parser to
-		     * complete external PEreferences coming from the
+		     * complete external PEReferences coming from the
 		     * internal subset
 		     */
 		    if (((ctxt->options & XML_PARSE_NOENT) != 0) ||
@@ -3366,7 +3386,7 @@ xmlParseNCNameComplex(xmlParserCtxtPtr ctxt) {
 	    /*
 	     * when shrinking to extend the buffer we really need to preserve
 	     * the part of the name we already parsed. Hence rolling back
-	     * by current lenght.
+	     * by current length.
 	     */
 	    ctxt->input->cur -= l;
 	    GROW;
@@ -3835,7 +3855,7 @@ error:
  * xmlParseAttValueComplex:
  * @ctxt:  an XML parser context
  * @len:   the resulting attribute len
- * @normalize:  wether to apply the inner normalization
+ * @normalize:  whether to apply the inner normalization
  *
  * parse a value for an attribute, this is the fallback function
  * of xmlParseAttValue() when the attribute parsing requires handling
@@ -3984,14 +4004,17 @@ xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) {
 		     */
 		    if ((ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) &&
 			(ent->content != NULL) && (ent->checked == 0)) {
-			unsigned long oldnbent = ctxt->nbentities;
+			unsigned long oldnbent = ctxt->nbentities, diff;
 
 			++ctxt->depth;
 			rep = xmlStringDecodeEntities(ctxt, ent->content,
 						  XML_SUBSTITUTE_REF, 0, 0, 0);
 			--ctxt->depth;
 
-			ent->checked = (ctxt->nbentities - oldnbent + 1) * 2;
+                        diff = ctxt->nbentities - oldnbent + 1;
+                        if (diff > INT_MAX / 2)
+                            diff = INT_MAX / 2;
+                        ent->checked = diff * 2;
 			if (rep != NULL) {
 			    if (xmlStrchr(rep, '<'))
 			        ent->checked |= 1;
@@ -4059,7 +4082,7 @@ xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) {
 
     /*
      * There we potentially risk an overflow, don't allow attribute value of
-     * length more than INT_MAX it is a very reasonnable assumption !
+     * length more than INT_MAX it is a very reasonable assumption !
      */
     if (len >= INT_MAX) {
         xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED,
@@ -4664,7 +4687,7 @@ xmlParseExternalID(xmlParserCtxtPtr ctxt, xmlChar **publicID, int strict) {
  * xmlParseCommentComplex:
  * @ctxt:  an XML parser context
  * @buf:  the already parsed part of the buffer
- * @len:  number of bytes filles in the buffer
+ * @len:  number of bytes in the buffer
  * @size:  allocated size of the buffer
  *
  * Skip an XML (SGML) comment <!-- .... -->
@@ -4955,6 +4978,10 @@ get_more:
 		} else
 		    xmlFatalErrMsgStr(ctxt, XML_ERR_HYPHEN_IN_COMMENT,
 		                      "Double hyphen within comment\n", NULL);
+                if (ctxt->instate == XML_PARSER_EOF) {
+                    xmlFree(buf);
+                    return;
+                }
 		in++;
 		ctxt->input->col++;
 	    }
@@ -5085,7 +5112,7 @@ error:
  *
  * [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
  *
- * The processing is transfered to SAX once parsed.
+ * The processing is transferred to SAX once parsed.
  */
 
 void
@@ -5501,7 +5528,7 @@ xmlParseEntityDecl(xmlParserCtxtPtr ctxt) {
 				    literal, URI, NULL);
 		    /*
 		     * For expat compatibility in SAX mode.
-		     * assuming the entity repalcement was asked for
+		     * assuming the entity replacement was asked for
 		     */
 		    if ((ctxt->replaceEntities != 0) &&
 			((ctxt->myDoc == NULL) ||
@@ -6611,149 +6638,143 @@ xmlParseElementDecl(xmlParserCtxtPtr ctxt) {
 
 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')) {
-	SKIP(7);
-	SKIP_BLANKS;
-	if (RAW != '[') {
-	    xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL);
-	    xmlHaltParser(ctxt);
-	    return;
-	} else {
-	    if (ctxt->input->id != id) {
-		xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
-	                       "All markup of the conditional section is not"
-                               " in the same entity\n");
-	    }
-	    NEXT;
-	}
-	if (xmlParserDebugEntities) {
-	    if ((ctxt->input != NULL) && (ctxt->input->filename))
-		xmlGenericError(xmlGenericErrorContext,
-			"%s(%d): ", ctxt->input->filename,
-			ctxt->input->line);
-	    xmlGenericError(xmlGenericErrorContext,
-		    "Entering INCLUDE Conditional Section\n");
-	}
-
-        SKIP_BLANKS;
-        GROW;
-	while (((RAW != 0) && ((RAW != ']') || (NXT(1) != ']') ||
-	        (NXT(2) != '>'))) && (ctxt->instate != XML_PARSER_EOF)) {
-	    const xmlChar *check = CUR_PTR;
-	    unsigned int cons = ctxt->input->consumed;
+    int *inputIds = NULL;
+    size_t inputIdsSize = 0;
+    size_t depth = 0;
 
-	    if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) {
-		xmlParseConditionalSections(ctxt);
-	    } else
-		xmlParseMarkupDecl(ctxt);
+    while (ctxt->instate != XML_PARSER_EOF) {
+        if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) {
+            int id = ctxt->input->id;
 
+            SKIP(3);
             SKIP_BLANKS;
-            GROW;
 
-	    if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) {
-		xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL);
-		xmlHaltParser(ctxt);
-		break;
-	    }
-	}
-	if (xmlParserDebugEntities) {
-	    if ((ctxt->input != NULL) && (ctxt->input->filename))
-		xmlGenericError(xmlGenericErrorContext,
-			"%s(%d): ", ctxt->input->filename,
-			ctxt->input->line);
-	    xmlGenericError(xmlGenericErrorContext,
-		    "Leaving INCLUDE Conditional Section\n");
-	}
+            if (CMP7(CUR_PTR, 'I', 'N', 'C', 'L', 'U', 'D', 'E')) {
+                SKIP(7);
+                SKIP_BLANKS;
+                if (RAW != '[') {
+                    xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL);
+                    xmlHaltParser(ctxt);
+                    goto error;
+                }
+                if (ctxt->input->id != id) {
+                    xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
+                                   "All markup of the conditional section is"
+                                   " not in the same entity\n");
+                }
+                NEXT;
 
-    } else if (CMP6(CUR_PTR, 'I', 'G', 'N', 'O', 'R', 'E')) {
-	int state;
-	xmlParserInputState instate;
-	int depth = 0;
+                if (inputIdsSize <= depth) {
+                    int *tmp;
 
-	SKIP(6);
-	SKIP_BLANKS;
-	if (RAW != '[') {
-	    xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL);
-	    xmlHaltParser(ctxt);
-	    return;
-	} else {
-	    if (ctxt->input->id != id) {
-		xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
-	                       "All markup of the conditional section is not"
-                               " in the same entity\n");
-	    }
-	    NEXT;
-	}
-	if (xmlParserDebugEntities) {
-	    if ((ctxt->input != NULL) && (ctxt->input->filename))
-		xmlGenericError(xmlGenericErrorContext,
-			"%s(%d): ", ctxt->input->filename,
-			ctxt->input->line);
-	    xmlGenericError(xmlGenericErrorContext,
-		    "Entering IGNORE Conditional Section\n");
-	}
+                    inputIdsSize = (inputIdsSize == 0 ? 4 : inputIdsSize * 2);
+                    tmp = (int *) xmlRealloc(inputIds,
+                            inputIdsSize * sizeof(int));
+                    if (tmp == NULL) {
+                        xmlErrMemory(ctxt, NULL);
+                        goto error;
+                    }
+                    inputIds = tmp;
+                }
+                inputIds[depth] = id;
+                depth++;
+            } else if (CMP6(CUR_PTR, 'I', 'G', 'N', 'O', 'R', 'E')) {
+                int state;
+                xmlParserInputState instate;
+                size_t ignoreDepth = 0;
+
+                SKIP(6);
+                SKIP_BLANKS;
+                if (RAW != '[') {
+                    xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL);
+                    xmlHaltParser(ctxt);
+                    goto error;
+                }
+                if (ctxt->input->id != id) {
+                    xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
+                                   "All markup of the conditional section is"
+                                   " not in the same entity\n");
+                }
+                NEXT;
 
-	/*
-	 * Parse up to the end of the conditional section
-	 * But disable SAX event generating DTD building in the meantime
-	 */
-	state = ctxt->disableSAX;
-	instate = ctxt->instate;
-	if (ctxt->recovery == 0) ctxt->disableSAX = 1;
-	ctxt->instate = XML_PARSER_IGNORE;
+                /*
+                 * Parse up to the end of the conditional section but disable
+                 * SAX event generating DTD building in the meantime
+                 */
+                state = ctxt->disableSAX;
+                instate = ctxt->instate;
+                if (ctxt->recovery == 0) ctxt->disableSAX = 1;
+                ctxt->instate = XML_PARSER_IGNORE;
+
+                while (RAW != 0) {
+                    if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) {
+                        SKIP(3);
+                        ignoreDepth++;
+                        /* Check for integer overflow */
+                        if (ignoreDepth == 0) {
+                            xmlErrMemory(ctxt, NULL);
+                            goto error;
+                        }
+                    } else if ((RAW == ']') && (NXT(1) == ']') &&
+                               (NXT(2) == '>')) {
+                        if (ignoreDepth == 0)
+                            break;
+                        SKIP(3);
+                        ignoreDepth--;
+                    } else {
+                        NEXT;
+                    }
+                }
 
-	while (((depth >= 0) && (RAW != 0)) &&
-               (ctxt->instate != XML_PARSER_EOF)) {
-	  if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) {
-	    depth++;
-	    SKIP(3);
-	    continue;
-	  }
-	  if ((RAW == ']') && (NXT(1) == ']') && (NXT(2) == '>')) {
-	    if (--depth >= 0) SKIP(3);
-	    continue;
-	  }
-	  NEXT;
-	  continue;
-	}
+                ctxt->disableSAX = state;
+                ctxt->instate = instate;
 
-	ctxt->disableSAX = state;
-	ctxt->instate = instate;
+		if (RAW == 0) {
+		    xmlFatalErr(ctxt, XML_ERR_CONDSEC_NOT_FINISHED, NULL);
+                    goto error;
+		}
+                if (ctxt->input->id != id) {
+                    xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
+                                   "All markup of the conditional section is"
+                                   " not in the same entity\n");
+                }
+                SKIP(3);
+            } else {
+                xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID_KEYWORD, NULL);
+                xmlHaltParser(ctxt);
+                goto error;
+            }
+        } else if ((depth > 0) &&
+                   (RAW == ']') && (NXT(1) == ']') && (NXT(2) == '>')) {
+            depth--;
+            if (ctxt->input->id != inputIds[depth]) {
+                xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
+                               "All markup of the conditional section is not"
+                               " in the same entity\n");
+            }
+            SKIP(3);
+        } else {
+            const xmlChar *check = CUR_PTR;
+            unsigned int cons = ctxt->input->consumed;
 
-	if (xmlParserDebugEntities) {
-	    if ((ctxt->input != NULL) && (ctxt->input->filename))
-		xmlGenericError(xmlGenericErrorContext,
-			"%s(%d): ", ctxt->input->filename,
-			ctxt->input->line);
-	    xmlGenericError(xmlGenericErrorContext,
-		    "Leaving IGNORE Conditional Section\n");
-	}
+            xmlParseMarkupDecl(ctxt);
 
-    } else {
-	xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID_KEYWORD, NULL);
-	xmlHaltParser(ctxt);
-	return;
-    }
+            if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) {
+                xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL);
+                xmlHaltParser(ctxt);
+                goto error;
+            }
+        }
 
-    if (RAW == 0)
-        SHRINK;
+        if (depth == 0)
+            break;
 
-    if (RAW == 0) {
-	xmlFatalErr(ctxt, XML_ERR_CONDSEC_NOT_FINISHED, NULL);
-    } else {
-	if (ctxt->input->id != id) {
-	    xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
-	                   "All markup of the conditional section is not in"
-                           " the same entity\n");
-	}
-	if ((ctxt-> instate != XML_PARSER_EOF) &&
-	    ((ctxt->input->cur + 3) <= ctxt->input->end))
-	    SKIP(3);
+        SKIP_BLANKS;
+        GROW;
     }
+
+error:
+    xmlFree(inputIds);
 }
 
 /**
@@ -6810,21 +6831,11 @@ xmlParseMarkupDecl(xmlParserCtxtPtr ctxt) {
 
     /*
      * detect requirement to exit there and act accordingly
-     * and avoid having instate overriden later on
+     * and avoid having instate overridden later on
      */
     if (ctxt->instate == XML_PARSER_EOF)
         return;
 
-    /*
-     * Conditional sections are allowed from entities included
-     * by PE References in the internal subset.
-     */
-    if ((ctxt->external == 0) && (ctxt->inputNr > 1)) {
-        if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) {
-	    xmlParseConditionalSections(ctxt);
-	}
-    }
-
     ctxt->instate = XML_PARSER_DTD;
 }
 
@@ -7009,7 +7020,7 @@ xmlParseReference(xmlParserCtxtPtr ctxt) {
      */
     if (NXT(1) == '#') {
 	int i = 0;
-	xmlChar out[10];
+	xmlChar out[16];
 	int hex = NXT(2);
 	int value = xmlParseCharRef(ctxt);
 
@@ -7086,7 +7097,7 @@ xmlParseReference(xmlParserCtxtPtr ctxt) {
          ((ent->children == NULL) && (ctxt->options & XML_PARSE_NOENT))) &&
         ((ent->etype != XML_EXTERNAL_GENERAL_PARSED_ENTITY) ||
          (ctxt->options & (XML_PARSE_NOENT | XML_PARSE_DTDVALID)))) {
-	unsigned long oldnbent = ctxt->nbentities;
+	unsigned long oldnbent = ctxt->nbentities, diff;
 
 	/*
 	 * This is a bit hackish but this seems the best
@@ -7127,7 +7138,10 @@ xmlParseReference(xmlParserCtxtPtr ctxt) {
 	 * Store the number of entities needing parsing for this entity
 	 * content and do checkings
 	 */
-	ent->checked = (ctxt->nbentities - oldnbent + 1) * 2;
+        diff = ctxt->nbentities - oldnbent + 1;
+        if (diff > INT_MAX / 2)
+            diff = INT_MAX / 2;
+        ent->checked = diff * 2;
 	if ((ent->content != NULL) && (xmlStrchr(ent->content, '<')))
 	    ent->checked |= 1;
 	if (ret == XML_ERR_ENTITY_LOOP) {
@@ -7675,7 +7689,7 @@ xmlParseStringEntityRef(xmlParserCtxtPtr ctxt, const xmlChar ** str) {
     }
 
     /*
-     * Increate the number of entity references parsed
+     * Increase the number of entity references parsed
      */
     ctxt->nbentities++;
 
@@ -7851,7 +7865,7 @@ xmlParsePEReference(xmlParserCtxtPtr ctxt)
     NEXT;
 
     /*
-     * Increate the number of entity references parsed
+     * Increase the number of entity references parsed
      */
     ctxt->nbentities++;
 
@@ -8117,7 +8131,7 @@ xmlParseStringPEReference(xmlParserCtxtPtr ctxt, const xmlChar **str) {
     ptr++;
 
     /*
-     * Increate the number of entity references parsed
+     * Increase the number of entity references parsed
      */
     ctxt->nbentities++;
 
@@ -8285,6 +8299,15 @@ xmlParseInternalSubset(xmlParserCtxtPtr ctxt) {
 	    xmlParseMarkupDecl(ctxt);
 	    xmlParsePEReference(ctxt);
 
+            /*
+             * Conditional sections are allowed from external entities included
+             * by PE References in the internal subset.
+             */
+            if ((ctxt->inputNr > 1) && (ctxt->input->filename != NULL) &&
+                (RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) {
+                xmlParseConditionalSections(ctxt);
+            }
+
 	    if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) {
 		xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR,
 	     "xmlParseInternalSubset: error detected in Markup declaration\n");
@@ -8713,12 +8736,16 @@ xmlParseQName(xmlParserCtxtPtr ctxt, const xmlChar **prefix) {
 	if (l == NULL) {
 	    xmlChar *tmp;
 
+            if (ctxt->instate == XML_PARSER_EOF)
+                return(NULL);
             xmlNsErr(ctxt, XML_NS_ERR_QNAME,
 	             "Failed to parse QName '%s:'\n", p, NULL, NULL);
 	    l = xmlParseNmtoken(ctxt);
-	    if (l == NULL)
+	    if (l == NULL) {
+                if (ctxt->instate == XML_PARSER_EOF)
+                    return(NULL);
 		tmp = xmlBuildQName(BAD_CAST "", p, NULL, 0);
-	    else {
+            } else {
 		tmp = xmlBuildQName(l, p, NULL, 0);
 		xmlFree((char *)l);
 	    }
@@ -8741,6 +8768,8 @@ xmlParseQName(xmlParserCtxtPtr ctxt, const xmlChar **prefix) {
 		*prefix = p;
 		return(l);
 	    }
+            if (ctxt->instate == XML_PARSER_EOF)
+                return(NULL);
 	    tmp = xmlBuildQName(BAD_CAST "", l, NULL, 0);
 	    l = xmlDictLookup(ctxt->dict, tmp, -1);
 	    if (tmp != NULL) xmlFree(tmp);
@@ -8840,6 +8869,18 @@ xmlParseQNameAndCompare(xmlParserCtxtPtr ctxt, xmlChar const *name,
  *     caller if it was copied, this can be detected by val[*len] == 0.
  */
 
+#define GROW_PARSE_ATT_VALUE_INTERNAL(ctxt, in, start, end) \
+    const xmlChar *oldbase = ctxt->input->base;\
+    GROW;\
+    if (ctxt->instate == XML_PARSER_EOF)\
+        return(NULL);\
+    if (oldbase != ctxt->input->base) {\
+        ptrdiff_t delta = ctxt->input->base - oldbase;\
+        start = start + delta;\
+        in = in + delta;\
+    }\
+    end = ctxt->input->end;
+
 static xmlChar *
 xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc,
                          int normalize)
@@ -8869,14 +8910,7 @@ xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc,
     end = ctxt->input->end;
     start = in;
     if (in >= end) {
-        const xmlChar *oldbase = ctxt->input->base;
-	GROW;
-	if (oldbase != ctxt->input->base) {
-	    long delta = ctxt->input->base - oldbase;
-	    start = start + delta;
-	    in = in + delta;
-	}
-	end = ctxt->input->end;
+        GROW_PARSE_ATT_VALUE_INTERNAL(ctxt, in, start, end)
     }
     if (normalize) {
         /*
@@ -8893,16 +8927,7 @@ xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc,
 	    in++;
 	    start = in;
 	    if (in >= end) {
-		const xmlChar *oldbase = ctxt->input->base;
-		GROW;
-                if (ctxt->instate == XML_PARSER_EOF)
-                    return(NULL);
-		if (oldbase != ctxt->input->base) {
-		    long delta = ctxt->input->base - oldbase;
-		    start = start + delta;
-		    in = in + delta;
-		}
-		end = ctxt->input->end;
+                GROW_PARSE_ATT_VALUE_INTERNAL(ctxt, in, start, end)
                 if (((in - start) > XML_MAX_TEXT_LENGTH) &&
                     ((ctxt->options & XML_PARSE_HUGE) == 0)) {
                     xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED,
@@ -8916,16 +8941,7 @@ xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc,
 	    col++;
 	    if ((*in++ == 0x20) && (*in == 0x20)) break;
 	    if (in >= end) {
-		const xmlChar *oldbase = ctxt->input->base;
-		GROW;
-                if (ctxt->instate == XML_PARSER_EOF)
-                    return(NULL);
-		if (oldbase != ctxt->input->base) {
-		    long delta = ctxt->input->base - oldbase;
-		    start = start + delta;
-		    in = in + delta;
-		}
-		end = ctxt->input->end;
+                GROW_PARSE_ATT_VALUE_INTERNAL(ctxt, in, start, end)
                 if (((in - start) > XML_MAX_TEXT_LENGTH) &&
                     ((ctxt->options & XML_PARSE_HUGE) == 0)) {
                     xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED,
@@ -8954,7 +8970,7 @@ xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc,
                 if (ctxt->instate == XML_PARSER_EOF)
                     return(NULL);
 		if (oldbase != ctxt->input->base) {
-		    long delta = ctxt->input->base - oldbase;
+		    ptrdiff_t delta = ctxt->input->base - oldbase;
 		    start = start + delta;
 		    in = in + delta;
 		    last = last + delta;
@@ -8981,16 +8997,7 @@ xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc,
 	    in++;
 	    col++;
 	    if (in >= end) {
-		const xmlChar *oldbase = ctxt->input->base;
-		GROW;
-                if (ctxt->instate == XML_PARSER_EOF)
-                    return(NULL);
-		if (oldbase != ctxt->input->base) {
-		    long delta = ctxt->input->base - oldbase;
-		    start = start + delta;
-		    in = in + delta;
-		}
-		end = ctxt->input->end;
+                GROW_PARSE_ATT_VALUE_INTERNAL(ctxt, in, start, end)
                 if (((in - start) > XML_MAX_TEXT_LENGTH) &&
                     ((ctxt->options & XML_PARSE_HUGE) == 0)) {
                     xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED,
@@ -9084,7 +9091,7 @@ xmlParseAttribute2(xmlParserCtxtPtr ctxt,
 	if (normalize) {
 	    /*
 	     * Sometimes a second normalisation pass for spaces is needed
-	     * but that only happens if charrefs or entities refernces
+	     * but that only happens if charrefs or entities references
 	     * have been used in the attribute value, i.e. the attribute
 	     * value have been extracted in an allocated string already.
 	     */
@@ -9247,7 +9254,8 @@ xmlParseStartTag2(xmlParserCtxtPtr ctxt, const xmlChar **pref,
                 xmlErrMemory(ctxt, "dictionary allocation failure");
                 if ((attvalue != NULL) && (alloc != 0))
                     xmlFree(attvalue);
-                return(NULL);
+                localname = NULL;
+                goto done;
             }
             if (*URL != 0) {
                 uri = xmlParseURI((const char *) URL);
@@ -9497,7 +9505,8 @@ next_attr:
 
 		    if ((atts == NULL) || (nbatts + 5 > maxatts)) {
 			if (xmlCtxtGrowAttrs(ctxt, nbatts + 5) < 0) {
-			    return(NULL);
+                            localname = NULL;
+                            goto done;
 			}
 			maxatts = ctxt->maxatts;
 			atts = ctxt->atts;
@@ -9807,9 +9816,10 @@ xmlParseCDSect(xmlParserCtxtPtr ctxt) {
 
 void
 xmlParseContent(xmlParserCtxtPtr ctxt) {
+    int nameNr = ctxt->nameNr;
+
     GROW;
     while ((RAW != 0) &&
-	   ((RAW != '<') || (NXT(1) != '/')) &&
 	   (ctxt->instate != XML_PARSER_EOF)) {
 	const xmlChar *test = CUR_PTR;
 	unsigned int cons = ctxt->input->consumed;
@@ -9843,7 +9853,13 @@ xmlParseContent(xmlParserCtxtPtr ctxt) {
 	 * Fourth case :  a sub-element.
 	 */
 	else if (*cur == '<') {
-	    xmlParseElement(ctxt);
+            if (NXT(1) == '/') {
+                if (ctxt->nameNr <= nameNr)
+                    break;
+	        xmlParseElementEnd(ctxt);
+            } else {
+	        xmlParseElementStart(ctxt);
+            }
 	}
 
 	/*
@@ -9878,7 +9894,7 @@ xmlParseContent(xmlParserCtxtPtr ctxt) {
  * xmlParseElement:
  * @ctxt:  an XML parser context
  *
- * parse an XML element, this is highly recursive
+ * parse an XML element
  *
  * [39] element ::= EmptyElemTag | STag content ETag
  *
@@ -9890,6 +9906,23 @@ xmlParseContent(xmlParserCtxtPtr ctxt) {
 
 void
 xmlParseElement(xmlParserCtxtPtr ctxt) {
+    if (xmlParseElementStart(ctxt) != 0)
+        return;
+    xmlParseContent(ctxt);
+    if (ctxt->instate == XML_PARSER_EOF)
+	return;
+    xmlParseElementEnd(ctxt);
+}
+
+/**
+ * xmlParseElementStart:
+ * @ctxt:  an XML parser context
+ *
+ * Parse the start of an XML element. Returns -1 in case of error, 0 if an
+ * opening tag was parsed, 1 if an empty element was parsed.
+ */
+static int
+xmlParseElementStart(xmlParserCtxtPtr ctxt) {
     const xmlChar *name;
     const xmlChar *prefix = NULL;
     const xmlChar *URI = NULL;
@@ -9904,7 +9937,7 @@ xmlParseElement(xmlParserCtxtPtr ctxt) {
 		 "Excessive depth in document: %d use XML_PARSE_HUGE option\n",
 			  xmlParserMaxDepth);
 	xmlHaltParser(ctxt);
-	return;
+	return(-1);
     }
 
     /* Capture start position */
@@ -9931,12 +9964,17 @@ xmlParseElement(xmlParserCtxtPtr ctxt) {
 	name = xmlParseStartTag(ctxt);
 #endif /* LIBXML_SAX1_ENABLED */
     if (ctxt->instate == XML_PARSER_EOF)
-	return;
+	return(-1);
     if (name == NULL) {
 	spacePop(ctxt);
-        return;
+        return(-1);
     }
-    namePush(ctxt, name);
+    if (ctxt->sax2)
+        nameNsPush(ctxt, name, prefix, URI, ctxt->nsNr - nsNr);
+#ifdef LIBXML_SAX1_ENABLED
+    else
+        namePush(ctxt, name);
+#endif /* LIBXML_SAX1_ENABLED */
     ret = ctxt->node;
 
 #ifdef LIBXML_VALID_ENABLED
@@ -9977,7 +10015,7 @@ xmlParseElement(xmlParserCtxtPtr ctxt) {
 	   node_info.node = ret;
 	   xmlParserAddNodeInfo(ctxt, &node_info);
 	}
-	return;
+	return(1);
     }
     if (RAW == '>') {
         NEXT1;
@@ -10005,41 +10043,39 @@ xmlParseElement(xmlParserCtxtPtr ctxt) {
 	   node_info.node = ret;
 	   xmlParserAddNodeInfo(ctxt, &node_info);
 	}
-	return;
+	return(-1);
     }
 
-    /*
-     * Parse the content of the element:
-     */
-    xmlParseContent(ctxt);
-    if (ctxt->instate == XML_PARSER_EOF)
-	return;
-    if (!IS_BYTE_CHAR(RAW)) {
-        xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NOT_FINISHED,
-	 "Premature end of data in tag %s line %d\n",
-		                name, line, NULL);
+    return(0);
+}
 
-	/*
-	 * end of parsing of this node.
-	 */
-	nodePop(ctxt);
-	namePop(ctxt);
-	spacePop(ctxt);
-	if (nsNr != ctxt->nsNr)
-	    nsPop(ctxt, ctxt->nsNr - nsNr);
-	return;
-    }
+/**
+ * xmlParseElementEnd:
+ * @ctxt:  an XML parser context
+ *
+ * Parse the end of an XML element.
+ */
+static void
+xmlParseElementEnd(xmlParserCtxtPtr ctxt) {
+    xmlParserNodeInfo node_info;
+    xmlNodePtr ret = ctxt->node;
+
+    if (ctxt->nameNr <= 0)
+        return;
 
     /*
      * parse the end of tag: '</' should be here.
      */
     if (ctxt->sax2) {
-	xmlParseEndTag2(ctxt, prefix, URI, line, ctxt->nsNr - nsNr, tlen);
+        const xmlChar *prefix = ctxt->pushTab[ctxt->nameNr * 3 - 3];
+        const xmlChar *URI = ctxt->pushTab[ctxt->nameNr * 3 - 2];
+        int nsNr = (ptrdiff_t) ctxt->pushTab[ctxt->nameNr * 3 - 1];
+	xmlParseEndTag2(ctxt, prefix, URI, 0, nsNr, 0);
 	namePop(ctxt);
     }
 #ifdef LIBXML_SAX1_ENABLED
-      else
-	xmlParseEndTag1(ctxt, line);
+    else
+	xmlParseEndTag1(ctxt, 0);
 #endif /* LIBXML_SAX1_ENABLED */
 
     /*
@@ -10281,7 +10317,7 @@ xmlParseEncodingDecl(xmlParserCtxtPtr ctxt) {
 	}
 
 	/*
-	 * UTF-16 encoding stwich has already taken place at this stage,
+	 * UTF-16 encoding switch has already taken place at this stage,
 	 * more over the little-endian/big-endian selection is already done
 	 */
         if ((encoding != NULL) &&
@@ -11164,7 +11200,7 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) {
 	else {
 	    /*
 	     * If we are operating on converted input, try to flush
-	     * remainng chars to avoid them stalling in the non-converted
+	     * remaining chars to avoid them stalling in the non-converted
 	     * buffer. But do not do this in document start where
 	     * encoding="..." may not have been read and we work on a
 	     * guessed encoding.
@@ -12356,13 +12392,6 @@ xmlCreatePushParserCtxt(xmlSAXHandlerPtr sax, void *user_data,
 	return(NULL);
     }
     ctxt->dictNames = 1;
-    ctxt->pushTab = (void **) xmlMalloc(ctxt->nameMax * 3 * sizeof(xmlChar *));
-    if (ctxt->pushTab == NULL) {
-        xmlErrMemory(ctxt, NULL);
-	xmlFreeParserInputBuffer(buf);
-	xmlFreeParserCtxt(ctxt);
-	return(NULL);
-    }
     if (sax != NULL) {
 #ifdef LIBXML_SAX1_ENABLED
 	if (ctxt->sax != (xmlSAXHandlerPtr) &xmlDefaultSAXHandler)
@@ -13898,7 +13927,8 @@ xmlParseBalancedChunkMemoryRecover(xmlDocPtr doc, xmlSAXHandlerPtr sax,
     xmlFreeParserCtxt(ctxt);
     newDoc->intSubset = NULL;
     newDoc->extSubset = NULL;
-    newDoc->oldNs = NULL;
+    if(doc != NULL)
+	newDoc->oldNs = NULL;
     xmlFreeDoc(newDoc);
 
     return(ret);
@@ -14007,6 +14037,10 @@ xmlCreateEntityParserCtxtInternal(const xmlChar *URL, const xmlChar *ID,
 	ctxt->input_id = pctx->input_id + 1;
     }
 
+    /* Don't read from stdin. */
+    if (xmlStrcmp(URL, BAD_CAST "-") == 0)
+        URL = BAD_CAST "./-";
+
     uri = xmlBuildURI(URL, base);
 
     if (uri == NULL) {
@@ -14939,16 +14973,6 @@ xmlCtxtResetPush(xmlParserCtxtPtr ctxt, const char *chunk,
 
     xmlCtxtReset(ctxt);
 
-    if (ctxt->pushTab == NULL) {
-        ctxt->pushTab = (void **) xmlMalloc(ctxt->nameMax * 3 *
-	                                    sizeof(xmlChar *));
-        if (ctxt->pushTab == NULL) {
-	    xmlErrMemory(ctxt, NULL);
-            xmlFreeParserInputBuffer(buf);
-            return(1);
-        }
-    }
-
     if (filename == NULL) {
         ctxt->directory = NULL;
     } else {
diff --git a/parserInternals.c b/parserInternals.c
index 02e7322a0da..4a330fbd79d 100644
--- a/parserInternals.c
+++ b/parserInternals.c
@@ -703,7 +703,7 @@ encoding_error:
     /*
      * An encoding problem may arise from a truncated input buffer
      * splitting a character in the middle. In that case do not raise
-     * an error but return 0 to endicate an end of stream problem
+     * an error but return 0 to indicate an end of stream problem
      */
     if (ctxt->input->end - ctxt->input->cur < 4) {
 	*len = 0;
@@ -816,7 +816,7 @@ encoding_error:
     /*
      * An encoding problem may arise from a truncated input buffer
      * splitting a character in the middle. In that case do not raise
-     * an error but return 0 to endicate an end of stream problem
+     * an error but return 0 to indicate an end of stream problem
      */
     if ((ctxt == NULL) || (ctxt->input == NULL) ||
         (ctxt->input->end - ctxt->input->cur < 4)) {
@@ -1093,7 +1093,7 @@ xmlSwitchEncoding(xmlParserCtxtPtr ctxt, xmlCharEncoding enc)
 	}
     }
     /*
-     * TODO: We could recover from errors in external entites if we
+     * TODO: We could recover from errors in external entities if we
      * didn't stop the parser. But most callers of this function don't
      * check the return value.
      */
@@ -1138,7 +1138,7 @@ xmlSwitchInputEncodingInt(xmlParserCtxtPtr ctxt, xmlParserInputPtr input,
     if (input->buf != NULL) {
         if (input->buf->encoder != NULL) {
             /*
-             * Check in case the auto encoding detetection triggered
+             * Check in case the auto encoding detection triggered
              * in already.
              */
             if (input->buf->encoder == handler)
diff --git a/pattern.c b/pattern.c
index 0eb8d81244d..27e96946b69 100644
--- a/pattern.c
+++ b/pattern.c
@@ -1,5 +1,5 @@
 /*
- * pattern.c: Implemetation of selectors for nodes
+ * pattern.c: Implementation of selectors for nodes
  *
  * Reference:
  *   http://www.w3.org/TR/2001/REC-xmlschema-1-20010502/
@@ -55,7 +55,7 @@
 /*
 * NOTE: Those private flags (XML_STREAM_xxx) are used
 *   in _xmlStreamCtxt->flag. They extend the public
-*   xmlPatternFlags, so be carefull not to interfere with the
+*   xmlPatternFlags, so be careful not to interfere with the
 *   reserved values for xmlPatternFlags.
 */
 #define XML_STREAM_FINAL_IS_ANY_NODE 1<<14
@@ -229,13 +229,16 @@ xmlNewPattern(void) {
  */
 void
 xmlFreePattern(xmlPatternPtr comp) {
+    xmlFreePatternList(comp);
+}
+
+static void
+xmlFreePatternInternal(xmlPatternPtr comp) {
     xmlStepOpPtr op;
     int i;
 
     if (comp == NULL)
 	return;
-    if (comp->next != NULL)
-        xmlFreePattern(comp->next);
     if (comp->stream != NULL)
         xmlFreeStreamComp(comp->stream);
     if (comp->pattern != NULL)
@@ -273,7 +276,7 @@ xmlFreePatternList(xmlPatternPtr comp) {
 	cur = comp;
 	comp = comp->next;
 	cur->next = NULL;
-	xmlFreePattern(cur);
+	xmlFreePatternInternal(cur);
     }
 }
 
@@ -742,7 +745,7 @@ rollback:
  * xmlPatScanLiteral:
  * @ctxt:  the XPath Parser context
  *
- * Parse an XPath Litteral:
+ * Parse an XPath Literal:
  *
  * [29] Literal ::= '"' [^"]* '"'
  *                | "'" [^']* "'"
@@ -1973,7 +1976,7 @@ xmlStreamPushInternal(xmlStreamCtxtPtr stream,
 	    } else {
 		/*
 		* If there are "//", then we need to process every "//"
-		* occuring in the states, plus any other state for this
+		* occurring in the states, plus any other state for this
 		* level.
 		*/
 		stepNr = stream->states[2 * i];
diff --git a/relaxng.c b/relaxng.c
index 914706ac168..13fd954c7dd 100644
--- a/relaxng.c
+++ b/relaxng.c
@@ -125,11 +125,11 @@ typedef enum {
     XML_RELAXNG_EXCEPT,         /* except present in nameclass defs */
     XML_RELAXNG_TEXT,           /* textual content */
     XML_RELAXNG_ELEMENT,        /* an element */
-    XML_RELAXNG_DATATYPE,       /* extenal data type definition */
-    XML_RELAXNG_PARAM,          /* extenal data type parameter */
-    XML_RELAXNG_VALUE,          /* value from an extenal data type definition */
+    XML_RELAXNG_DATATYPE,       /* external data type definition */
+    XML_RELAXNG_PARAM,          /* external data type parameter */
+    XML_RELAXNG_VALUE,          /* value from an external data type definition */
     XML_RELAXNG_LIST,           /* a list of patterns */
-    XML_RELAXNG_ATTRIBUTE,      /* an attrbute following a pattern */
+    XML_RELAXNG_ATTRIBUTE,      /* an attribute following a pattern */
     XML_RELAXNG_DEF,            /* a definition */
     XML_RELAXNG_REF,            /* reference to a definition */
     XML_RELAXNG_EXTERNALREF,    /* reference to an external def */
@@ -228,7 +228,7 @@ struct _xmlRelaxNGParserCtxt {
     xmlDocPtr document;
 
     int defNr;                  /* number of defines used */
-    int defMax;                 /* number of defines aloocated */
+    int defMax;                 /* number of defines allocated */
     xmlRelaxNGDefinePtr *defTab;        /* pointer to the allocated definitions */
 
     const char *buffer;
@@ -1128,7 +1128,7 @@ xmlRelaxNGAddStates(xmlRelaxNGValidCtxtPtr ctxt,
 /**
  * xmlRelaxNGFreeStates:
  * @ctxt:  a Relax-NG validation context
- * @states:  teh container
+ * @states:  the container
  *
  * Free a RelaxNG validation state container
  */
@@ -1340,7 +1340,7 @@ xmlRelaxNGCopyValidState(xmlRelaxNGValidCtxtPtr ctxt,
  *
  * Compare the validation states for equality
  *
- * Returns 1 if equald, 0 otherwise
+ * Returns 1 if equal, 0 otherwise
  */
 static int
 xmlRelaxNGEqualValidState(xmlRelaxNGValidCtxtPtr ctxt ATTRIBUTE_UNUSED,
@@ -2815,7 +2815,7 @@ xmlRelaxNGRegisterTypeLibrary(const xmlChar * namespace, void *data,
 /**
  * xmlRelaxNGInitTypes:
  *
- * Initilize the default type libraries.
+ * Initialize the default type libraries.
  *
  * Returns 0 in case of success and -1 in case of error.
  */
@@ -2878,7 +2878,7 @@ static int xmlRelaxNGTryCompile(xmlRelaxNGParserCtxtPtr ctxt,
                                 xmlRelaxNGDefinePtr def);
 
 /**
- * xmlRelaxNGIsCompileable:
+ * xmlRelaxNGIsCompilable:
  * @define:  the definition to check
  *
  * Check if a definition is nullable.
@@ -2886,7 +2886,7 @@ static int xmlRelaxNGTryCompile(xmlRelaxNGParserCtxtPtr ctxt,
  * Returns 1 if yes, 0 if no and -1 in case of error
  */
 static int
-xmlRelaxNGIsCompileable(xmlRelaxNGDefinePtr def)
+xmlRelaxNGIsCompilable(xmlRelaxNGDefinePtr def)
 {
     int ret = -1;
 
@@ -2901,7 +2901,7 @@ xmlRelaxNGIsCompileable(xmlRelaxNGDefinePtr def)
         return (0);
     switch (def->type) {
         case XML_RELAXNG_NOOP:
-            ret = xmlRelaxNGIsCompileable(def->content);
+            ret = xmlRelaxNGIsCompilable(def->content);
             break;
         case XML_RELAXNG_TEXT:
         case XML_RELAXNG_EMPTY:
@@ -2909,7 +2909,7 @@ xmlRelaxNGIsCompileable(xmlRelaxNGDefinePtr def)
             break;
         case XML_RELAXNG_ELEMENT:
             /*
-             * Check if the element content is compileable
+             * Check if the element content is compilable
              */
             if (((def->dflags & IS_NOT_COMPILABLE) == 0) &&
                 ((def->dflags & IS_COMPILABLE) == 0)) {
@@ -2917,7 +2917,7 @@ xmlRelaxNGIsCompileable(xmlRelaxNGDefinePtr def)
 
                 list = def->content;
                 while (list != NULL) {
-                    ret = xmlRelaxNGIsCompileable(list);
+                    ret = xmlRelaxNGIsCompilable(list);
                     if (ret != 1)
                         break;
                     list = list->next;
@@ -2943,13 +2943,13 @@ xmlRelaxNGIsCompileable(xmlRelaxNGDefinePtr def)
                                     def->name);
                 } else {
                     xmlGenericError(xmlGenericErrorContext,
-                                    "Problem in RelaxNGIsCompileable for element %s\n",
+                                    "Problem in RelaxNGIsCompilable for element %s\n",
                                     def->name);
                 }
 #endif
             }
             /*
-             * All elements return a compileable status unless they
+             * All elements return a compilable status unless they
              * are generic like anyName
              */
             if ((def->nameClass != NULL) || (def->name == NULL))
@@ -2968,7 +2968,7 @@ xmlRelaxNGIsCompileable(xmlRelaxNGDefinePtr def)
                 def->depth = -20;
                 list = def->content;
                 while (list != NULL) {
-                    ret = xmlRelaxNGIsCompileable(list);
+                    ret = xmlRelaxNGIsCompilable(list);
                     if (ret != 1)
                         break;
                     list = list->next;
@@ -2986,7 +2986,7 @@ xmlRelaxNGIsCompileable(xmlRelaxNGDefinePtr def)
 
                 list = def->content;
                 while (list != NULL) {
-                    ret = xmlRelaxNGIsCompileable(list);
+                    ret = xmlRelaxNGIsCompilable(list);
                     if (ret != 1)
                         break;
                     list = list->next;
@@ -3011,15 +3011,15 @@ xmlRelaxNGIsCompileable(xmlRelaxNGDefinePtr def)
 #ifdef DEBUG_COMPILE
     if (ret == 1) {
         xmlGenericError(xmlGenericErrorContext,
-                        "RelaxNGIsCompileable %s : true\n",
+                        "RelaxNGIsCompilable %s : true\n",
                         xmlRelaxNGDefName(def));
     } else if (ret == 0) {
         xmlGenericError(xmlGenericErrorContext,
-                        "RelaxNGIsCompileable %s : false\n",
+                        "RelaxNGIsCompilable %s : false\n",
                         xmlRelaxNGDefName(def));
     } else {
         xmlGenericError(xmlGenericErrorContext,
-                        "Problem in RelaxNGIsCompileable %s\n",
+                        "Problem in RelaxNGIsCompilable %s\n",
                         xmlRelaxNGDefName(def));
     }
 #endif
@@ -3047,7 +3047,7 @@ xmlRelaxNGCompile(xmlRelaxNGParserCtxtPtr ctxt, xmlRelaxNGDefinePtr def)
 
     switch (def->type) {
         case XML_RELAXNG_START:
-            if ((xmlRelaxNGIsCompileable(def) == 1) && (def->depth != -25)) {
+            if ((xmlRelaxNGIsCompilable(def) == 1) && (def->depth != -25)) {
                 xmlAutomataPtr oldam = ctxt->am;
                 xmlAutomataStatePtr oldstate = ctxt->state;
 
@@ -3273,7 +3273,7 @@ xmlRelaxNGTryCompile(xmlRelaxNGParserCtxtPtr ctxt, xmlRelaxNGDefinePtr def)
 
     if ((def->type == XML_RELAXNG_START) ||
         (def->type == XML_RELAXNG_ELEMENT)) {
-        ret = xmlRelaxNGIsCompileable(def);
+        ret = xmlRelaxNGIsCompilable(def);
         if ((def->dflags & IS_COMPILABLE) && (def->depth != -25)) {
             ctxt->am = NULL;
             ret = xmlRelaxNGCompile(ctxt, def);
@@ -3478,7 +3478,7 @@ xmlRelaxNGIsBlank(xmlChar * str)
  *
  * Applies algorithm from 4.3. datatypeLibrary attribute
  *
- * Returns the datatypeLibary value or NULL if not found
+ * Returns the datatypeLibrary value or NULL if not found
  */
 static xmlChar *
 xmlRelaxNGGetDataTypeLibrary(xmlRelaxNGParserCtxtPtr ctxt ATTRIBUTE_UNUSED,
@@ -3788,7 +3788,7 @@ static const xmlChar *invalidName = BAD_CAST "\1";
  * that if both lists do not accept the same QNames, it returns 1
  * If the 2 lists can accept the same QName the comparison returns 0
  *
- * Returns 1 disttinct, 0 if equal
+ * Returns 1 distinct, 0 if equal
  */
 static int
 xmlRelaxNGCompareNameClasses(xmlRelaxNGDefinePtr def1,
@@ -3889,7 +3889,7 @@ xmlRelaxNGCompareNameClasses(xmlRelaxNGDefinePtr def1,
  * is that if both lists do not accept the same QNames, it returns 1
  * If the 2 lists can accept the same QName the comparison returns 0
  *
- * Returns 1 disttinct, 0 if equal
+ * Returns 1 distinct, 0 if equal
  */
 static int
 xmlRelaxNGCompareElemDefLists(xmlRelaxNGParserCtxtPtr ctxt
@@ -4743,9 +4743,9 @@ xmlRelaxNGParseImportRefs(xmlRelaxNGParserCtxtPtr ctxt,
 /**
  * xmlRelaxNGProcessExternalRef:
  * @ctxt: the parser context
- * @node:  the externlRef node
+ * @node:  the externalRef node
  *
- * Process and compile an externlRef node
+ * Process and compile an externalRef node
  *
  * Returns the xmlRelaxNGDefinePtr or NULL in case of error
  */
@@ -5548,12 +5548,16 @@ xmlRelaxNGParsePatterns(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr nodes,
     while (nodes != NULL) {
         if (IS_RELAXNG(nodes, "element")) {
             cur = xmlRelaxNGParseElement(ctxt, nodes);
+            if (cur == NULL)
+                return (NULL);
             if (def == NULL) {
                 def = last = cur;
             } else {
                 if ((group == 1) && (def->type == XML_RELAXNG_ELEMENT) &&
                     (def == last)) {
                     def = xmlRelaxNGNewDefine(ctxt, nodes);
+                    if (def == NULL)
+                        return (NULL);
                     def->type = XML_RELAXNG_GROUP;
                     def->content = last;
                 }
@@ -6012,7 +6016,7 @@ xmlRelaxNGCheckCycles(xmlRelaxNGParserCtxtPtr ctxt,
  * @parent:  the parent definition
  * @prev:  the previous sibling definition
  *
- * Try to unlink a definition. If not possble make it a NOOP
+ * Try to unlink a definition. If not possible make it a NOOP
  *
  * Returns the new prev definition
  */
@@ -6395,7 +6399,10 @@ xmlRelaxNGCheckRules(xmlRelaxNGParserCtxtPtr ctxt,
                            NULL, NULL);
             }
             if ((!(flags & XML_RELAXNG_IN_ONEORMORE))
-                && (cur->name == NULL)) {
+                && cur->name == NULL
+                /* following is checking alternative name class readiness
+                   in case it went the "choice" route */
+                && cur->nameClass == NULL) {
                 if (cur->ns == NULL) {
                     xmlRngPErr(ctxt, cur->node, XML_RNGP_ANYNAME_ATTR_ANCESTOR,
                                "Found anyName attribute without oneOrMore ancestor\n",
@@ -6659,7 +6666,7 @@ xmlRelaxNGParseGrammar(xmlRelaxNGParserCtxtPtr ctxt, xmlNodePtr nodes)
  * @node:  the root node of the RelaxNG schema
  *
  * parse a Relax-NG definition resource and build an internal
- * xmlRelaxNG struture which can be used to validate instances.
+ * xmlRelaxNG structure which can be used to validate instances.
  *
  * Returns the internal XML RelaxNG structure built or
  *         NULL in case of error
@@ -7490,7 +7497,7 @@ xmlRelaxNGCleanupDoc(xmlRelaxNGParserCtxtPtr ctxt, xmlDocPtr doc)
  * @ctxt:  a Relax-NG parser context
  *
  * parse a schema definition resource and build an internal
- * XML Shema struture which can be used to validate instances.
+ * XML Schema structure which can be used to validate instances.
  *
  * Returns the internal XML RelaxNG structure built from the resource or
  *         NULL in case of error
@@ -8603,7 +8610,7 @@ xmlRelaxNGNormalize(xmlRelaxNGValidCtxtPtr ctxt, const xmlChar * str)
  * @type:  the datatype definition
  * @node:  the node
  *
- * Validate the given value against the dataype
+ * Validate the given value against the datatype
  *
  * Returns 0 if the validation succeeded or an error code.
  */
@@ -9476,7 +9483,17 @@ xmlRelaxNGValidateInterleave(xmlRelaxNGValidCtxtPtr ctxt,
             xmlRelaxNGFreeValidState(ctxt, oldstate);
             oldstate = ctxt->state;
             ctxt->state = NULL;
-            if (cur != NULL) {
+            if (cur != NULL
+                    /* there's a nasty violation of context-free unambiguities,
+                       since in open-name-class context, interleave in the
+                       production shall finish without caring about anything
+                       else that is OK to follow in that case -- it would
+                       otherwise get marked as "extra content" and would
+                       hence fail the validation, hence this perhaps
+                       dirty attempt to rectify such a situation */
+                    && (define->parent->type != XML_RELAXNG_DEF
+                        || !xmlStrEqual(define->parent->name,
+                                        (const xmlChar *) "open-name-class"))) {
                 VALID_ERR2(XML_RELAXNG_ERR_INTEREXTRA, cur->name);
                 ret = -1;
                 ctxt->state = oldstate;
@@ -9749,7 +9766,7 @@ xmlRelaxNGElementMatch(xmlRelaxNGValidCtxtPtr ctxt,
  * Find the "best" state in the ctxt->states list of states to report
  * errors about. I.e. a state with no element left in the child list
  * or the one with the less attributes left.
- * This is called only if a falidation error was detected
+ * This is called only if a validation error was detected
  *
  * Returns the index of the "best" state or -1 in case of error
  */
@@ -9891,7 +9908,6 @@ xmlRelaxNGValidateState(xmlRelaxNGValidCtxtPtr ctxt,
     ctxt->depth++;
     switch (define->type) {
         case XML_RELAXNG_EMPTY:
-            xmlRelaxNGSkipIgnored(ctxt, node);
             ret = 0;
             break;
         case XML_RELAXNG_NOT_ALLOWED:
@@ -10357,7 +10373,7 @@ xmlRelaxNGValidateState(xmlRelaxNGValidCtxtPtr ctxt,
 
                     /*
                      * Something we can optimize cleanly there is only one
-                     * possble branch out !
+                     * possible branch out !
                      */
                     if ((node->type == XML_TEXT_NODE) ||
                         (node->type == XML_CDATA_SECTION_NODE)) {
@@ -10610,7 +10626,7 @@ xmlRelaxNGValidateState(xmlRelaxNGValidCtxtPtr ctxt,
     if (define->name != NULL)
         xmlGenericError(xmlGenericErrorContext, "%s ", define->name);
     if (ret == 0)
-        xmlGenericError(xmlGenericErrorContext, "suceeded\n");
+        xmlGenericError(xmlGenericErrorContext, "succeeded\n");
     else
         xmlGenericError(xmlGenericErrorContext, "failed\n");
 #endif
diff --git a/save.h b/save.h
index 2c32a103998..192b6741335 100644
--- a/save.h
+++ b/save.h
@@ -1,7 +1,7 @@
 /*
  * Summary: Internal Interfaces for saving in libxml2
  * Description: this module describes a few interfaces which were
- *              addded along with the API changes in 2.9.0
+ *              added along with the API changes in 2.9.0
  *              those are private routines at this point
  *
  * Copy: See Copyright for the status of this software.
@@ -25,9 +25,10 @@ void xmlBufDumpNotationTable(xmlBufPtr buf, xmlNotationTablePtr table);
 void xmlBufDumpElementDecl(xmlBufPtr buf, xmlElementPtr elem);
 void xmlBufDumpAttributeDecl(xmlBufPtr buf, xmlAttributePtr attr);
 void xmlBufDumpEntityDecl(xmlBufPtr buf, xmlEntityPtr ent);
-xmlChar *xmlEncodeAttributeEntities(xmlDocPtr doc, const xmlChar *input);
 #endif
 
+xmlChar *xmlEncodeAttributeEntities(xmlDocPtr doc, const xmlChar *input);
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/schematron.c b/schematron.c
index 6200f2d4130..258ce4091f0 100644
--- a/schematron.c
+++ b/schematron.c
@@ -1068,7 +1068,7 @@ done:
  * @ctxt:  a schema validation context
  *
  * parse a schema definition resource and build an internal
- * XML Shema struture which can be used to validate instances.
+ * XML Schema structure which can be used to validate instances.
  *
  * Returns the internal XML Schematron structure built from the resource or
  *         NULL in case of error
@@ -1287,7 +1287,7 @@ xmlSchematronReportOutput(xmlSchematronValidCtxtPtr ctxt ATTRIBUTE_UNUSED,
  * Build the string being reported to the user.
  *
  * Returns a report string or NULL in case of error. The string needs
- *         to be deallocated by teh caller
+ *         to be deallocated by the caller
  */
 static xmlChar *
 xmlSchematronFormatReport(xmlSchematronValidCtxtPtr ctxt,
@@ -1591,7 +1591,7 @@ xmlSchematronNextNode(xmlNodePtr cur) {
  * xmlSchematronRunTest:
  * @ctxt:  the schema validation context
  * @test:  the current test
- * @instance:  the document instace tree
+ * @instance:  the document instance tree
  * @cur:  the current node in the instance
  *
  * Validate a rule against a tree instance at a given position
@@ -1655,7 +1655,7 @@ xmlSchematronRunTest(xmlSchematronValidCtxtPtr ctxt,
 /**
  * xmlSchematronValidateDoc:
  * @ctxt:  the schema validation context
- * @instance:  the document instace tree
+ * @instance:  the document instance tree
  *
  * Validate a tree instance against the schematron
  *
diff --git a/threads.c b/threads.c
index 6dc4233fc6d..30819e1a191 100644
--- a/threads.c
+++ b/threads.c
@@ -82,7 +82,7 @@ static int libxml_is_threaded = 1;
 
 /*
  * TODO: this module still uses malloc/free and not xmlMalloc/xmlFree
- *       to avoid some crazyness since xmlMalloc/xmlFree may actually
+ *       to avoid some craziness since xmlMalloc/xmlFree may actually
  *       be hosted on allocated blocks needing them for the allocation ...
  */
 
@@ -239,7 +239,7 @@ xmlMutexLock(xmlMutexPtr tok)
     if (acquire_sem(tok->sem) != B_NO_ERROR) {
 #ifdef DEBUG_THREADS
         xmlGenericError(xmlGenericErrorContext,
-                        "xmlMutexLock():BeOS:Couldn't aquire semaphore\n");
+                        "xmlMutexLock():BeOS:Couldn't acquire semaphore\n");
 #endif
     }
     tok->tid = find_thread(NULL);
diff --git a/timsort.h b/timsort.h
index 0c6346b8a6e..383584fb35f 100644
--- a/timsort.h
+++ b/timsort.h
@@ -59,7 +59,7 @@ typedef unsigned __int64 uint64_t;
 #define SORT_SWAP(x,y) {SORT_TYPE __SORT_SWAP_t = (x); (x) = (y); (y) = __SORT_SWAP_t;}
 
 
-/* Common, type-agnosting functions and constants that we don't want to declare twice. */
+/* Common, type-agnostic functions and constants that we don't want to declare twice. */
 #ifndef SORT_COMMON_H
 #define SORT_COMMON_H
 
@@ -74,7 +74,7 @@ typedef unsigned __int64 uint64_t;
 static int compute_minrun(const uint64_t);
 
 #ifndef CLZ
-#ifdef __GNUC__
+#if defined(__GNUC__) && ((__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ > 3))
 #define CLZ __builtin_clzll
 #else
 
@@ -404,7 +404,8 @@ static void TIM_SORT_MERGE(SORT_TYPE *dst, const TIM_SORT_RUN_T *stack, const in
     j = curr + A;
     k = curr + A + B;
 
-    while (k-- > curr) {
+    while (k > curr) {
+      k--;
       if ((i > 0) && (j > curr)) {
         if (SORT_CMP(dst[j - 1], storage[i - 1]) > 0) {
           dst[k] = dst[--j];
diff --git a/tree.c b/tree.c
index 3272122e16f..406235d9ee1 100644
--- a/tree.c
+++ b/tree.c
@@ -59,7 +59,7 @@ int __xmlRegisterCallbacks = 0;
  ************************************************************************/
 
 static xmlNsPtr
-xmlNewReconciliedNs(xmlDocPtr doc, xmlNodePtr tree, xmlNsPtr ns);
+xmlNewReconciledNs(xmlDocPtr doc, xmlNodePtr tree, xmlNsPtr ns);
 
 static xmlChar* xmlGetPropNodeValueInternal(const xmlAttr *prop);
 
@@ -181,7 +181,7 @@ xmlGetEntityFromDtd(const xmlDtd *dtd, const xmlChar *name) {
  * @dtd:  A pointer to the DTD to search
  * @name:  The entity name
  *
- * Do an entity lookup in the DTD pararmeter entity hash table and
+ * Do an entity lookup in the DTD parameter entity hash table and
  * return the corresponding entity, if found.
  *
  * Returns A pointer to the entity structure or NULL if not found.
@@ -2950,7 +2950,7 @@ xmlNewChild(xmlNodePtr parent, xmlNsPtr ns,
  * 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 destroyed prior to adding @prop.
  *
  * Returns the attribute being inserted or NULL in case of error.
  */
@@ -3664,7 +3664,9 @@ xmlNextElementSibling(xmlNodePtr node) {
 void
 xmlFreeNodeList(xmlNodePtr cur) {
     xmlNodePtr next;
+    xmlNodePtr parent;
     xmlDictPtr dict = NULL;
+    size_t depth = 0;
 
     if (cur == NULL) return;
     if (cur->type == XML_NAMESPACE_DECL) {
@@ -3680,16 +3682,21 @@ xmlFreeNodeList(xmlNodePtr cur) {
 	return;
     }
     if (cur->doc != NULL) dict = cur->doc->dict;
-    while (cur != NULL) {
+    while (1) {
+        while ((cur->children != NULL) &&
+               (cur->type != XML_DTD_NODE) &&
+               (cur->type != XML_ENTITY_REF_NODE)) {
+            cur = cur->children;
+            depth += 1;
+        }
+
         next = cur->next;
+        parent = cur->parent;
 	if (cur->type != XML_DTD_NODE) {
 
 	    if ((__xmlRegisterCallbacks) && (xmlDeregisterNodeDefaultValue))
 		xmlDeregisterNodeDefaultValue(cur);
 
-	    if ((cur->children != NULL) &&
-		(cur->type != XML_ENTITY_REF_NODE))
-		xmlFreeNodeList(cur->children);
 	    if (((cur->type == XML_ELEMENT_NODE) ||
 		 (cur->type == XML_XINCLUDE_START) ||
 		 (cur->type == XML_XINCLUDE_END)) &&
@@ -3720,7 +3727,16 @@ xmlFreeNodeList(xmlNodePtr cur) {
 		DICT_FREE(cur->name)
 	    xmlFree(cur);
 	}
-	cur = next;
+
+        if (next != NULL) {
+	    cur = next;
+        } else {
+            if ((depth == 0) || (parent == NULL))
+                break;
+            depth -= 1;
+            cur = parent;
+            cur->children = NULL;
+        }
     }
 }
 
@@ -4050,7 +4066,7 @@ xmlCopyPropInternal(xmlDocPtr doc, xmlNodePtr target, xmlAttrPtr cur) {
       } else {
         /*
          * we have to find something appropriate here since
-         * we cant be sure, that the namespce we found is identified
+         * we cant be sure, that the namespace we found is identified
          * by the prefix
          */
         if (xmlStrEqual(ns->href, cur->ns->href)) {
@@ -4058,10 +4074,10 @@ xmlCopyPropInternal(xmlDocPtr doc, xmlNodePtr target, xmlAttrPtr cur) {
           ret->ns = ns;
         } else {
           /*
-           * we are in trouble: we need a new reconcilied namespace.
+           * we are in trouble: we need a new reconciled namespace.
            * This is expensive
            */
-          ret->ns = xmlNewReconciliedNs(target->doc, target, cur->ns);
+          ret->ns = xmlNewReconciledNs(target->doc, target, cur->ns);
         }
       }
 
@@ -4154,8 +4170,8 @@ xmlCopyPropList(xmlNodePtr target, xmlAttrPtr cur) {
  * say RPM:Copyright without changing the namespace pointer to
  * something else can produce stale links. One way to do it is
  * to keep a reference counter but this doesn't work as soon
- * as one move the element or the subtree out of the scope of
- * the existing namespace. The actual solution seems to add
+ * as one moves the element or the subtree out of the scope of
+ * the existing namespace. The actual solution seems to be to add
  * a copy of the namespace at the top of the copied tree if
  * not available in the subtree.
  * Hence two functions, the public front-end call the inner ones
@@ -4280,7 +4296,7 @@ xmlStaticCopyNode(xmlNodePtr node, xmlDocPtr doc, xmlNodePtr parent,
 		while (root->parent != NULL) root = root->parent;
 		ret->ns = xmlNewNs(root, ns->href, ns->prefix);
 		} else {
-			ret->ns = xmlNewReconciliedNs(doc, ret, node->ns);
+			ret->ns = xmlNewReconciledNs(doc, ret, node->ns);
 	    }
 	} else {
 	    /*
@@ -4719,7 +4735,7 @@ xmlGetNodePath(const xmlNode *node)
 
             /*
              * Thumbler index computation
-	     * TODO: the ocurence test seems bogus for namespaced names
+	     * TODO: the occurrence test seems bogus for namespaced names
              */
             tmp = cur->prev;
             while (tmp != NULL) {
@@ -6214,7 +6230,7 @@ xmlSearchNsByHref(xmlDocPtr doc, xmlNodePtr node, const xmlChar * href)
 }
 
 /**
- * xmlNewReconciliedNs:
+ * xmlNewReconciledNs:
  * @doc:  the document
  * @tree:  a node expected to hold the new namespace
  * @ns:  the original namespace
@@ -6227,7 +6243,7 @@ xmlSearchNsByHref(xmlDocPtr doc, xmlNodePtr node, const xmlChar * href)
  * Returns the (new) namespace definition or NULL in case of error
  */
 static xmlNsPtr
-xmlNewReconciliedNs(xmlDocPtr doc, xmlNodePtr tree, xmlNsPtr ns) {
+xmlNewReconciledNs(xmlDocPtr doc, xmlNodePtr tree, xmlNsPtr ns) {
     xmlNsPtr def;
     xmlChar prefix[50];
     int counter = 1;
@@ -6235,14 +6251,14 @@ xmlNewReconciliedNs(xmlDocPtr doc, xmlNodePtr tree, xmlNsPtr ns) {
     if ((tree == NULL) || (tree->type != XML_ELEMENT_NODE)) {
 #ifdef DEBUG_TREE
         xmlGenericError(xmlGenericErrorContext,
-		"xmlNewReconciliedNs : tree == NULL\n");
+		"xmlNewReconciledNs : tree == NULL\n");
 #endif
 	return(NULL);
     }
     if ((ns == NULL) || (ns->type != XML_NAMESPACE_DECL)) {
 #ifdef DEBUG_TREE
         xmlGenericError(xmlGenericErrorContext,
-		"xmlNewReconciliedNs : ns == NULL\n");
+		"xmlNewReconciledNs : ns == NULL\n");
 #endif
 	return(NULL);
     }
@@ -6344,7 +6360,7 @@ xmlReconciliateNs(xmlDocPtr doc, xmlNodePtr tree) {
 	        /*
 		 * OK we need to recreate a new namespace definition
 		 */
-		n = xmlNewReconciliedNs(doc, tree, node->ns);
+		n = xmlNewReconciledNs(doc, tree, node->ns);
 		if (n != NULL) { /* :-( what if else ??? */
 		    /*
 		     * check if we need to grow the cache buffers.
@@ -6373,7 +6389,7 @@ xmlReconciliateNs(xmlDocPtr doc, xmlNodePtr tree) {
 	    }
 	}
 	/*
-	 * now check for namespace hold by attributes on the node.
+	 * now check for namespace held by attributes on the node.
 	 */
 	if (node->type == XML_ELEMENT_NODE) {
 	    attr = node->properties;
@@ -6408,7 +6424,7 @@ xmlReconciliateNs(xmlDocPtr doc, xmlNodePtr tree) {
 			/*
 			 * OK we need to recreate a new namespace definition
 			 */
-			n = xmlNewReconciliedNs(doc, tree, attr->ns);
+			n = xmlNewReconciledNs(doc, tree, attr->ns);
 			if (n != NULL) { /* :-( what if else ??? */
 			    /*
 			     * check if we need to grow the cache buffers.
@@ -7961,7 +7977,7 @@ xmlDOMWrapNsMapAddItem(xmlNsMapPtr *nsmap, int position,
 * 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
+* Returns the acquired ns struct or NULL in case of an API
 *         or internal error.
 */
 static xmlNsPtr
@@ -8575,7 +8591,7 @@ ns_next_prefix:
 }
 
 /*
-* xmlDOMWrapNSNormAquireNormalizedNs:
+* xmlDOMWrapNSNormAcquireNormalizedNs:
 * @doc: the doc
 * @elem: the element-node to declare namespaces on
 * @ns: the ns-struct to use for the search
@@ -8594,7 +8610,7 @@ ns_next_prefix:
 * Returns 0 if succeeded, -1 otherwise and on API/internal errors.
 */
 static int
-xmlDOMWrapNSNormAquireNormalizedNs(xmlDocPtr doc,
+xmlDOMWrapNSNormAcquireNormalizedNs(xmlDocPtr doc,
 				   xmlNodePtr elem,
 				   xmlNsPtr ns,
 				   xmlNsPtr *retNs,
@@ -8893,9 +8909,9 @@ next_ns_decl:
 		    }
 		}
 		/*
-		* Aquire a normalized ns-decl and add it to the map.
+		* Acquire a normalized ns-decl and add it to the map.
 		*/
-		if (xmlDOMWrapNSNormAquireNormalizedNs(doc, curElem,
+		if (xmlDOMWrapNSNormAcquireNormalizedNs(doc, curElem,
 			cur->ns, &ns,
 			&nsMap, depth,
 			ancestorsOnly,
@@ -9033,7 +9049,7 @@ xmlDOMWrapAdoptBranch(xmlDOMWrapCtxtPtr ctxt,
 	nsMap = (xmlNsMapPtr) ctxt->namespaceMap;
     /*
     * Disable search for ns-decls in the parent-axis of the
-    * desination element, if:
+    * destination element, if:
     * 1) there's no destination parent
     * 2) custom ns-reference handling is used
     */
@@ -9178,9 +9194,9 @@ xmlDOMWrapAdoptBranch(xmlDOMWrapCtxtPtr ctxt,
 		    cur->ns = ns;
 		} else {
 		    /*
-		    * Aquire a normalized ns-decl and add it to the map.
+		    * Acquire a normalized ns-decl and add it to the map.
 		    */
-		    if (xmlDOMWrapNSNormAquireNormalizedNs(destDoc,
+		    if (xmlDOMWrapNSNormAcquireNormalizedNs(destDoc,
 			/* ns-decls on curElem or on destDoc->oldNs */
 			destParent ? curElem : NULL,
 			cur->ns, &ns,
@@ -9234,7 +9250,7 @@ ns_end:
 		goto leave_node;
 	    case XML_ENTITY_REF_NODE:
 		/*
-		* Remove reference to the entitity-node.
+		* Remove reference to the entity-node.
 		*/
 		cur->content = NULL;
 		cur->children = NULL;
@@ -9468,7 +9484,7 @@ xmlDOMWrapCloneNode(xmlDOMWrapCtxtPtr ctxt,
 		}
 		memset(clone, 0, sizeof(xmlNode));
 		/*
-		* Set hierachical links.
+		* Set hierarchical links.
 		*/
 		if (resultClone != NULL) {
 		    clone->parent = parentClone;
@@ -9492,7 +9508,7 @@ xmlDOMWrapCloneNode(xmlDOMWrapCtxtPtr ctxt,
 		}
 		memset(clone, 0, sizeof(xmlAttr));
 		/*
-		* Set hierachical links.
+		* Set hierarchical links.
 		* TODO: Change this to add to the end of attributes.
 		*/
 		if (resultClone != NULL) {
@@ -9720,9 +9736,9 @@ xmlDOMWrapCloneNode(xmlDOMWrapCtxtPtr ctxt,
 	    clone->ns = ns;
 	} else {
 	    /*
-	    * Aquire a normalized ns-decl and add it to the map.
+	    * Acquire a normalized ns-decl and add it to the map.
 	    */
-	    if (xmlDOMWrapNSNormAquireNormalizedNs(destDoc,
+	    if (xmlDOMWrapNSNormAcquireNormalizedNs(destDoc,
 		/* ns-decls on curElem or on destDoc->oldNs */
 		destParent ? curElem : NULL,
 		cur->ns, &ns,
@@ -9959,7 +9975,7 @@ xmlDOMWrapAdoptAttr(xmlDOMWrapCtxtPtr ctxt,
 		break;
 	    case XML_ENTITY_REF_NODE:
 		/*
-		* Remove reference to the entitity-node.
+		* Remove reference to the entity-node.
 		*/
 		cur->content = NULL;
 		cur->children = NULL;
@@ -10097,7 +10113,7 @@ xmlDOMWrapAdoptNode(xmlDOMWrapCtxtPtr ctxt,
 		    break;
 	    case XML_ENTITY_REF_NODE:
 		/*
-		* Remove reference to the entitity-node.
+		* Remove reference to the entity-node.
 		*/
 		node->content = NULL;
 		node->children = NULL;
diff --git a/trionan.c b/trionan.c
index 6fbabb5dbd8..530b1c0f907 100644
--- a/trionan.c
+++ b/trionan.c
@@ -92,7 +92,7 @@
 
 /*
  * In ANSI/IEEE 754-1985 64-bits double format numbers have the
- * following properties (amoungst others)
+ * following properties (amongst others)
  *
  *   o FLT_RADIX == 2: binary encoding
  *   o DBL_MAX_EXP == 1024: 11 bits exponent, where one bit is used
diff --git a/uri.c b/uri.c
index 2cf8d9f199b..05d81e57633 100644
--- a/uri.c
+++ b/uri.c
@@ -22,7 +22,7 @@
  * MAX_URI_LENGTH:
  *
  * The definition of the URI regexp in the above RFC has no size limit
- * In practice they are usually relativey short except for the
+ * In practice they are usually relatively short except for the
  * data URI scheme as defined in RFC 2397. Even for data URI the usual
  * maximum size before hitting random practical limits is around 64 KB
  * and 4KB is usually a maximum admitted limit for proper operations.
@@ -325,16 +325,18 @@ static int
 xmlParse3986Port(xmlURIPtr uri, const char **str)
 {
     const char *cur = *str;
-    unsigned port = 0; /* unsigned for defined overflow behavior */
+    int port = 0;
 
     if (ISA_DIGIT(cur)) {
 	while (ISA_DIGIT(cur)) {
 	    port = port * 10 + (*cur - '0');
+            if (port > 99999999)
+                port = 99999999;
 
 	    cur++;
 	}
 	if (uri != NULL)
-	    uri->port = port & INT_MAX; /* port value modulo INT_MAX+1 */
+	    uri->port = port;
 	*str = cur;
 	return(0);
     }
@@ -436,7 +438,7 @@ xmlParse3986Host(xmlURIPtr uri, const char **str)
 
     host = cur;
     /*
-     * IPv6 and future adressing scheme are enclosed between brackets
+     * IPv6 and future addressing scheme are enclosed between brackets
      */
     if (*cur == '[') {
         cur++;
@@ -1456,7 +1458,7 @@ xmlNormalizeURIPath(char *path) {
               goto done_cd;
 	    (out++)[0] = (cur++)[0];
 	}
-	/* nomalize // */
+	/* normalize // */
 	while ((cur[0] == '/') && (cur[1] == '/'))
 	    cur++;
 
@@ -2150,7 +2152,7 @@ done:
  *     http://site1.com/docs/pic1.gif   http://site1.com/docs/pic1.gif
  *
  *
- * Note: if the URI reference is really wierd or complicated, it may be
+ * Note: if the URI reference is really weird or complicated, it may be
  *       worthwhile to first convert it into a "nice" one by calling
  *       xmlBuildURI (using 'base') before calling this routine,
  *       since this routine (for reasonable efficiency) assumes URI has
@@ -2461,7 +2463,7 @@ path_processing:
 	/* allocate space for leading '/' + path + string terminator */
 	uri->path = xmlMallocAtomic(len + 2);
 	if (uri->path == NULL) {
-	    xmlFreeURI(uri);	/* Guard agains 'out of memory' */
+	    xmlFreeURI(uri);	/* Guard against 'out of memory' */
 	    return(NULL);
 	}
 	/* Put in leading '/' plus path */
@@ -2476,7 +2478,7 @@ path_processing:
 	}
 	p = uri->path;
     }
-    /* Now change all occurences of '\' to '/' */
+    /* Now change all occurrences of '\' to '/' */
     while (*p != '\0') {
 	if (*p == '\\')
 	    *p = '/';
@@ -2526,7 +2528,7 @@ xmlPathToURI(const xmlChar *path)
         return(NULL);
 #if defined(_WIN32) && !defined(__CYGWIN__)
     /* xmlCanonicPath can return an URI on Windows (is that the intended behaviour?)
-       If 'cal' is a valid URI allready then we are done here, as continuing would make
+       If 'cal' is a valid URI already then we are done here, as continuing would make
        it invalid. */
     if ((uri = xmlParseURI((const char *) cal)) != NULL) {
 	xmlFreeURI(uri);
diff --git a/valid.c b/valid.c
index b1cfede2dbb..07963e74510 100644
--- a/valid.c
+++ b/valid.c
@@ -1099,14 +1099,22 @@ xmlCopyElementContent(xmlElementContentPtr cur) {
  */
 void
 xmlFreeDocElementContent(xmlDocPtr doc, xmlElementContentPtr cur) {
-    xmlElementContentPtr next;
     xmlDictPtr dict = NULL;
+    size_t depth = 0;
 
+    if (cur == NULL)
+        return;
     if (doc != NULL)
         dict = doc->dict;
 
-    while (cur != NULL) {
-        next = cur->c2;
+    while (1) {
+        xmlElementContentPtr parent;
+
+        while ((cur->c1 != NULL) || (cur->c2 != NULL)) {
+            cur = (cur->c1 != NULL) ? cur->c1 : cur->c2;
+            depth += 1;
+        }
+
 	switch (cur->type) {
 	    case XML_ELEMENT_CONTENT_PCDATA:
 	    case XML_ELEMENT_CONTENT_ELEMENT:
@@ -1119,7 +1127,6 @@ xmlFreeDocElementContent(xmlDocPtr doc, xmlElementContentPtr cur) {
 			NULL);
 		return;
 	}
-	if (cur->c1 != NULL) xmlFreeDocElementContent(doc, cur->c1);
 	if (dict) {
 	    if ((cur->name != NULL) && (!xmlDictOwns(dict, cur->name)))
 	        xmlFree((xmlChar *) cur->name);
@@ -1129,8 +1136,23 @@ xmlFreeDocElementContent(xmlDocPtr doc, xmlElementContentPtr cur) {
 	    if (cur->name != NULL) xmlFree((xmlChar *) cur->name);
 	    if (cur->prefix != NULL) xmlFree((xmlChar *) cur->prefix);
 	}
+        parent = cur->parent;
+        if ((depth == 0) || (parent == NULL)) {
+            xmlFree(cur);
+            break;
+        }
+        if (cur == parent->c1)
+            parent->c1 = NULL;
+        else
+            parent->c2 = NULL;
 	xmlFree(cur);
-	cur = next;
+
+        if (parent->c2 != NULL) {
+	    cur = parent->c2;
+        } else {
+            depth -= 1;
+            cur = parent;
+        }
     }
 }
 
@@ -1148,83 +1170,104 @@ xmlFreeElementContent(xmlElementContentPtr cur) {
 
 #ifdef LIBXML_OUTPUT_ENABLED
 /**
- * xmlDumpElementContent:
+ * xmlDumpElementOccur:
  * @buf:  An XML buffer
- * @content:  An element table
- * @glob: 1 if one must print the englobing parenthesis, 0 otherwise
+ * @cur:  An element table
  *
- * This will dump the content of the element table as an XML DTD definition
+ * Dump the occurence operator of an element.
  */
 static void
-xmlDumpElementContent(xmlBufferPtr buf, xmlElementContentPtr content, int glob) {
-    if (content == NULL) return;
-
-    if (glob) xmlBufferWriteChar(buf, "(");
-    switch (content->type) {
-        case XML_ELEMENT_CONTENT_PCDATA:
-            xmlBufferWriteChar(buf, "#PCDATA");
-	    break;
-	case XML_ELEMENT_CONTENT_ELEMENT:
-	    if (content->prefix != NULL) {
-		xmlBufferWriteCHAR(buf, content->prefix);
-		xmlBufferWriteChar(buf, ":");
-	    }
-	    xmlBufferWriteCHAR(buf, content->name);
-	    break;
-	case XML_ELEMENT_CONTENT_SEQ:
-	    if ((content->c1 != NULL) &&
-	        ((content->c1->type == XML_ELEMENT_CONTENT_OR) ||
-	         (content->c1->type == XML_ELEMENT_CONTENT_SEQ)))
-		xmlDumpElementContent(buf, content->c1, 1);
-	    else
-		xmlDumpElementContent(buf, content->c1, 0);
-            xmlBufferWriteChar(buf, " , ");
-	    if ((content->c2 != NULL) &&
-	        ((content->c2->type == XML_ELEMENT_CONTENT_OR) ||
-	         ((content->c2->type == XML_ELEMENT_CONTENT_SEQ) &&
-		  (content->c2->ocur != XML_ELEMENT_CONTENT_ONCE))))
-		xmlDumpElementContent(buf, content->c2, 1);
-	    else
-		xmlDumpElementContent(buf, content->c2, 0);
-	    break;
-	case XML_ELEMENT_CONTENT_OR:
-	    if ((content->c1 != NULL) &&
-	        ((content->c1->type == XML_ELEMENT_CONTENT_OR) ||
-	         (content->c1->type == XML_ELEMENT_CONTENT_SEQ)))
-		xmlDumpElementContent(buf, content->c1, 1);
-	    else
-		xmlDumpElementContent(buf, content->c1, 0);
-            xmlBufferWriteChar(buf, " | ");
-	    if ((content->c2 != NULL) &&
-	        ((content->c2->type == XML_ELEMENT_CONTENT_SEQ) ||
-	         ((content->c2->type == XML_ELEMENT_CONTENT_OR) &&
-		  (content->c2->ocur != XML_ELEMENT_CONTENT_ONCE))))
-		xmlDumpElementContent(buf, content->c2, 1);
-	    else
-		xmlDumpElementContent(buf, content->c2, 0);
-	    break;
-	default:
-	    xmlErrValid(NULL, XML_ERR_INTERNAL_ERROR,
-		    "Internal: ELEMENT content corrupted invalid type\n",
-		    NULL);
-    }
-    if (glob)
-        xmlBufferWriteChar(buf, ")");
-    switch (content->ocur) {
+xmlDumpElementOccur(xmlBufferPtr buf, xmlElementContentPtr cur) {
+    switch (cur->ocur) {
         case XML_ELEMENT_CONTENT_ONCE:
-	    break;
+            break;
         case XML_ELEMENT_CONTENT_OPT:
-	    xmlBufferWriteChar(buf, "?");
-	    break;
+            xmlBufferWriteChar(buf, "?");
+            break;
         case XML_ELEMENT_CONTENT_MULT:
-	    xmlBufferWriteChar(buf, "*");
-	    break;
+            xmlBufferWriteChar(buf, "*");
+            break;
         case XML_ELEMENT_CONTENT_PLUS:
-	    xmlBufferWriteChar(buf, "+");
-	    break;
+            xmlBufferWriteChar(buf, "+");
+            break;
     }
 }
 
+/**
+ * xmlDumpElementContent:
+ * @buf:  An XML buffer
+ * @content:  An element table
+ *
+ * This will dump the content of the element table as an XML DTD definition
+ */
+static void
+xmlDumpElementContent(xmlBufferPtr buf, xmlElementContentPtr content) {
+    xmlElementContentPtr cur;
+
+    if (content == NULL) return;
+
+    xmlBufferWriteChar(buf, "(");
+    cur = content;
+
+    do {
+        if (cur == NULL) return;
+
+        switch (cur->type) {
+            case XML_ELEMENT_CONTENT_PCDATA:
+                xmlBufferWriteChar(buf, "#PCDATA");
+                break;
+            case XML_ELEMENT_CONTENT_ELEMENT:
+                if (cur->prefix != NULL) {
+                    xmlBufferWriteCHAR(buf, cur->prefix);
+                    xmlBufferWriteChar(buf, ":");
+                }
+                xmlBufferWriteCHAR(buf, cur->name);
+                break;
+            case XML_ELEMENT_CONTENT_SEQ:
+            case XML_ELEMENT_CONTENT_OR:
+                if ((cur != content) &&
+                    (cur->parent != NULL) &&
+                    ((cur->type != cur->parent->type) ||
+                     (cur->ocur != XML_ELEMENT_CONTENT_ONCE)))
+                    xmlBufferWriteChar(buf, "(");
+                cur = cur->c1;
+                continue;
+            default:
+                xmlErrValid(NULL, XML_ERR_INTERNAL_ERROR,
+                        "Internal: ELEMENT cur corrupted invalid type\n",
+                        NULL);
+        }
+
+        while (cur != content) {
+            xmlElementContentPtr parent = cur->parent;
+
+            if (parent == NULL) return;
+
+            if (((cur->type == XML_ELEMENT_CONTENT_OR) ||
+                 (cur->type == XML_ELEMENT_CONTENT_SEQ)) &&
+                ((cur->type != parent->type) ||
+                 (cur->ocur != XML_ELEMENT_CONTENT_ONCE)))
+                xmlBufferWriteChar(buf, ")");
+            xmlDumpElementOccur(buf, cur);
+
+            if (cur == parent->c1) {
+                if (parent->type == XML_ELEMENT_CONTENT_SEQ)
+                    xmlBufferWriteChar(buf, " , ");
+                else if (parent->type == XML_ELEMENT_CONTENT_OR)
+                    xmlBufferWriteChar(buf, " | ");
+
+                cur = parent->c2;
+                break;
+            }
+
+            cur = parent;
+        }
+    } while (cur != content);
+
+    xmlBufferWriteChar(buf, ")");
+    xmlDumpElementOccur(buf, content);
+}
+
 /**
  * xmlSprintfElementContent:
  * @buf:  an output buffer
@@ -1703,7 +1746,7 @@ xmlDumpElementDecl(xmlBufferPtr buf, xmlElementPtr elem) {
 	    }
 	    xmlBufferWriteCHAR(buf, elem->name);
 	    xmlBufferWriteChar(buf, " ");
-	    xmlDumpElementContent(buf, elem->content, 1);
+	    xmlDumpElementContent(buf, elem->content);
 	    xmlBufferWriteChar(buf, ">\n");
 	    break;
 	case XML_ELEMENT_TYPE_ELEMENT:
@@ -1714,7 +1757,7 @@ xmlDumpElementDecl(xmlBufferPtr buf, xmlElementPtr elem) {
 	    }
 	    xmlBufferWriteCHAR(buf, elem->name);
 	    xmlBufferWriteChar(buf, " ");
-	    xmlDumpElementContent(buf, elem->content, 1);
+	    xmlDumpElementContent(buf, elem->content);
 	    xmlBufferWriteChar(buf, ">\n");
 	    break;
 	default:
@@ -2640,7 +2683,7 @@ xmlAddID(xmlValidCtxtPtr ctxt, xmlDocPtr doc, const xmlChar *value,
     ret->doc = doc;
     if ((ctxt != NULL) && (ctxt->vstateNr != 0)) {
 	/*
-	 * Operating in streaming mode, attr is gonna disapear
+	 * Operating in streaming mode, attr is gonna disappear
 	 */
 	if (doc->dict != NULL)
 	    ret->name = xmlDictLookup(doc->dict, attr->name, -1);
@@ -2968,7 +3011,7 @@ xmlAddRef(xmlValidCtxtPtr ctxt, xmlDocPtr doc, const xmlChar *value,
     ret->value = xmlStrdup(value);
     if ((ctxt != NULL) && (ctxt->vstateNr != 0)) {
 	/*
-	 * Operating in streaming mode, attr is gonna disapear
+	 * Operating in streaming mode, attr is gonna disappear
 	 */
 	ret->name = xmlStrdup(attr->name);
 	ret->attr = NULL;
diff --git a/xinclude.c b/xinclude.c
index 001e992f7c2..ba850fa538d 100644
--- a/xinclude.c
+++ b/xinclude.c
@@ -449,6 +449,10 @@ xmlXIncludeParseFile(xmlXIncludeCtxtPtr ctxt, const char *URL) {
 
     xmlCtxtUseOptions(pctxt, ctxt->parseFlags | XML_PARSE_DTDLOAD);
 
+    /* Don't read from stdin. */
+    if ((URL != NULL) && (strcmp(URL, "-") == 0))
+        URL = "./-";
+
     inputStream = xmlLoadExternalEntity(URL, NULL, pctxt);
     if (inputStream == NULL) {
 	xmlFreeParserCtxt(pctxt);
@@ -667,7 +671,7 @@ xmlXIncludeRecurseDoc(xmlXIncludeCtxtPtr ctxt, xmlDocPtr doc,
     int i;
 
     /*
-     * Avoid recursion in already substitued resources
+     * Avoid recursion in already substituted resources
     for (i = 0;i < ctxt->urlNr;i++) {
 	if (xmlStrEqual(doc->URL, ctxt->urlTab[i]))
 	    return;
@@ -752,7 +756,7 @@ xmlXIncludeRecurseDoc(xmlXIncludeCtxtPtr ctxt, xmlDocPtr doc,
  * @txt:  the new text node
  * @url:  the associated URL
  *
- * Add a new txtument to the list
+ * Add a new text node to the list
  */
 static void
 xmlXIncludeAddTxt(xmlXIncludeCtxtPtr ctxt, xmlNodePtr txt, const xmlURL url) {
@@ -1258,7 +1262,7 @@ struct _xmlXIncludeMergeData {
  * @doc:  the including doc
  * @nr: the entity name
  *
- * Inplements the merge of one entity
+ * Implements the merge of one entity
  */
 static void
 xmlXIncludeMergeEntity(void *payload, void *vdata,
@@ -1335,7 +1339,7 @@ error:
  * @doc:  the including doc
  * @from:  the included doc
  *
- * Inplements the entity merge
+ * Implements the entity merge
  *
  * Returns 0 if merge succeeded, -1 if some processing failed
  */
@@ -1806,6 +1810,10 @@ xmlXIncludeLoadTxt(xmlXIncludeCtxtPtr ctxt, const xmlChar *url, int nr) {
     xmlParserInputPtr inputStream;
     int xinclude_multibyte_fallback_used = 0;
 
+    /* Don't read from stdin. */
+    if (xmlStrcmp(url, BAD_CAST "-") == 0)
+        url = BAD_CAST "./-";
+
     /*
      * Check the URL and remove any fragment identifier
      */
@@ -1914,7 +1922,7 @@ xinclude_multibyte_fallback:
 
 	    cur = xmlStringCurrentChar(NULL, &content[i], &l);
 	    if (!IS_CHAR(cur)) {
-		/* Handle splitted multibyte char at buffer boundary */
+		/* Handle split multibyte char at buffer boundary */
 		if (((len - i) < 4) && (!xinclude_multibyte_fallback_used)) {
 		    xinclude_multibyte_fallback_used = 1;
 		    xmlBufShrink(buf->buffer, i);
@@ -1923,6 +1931,7 @@ xinclude_multibyte_fallback:
 		    xmlXIncludeErr(ctxt, ctxt->incTab[nr]->ref,
 				   XML_XINCLUDE_INVALID_CHAR,
 				   "%s contains invalid char\n", URL);
+		    xmlFreeParserCtxt(pctxt);
 		    xmlFreeParserInputBuffer(buf);
 		    xmlFree(URL);
 		    return(-1);
@@ -1963,6 +1972,7 @@ static int
 xmlXIncludeLoadFallback(xmlXIncludeCtxtPtr ctxt, xmlNodePtr fallback, int nr) {
     xmlXIncludeCtxtPtr newctxt;
     int ret = 0;
+    int oldNbErrors = ctxt->nbErrors;
 
     if ((fallback == NULL) || (fallback->type == XML_NAMESPACE_DECL) ||
         (ctxt == NULL))
@@ -1979,7 +1989,7 @@ xmlXIncludeLoadFallback(xmlXIncludeCtxtPtr ctxt, xmlNodePtr fallback, int nr) {
 	newctxt->base = xmlStrdup(ctxt->base);	/* Inherit the base from the existing context */
 	xmlXIncludeSetFlags(newctxt, ctxt->parseFlags);
 	ret = xmlXIncludeDoProcess(newctxt, ctxt->doc, fallback->children);
-	if (ctxt->nbErrors > 0)
+	if (ctxt->nbErrors > oldNbErrors)
 	    ret = -1;
 	else if (ret > 0)
 	    ret = 0;	/* xmlXIncludeDoProcess can return +ve number */
@@ -2133,7 +2143,7 @@ xmlXIncludeLoadNode(xmlXIncludeCtxtPtr ctxt, int nr) {
 	xmlNodePtr children;
 
 	/*
-	 * Time to try a fallback if availble
+	 * Time to try a fallback if available
 	 */
 #ifdef DEBUG_XINCLUDE
 	xmlGenericError(xmlGenericErrorContext, "error looking for fallback\n");
@@ -2178,7 +2188,7 @@ xmlXIncludeLoadNode(xmlXIncludeCtxtPtr ctxt, int nr) {
  * @ctxt: an XInclude context
  * @nr: the node number
  *
- * Inplement the infoset replacement for the given node
+ * Implement the infoset replacement for the given node
  *
  * Returns 0 if substitution succeeded, -1 if some processing failed
  */
diff --git a/xmlIO.c b/xmlIO.c
index 04d527019ba..bb07d40e8bc 100644
--- a/xmlIO.c
+++ b/xmlIO.c
@@ -185,9 +185,9 @@ static const char *IOerr[] = {
     "already connected",	/* EISCONN */
     "connection refused",	/* ECONNREFUSED */
     "unreachable network",	/* ENETUNREACH */
-    "adddress in use",		/* EADDRINUSE */
+    "address in use",		/* EADDRINUSE */
     "already in use",		/* EALREADY */
-    "unknown address familly",	/* EAFNOSUPPORT */
+    "unknown address family",	/* EAFNOSUPPORT */
 };
 
 #if defined(_WIN32) || defined (__DJGPP__) && !defined (__CYGWIN__)
@@ -2383,6 +2383,7 @@ xmlAllocOutputBuffer(xmlCharEncodingHandlerPtr encoder) {
     if (encoder != NULL) {
         ret->conv = xmlBufCreateSize(4000);
 	if (ret->conv == NULL) {
+            xmlBufFree(ret->buffer);
 	    xmlFree(ret);
 	    return(NULL);
 	}
@@ -2435,6 +2436,7 @@ xmlAllocOutputBufferInternal(xmlCharEncodingHandlerPtr encoder) {
     if (encoder != NULL) {
         ret->conv = xmlBufCreateSize(4000);
 	if (ret->conv == NULL) {
+            xmlBufFree(ret->buffer);
 	    xmlFree(ret);
 	    return(NULL);
 	}
@@ -3335,7 +3337,7 @@ xmlOutputBufferWrite(xmlOutputBufferPtr out, int len, const char *buf) {
     int nbchars = 0; /* number of chars to output to I/O */
     int ret;         /* return from function call */
     int written = 0; /* number of char written to I/O so far */
-    int chunk;       /* number of byte curreent processed from buf */
+    int chunk;       /* number of byte current processed from buf */
 
     if ((out == NULL) || (out->error)) return(-1);
     if (len < 0) return(0);
@@ -3372,20 +3374,26 @@ xmlOutputBufferWrite(xmlOutputBufferPtr out, int len, const char *buf) {
 		out->error = XML_IO_ENCODER;
 		return(-1);
 	    }
-	    nbchars = xmlBufUse(out->conv);
+            if (out->writecallback)
+	        nbchars = xmlBufUse(out->conv);
+            else
+                nbchars = ret;
 	} else {
 	    ret = xmlBufAdd(out->buffer, (const xmlChar *) buf, chunk);
 	    if (ret != 0)
 	        return(-1);
-	    nbchars = xmlBufUse(out->buffer);
+            if (out->writecallback)
+	        nbchars = xmlBufUse(out->buffer);
+            else
+                nbchars = chunk;
 	}
 	buf += chunk;
 	len -= chunk;
 
-	if ((nbchars < MINLEN) && (len <= 0))
-	    goto done;
-
 	if (out->writecallback) {
+            if ((nbchars < MINLEN) && (len <= 0))
+                goto done;
+
 	    /*
 	     * second write the stuff to the I/O channel
 	     */
@@ -3405,7 +3413,10 @@ xmlOutputBufferWrite(xmlOutputBufferPtr out, int len, const char *buf) {
 		out->error = XML_IO_WRITE;
 		return(ret);
 	    }
-	    out->written += ret;
+            if (out->written > INT_MAX - ret)
+                out->written = INT_MAX;
+            else
+                out->written += ret;
 	}
 	written += nbchars;
     } while (len > 0);
@@ -3485,7 +3496,7 @@ xmlEscapeContent(unsigned char* out, int *outlen,
  * @escaping:  an optional escaping function (or NULL)
  *
  * Write the content of the string in the output I/O buffer
- * This routine escapes the caracters and then handle the I18N
+ * This routine escapes the characters and then handle the I18N
  * transcoding from internal UTF-8
  * The buffer is lossless, i.e. will store in case of partial
  * or delayed writes.
@@ -3561,21 +3572,27 @@ xmlOutputBufferWriteEscape(xmlOutputBufferPtr out, const xmlChar *str,
 		out->error = XML_IO_ENCODER;
 		return(-1);
 	    }
-	    nbchars = xmlBufUse(out->conv);
+            if (out->writecallback)
+	        nbchars = xmlBufUse(out->conv);
+            else
+                nbchars = ret;
 	} else {
 	    ret = escaping(xmlBufEnd(out->buffer), &chunk, str, &cons);
 	    if ((ret < 0) || (chunk == 0)) /* chunk==0 => nothing done */
 	        return(-1);
             xmlBufAddLen(out->buffer, chunk);
-	    nbchars = xmlBufUse(out->buffer);
+            if (out->writecallback)
+	        nbchars = xmlBufUse(out->buffer);
+            else
+                nbchars = chunk;
 	}
 	str += cons;
 	len -= cons;
 
-	if ((nbchars < MINLEN) && (len <= 0))
-	    goto done;
-
 	if (out->writecallback) {
+            if ((nbchars < MINLEN) && (len <= 0))
+                goto done;
+
 	    /*
 	     * second write the stuff to the I/O channel
 	     */
@@ -3595,7 +3612,10 @@ xmlOutputBufferWriteEscape(xmlOutputBufferPtr out, const xmlChar *str,
 		out->error = XML_IO_WRITE;
 		return(ret);
 	    }
-	    out->written += ret;
+            if (out->written > INT_MAX - ret)
+                out->written = INT_MAX;
+            else
+                out->written += ret;
 	} else if (xmlBufAvail(out->buffer) < MINLEN) {
 	    xmlBufGrow(out->buffer, MINLEN);
 	}
@@ -3689,7 +3709,10 @@ xmlOutputBufferFlush(xmlOutputBufferPtr out) {
 	out->error = XML_IO_FLUSH;
 	return(ret);
     }
-    out->written += ret;
+    if (out->written > INT_MAX - ret)
+        out->written = INT_MAX;
+    else
+        out->written += ret;
 
 #ifdef DEBUG_INPUT
     xmlGenericError(xmlGenericErrorContext,
@@ -3937,7 +3960,7 @@ xmlResolveResourceFromCatalog(const char *URL, const char *ID,
  * @ID:  the System ID for the entity to load
  * @ctxt:  the context in which the entity is called or NULL
  *
- * By default we don't load external entitites, yet.
+ * By default we don't load external entities, yet.
  *
  * Returns a new allocated xmlParserInputPtr, or NULL.
  */
diff --git a/xmlmodule.c b/xmlmodule.c
index a95ab66acdf..1867a5e1603 100644
--- a/xmlmodule.c
+++ b/xmlmodule.c
@@ -67,7 +67,7 @@ xmlModuleErrMemory(xmlModulePtr module, const char *extra)
  *
  * Opens a module/shared library given its name or path
  * NOTE: that due to portability issues, behaviour can only be
- * guaranteed with @name using ASCII. We canot guarantee that
+ * guaranteed with @name using ASCII. We cannot guarantee that
  * an UTF-8 string would work, which is why name is a const char *
  * and not a const xmlChar * .
  * TODO: options are not yet implemented.
@@ -109,7 +109,7 @@ xmlModuleOpen(const char *name, int options ATTRIBUTE_UNUSED)
  *
  * Lookup for a symbol address in the given module
  * NOTE: that due to portability issues, behaviour can only be
- * guaranteed with @name using ASCII. We canot guarantee that
+ * guaranteed with @name using ASCII. We cannot guarantee that
  * an UTF-8 string would work, which is why name is a const char *
  * and not a const xmlChar * .
  *
diff --git a/xmlreader.c b/xmlreader.c
index db310c8fd82..f3891e43afe 100644
--- a/xmlreader.c
+++ b/xmlreader.c
@@ -238,6 +238,8 @@ xmlFreeID(xmlIDPtr id) {
 
     if (id->value != NULL)
 	DICT_FREE(id->value)
+    if (id->name != NULL)
+	DICT_FREE(id->name)
     xmlFree(id);
 }
 
@@ -271,6 +273,7 @@ xmlTextReaderRemoveID(xmlDocPtr doc, xmlAttrPtr attr) {
 	return(-1);
     }
     id->name = attr->name;
+    attr->name = NULL;
     id->attr = NULL;
     return(0);
 }
@@ -345,7 +348,9 @@ xmlTextReaderFreePropList(xmlTextReaderPtr reader, xmlAttrPtr cur) {
 static void
 xmlTextReaderFreeNodeList(xmlTextReaderPtr reader, xmlNodePtr cur) {
     xmlNodePtr next;
+    xmlNodePtr parent;
     xmlDictPtr dict;
+    size_t depth = 0;
 
     if ((reader != NULL) && (reader->ctxt != NULL))
 	dict = reader->ctxt->dict;
@@ -361,18 +366,21 @@ xmlTextReaderFreeNodeList(xmlTextReaderPtr reader, xmlNodePtr cur) {
 	xmlFreeDoc((xmlDocPtr) cur);
 	return;
     }
-    while (cur != NULL) {
+    while (1) {
+        while ((cur->type != XML_DTD_NODE) &&
+               (cur->type != XML_ENTITY_REF_NODE) &&
+               (cur->children != NULL) &&
+               (cur->children->parent == cur)) {
+            cur = cur->children;
+            depth += 1;
+        }
+
         next = cur->next;
+        parent = cur->parent;
+
 	/* unroll to speed up freeing the document */
 	if (cur->type != XML_DTD_NODE) {
 
-	    if ((cur->children != NULL) &&
-		(cur->type != XML_ENTITY_REF_NODE)) {
-		if (cur->children->parent == cur)
-		    xmlTextReaderFreeNodeList(reader, cur->children);
-		cur->children = NULL;
-	    }
-
 	    if ((__xmlRegisterCallbacks) && (xmlDeregisterNodeDefaultValue))
 		xmlDeregisterNodeDefaultValue(cur);
 
@@ -411,7 +419,16 @@ xmlTextReaderFreeNodeList(xmlTextReaderPtr reader, xmlNodePtr cur) {
 		xmlFree(cur);
 	    }
 	}
-	cur = next;
+
+        if (next != NULL) {
+	    cur = next;
+        } else {
+            if ((depth == 0) || (parent == NULL))
+                break;
+            depth -= 1;
+            cur = parent;
+            cur->children = NULL;
+        }
     }
 }
 
@@ -983,7 +1000,6 @@ xmlTextReaderValidatePush(xmlTextReaderPtr reader ATTRIBUTE_UNUSED) {
 	     */
 	    node = xmlTextReaderExpand(reader);
 	    if (node == NULL) {
-printf("Expand failed !\n");
 	        ret = -1;
 	    } else {
 		ret = xmlRelaxNGValidateFullElement(reader->rngValidCtxt,
@@ -1095,7 +1111,7 @@ xmlTextReaderValidateEntity(xmlTextReaderPtr reader) {
     do {
 	if (node->type == XML_ENTITY_REF_NODE) {
 	    /*
-	     * Case where the underlying tree is not availble, lookup the entity
+	     * Case where the underlying tree is not available, lookup the entity
 	     * and walk it.
 	     */
 	    if ((node->children == NULL) && (ctxt->sax != NULL) &&
@@ -1112,11 +1128,11 @@ xmlTextReaderValidateEntity(xmlTextReaderPtr reader) {
 		continue;
 	    } else {
 		/*
-		 * The error has probably be raised already.
+		 * The error has probably been raised already.
 		 */
 		if (node == oldnode)
 		    break;
-		node = node->next;
+                goto skip_children;
 	    }
 #ifdef LIBXML_REGEXP_ENABLED
 	} else if (node->type == XML_ELEMENT_NODE) {
@@ -1138,6 +1154,7 @@ xmlTextReaderValidateEntity(xmlTextReaderPtr reader) {
 	} else if (node->type == XML_ELEMENT_NODE) {
 	    xmlTextReaderValidatePop(reader);
 	}
+skip_children:
 	if (node->next != NULL) {
 	    node = node->next;
 	    continue;
@@ -1357,7 +1374,7 @@ get_next_node:
 
     /*
      * If we are not backtracking on ancestors or examined nodes,
-     * that the parser didn't finished or that we arent at the end
+     * that the parser didn't finished or that we aren't at the end
      * of stream, continue processing.
      */
     while ((reader->node != NULL) && (reader->node->next == NULL) &&
@@ -1548,7 +1565,7 @@ node_found:
 	(reader->node->type == XML_ENTITY_REF_NODE) &&
 	(reader->ctxt != NULL) && (reader->ctxt->replaceEntities == 1)) {
 	/*
-	 * Case where the underlying tree is not availble, lookup the entity
+	 * Case where the underlying tree is not available, lookup the entity
 	 * and walk it.
 	 */
 	if ((reader->node->children == NULL) && (reader->ctxt->sax != NULL) &&
@@ -1713,6 +1730,8 @@ xmlTextReaderReadInnerXml(xmlTextReaderPtr reader ATTRIBUTE_UNUSED)
     }
     doc = reader->node->doc;
     buff = xmlBufferCreate();
+    if (buff == NULL)
+        return NULL;
     for (cur_node = reader->node->children; cur_node != NULL;
          cur_node = cur_node->next) {
         /* XXX: Why is the node copied? */
@@ -1755,11 +1774,11 @@ xmlTextReaderReadOuterXml(xmlTextReaderPtr reader ATTRIBUTE_UNUSED)
     xmlBufferPtr buff;
     xmlDocPtr doc;
 
-    node = reader->node;
-    doc = node->doc;
     if (xmlTextReaderExpand(reader) == NULL) {
         return NULL;
     }
+    node = reader->node;
+    doc = node->doc;
     /* XXX: Why is the node copied? */
 	if (node->type == XML_DTD_NODE) {
 		node = (xmlNodePtr) xmlCopyDtd((xmlDtdPtr) node);
@@ -2262,17 +2281,19 @@ xmlFreeTextReader(xmlTextReaderPtr reader) {
     if (reader->ctxt != NULL) {
         if (reader->dict == reader->ctxt->dict)
 	    reader->dict = NULL;
-	if (reader->ctxt->myDoc != NULL) {
-	    if (reader->preserve == 0)
-		xmlTextReaderFreeDoc(reader, reader->ctxt->myDoc);
-	    reader->ctxt->myDoc = NULL;
-	}
 	if ((reader->ctxt->vctxt.vstateTab != NULL) &&
 	    (reader->ctxt->vctxt.vstateMax > 0)){
+            while (reader->ctxt->vctxt.vstateNr > 0)
+                xmlValidatePopElement(&reader->ctxt->vctxt, NULL, NULL, NULL);
 	    xmlFree(reader->ctxt->vctxt.vstateTab);
 	    reader->ctxt->vctxt.vstateTab = NULL;
 	    reader->ctxt->vctxt.vstateMax = 0;
 	}
+	if (reader->ctxt->myDoc != NULL) {
+	    if (reader->preserve == 0)
+		xmlTextReaderFreeDoc(reader, reader->ctxt->myDoc);
+	    reader->ctxt->myDoc = NULL;
+	}
 	if (reader->allocs & XML_TEXTREADER_CTXT)
 	    xmlFreeParserCtxt(reader->ctxt);
     }
@@ -2500,7 +2521,7 @@ xmlTextReaderGetAttributeNs(xmlTextReaderPtr reader, const xmlChar *localName,
  * parser, set its state to End Of File and return the input stream with
  * what is left that the parser did not use.
  *
- * The implementation is not good, the parser certainly procgressed past
+ * The implementation is not good, the parser certainly progressed past
  * what's left in reader->input, and there is an allocation problem. Best
  * would be to rewrite it differently.
  *
@@ -2882,8 +2903,8 @@ xmlTextReaderMoveToElement(xmlTextReaderPtr reader) {
  *
  * Parses an attribute value into one or more Text and EntityReference nodes.
  *
- * Returns 1 in case of success, 0 if the reader was not positionned on an
- *         ttribute node or all the attribute values have been read, or -1
+ * Returns 1 in case of success, 0 if the reader was not positioned on an
+ *         attribute node or all the attribute values have been read, or -1
  *         in case of error.
  */
 int
@@ -3920,7 +3941,7 @@ xmlTextReaderGetParserColumnNumber(xmlTextReaderPtr reader)
  * xmlTextReaderCurrentNode:
  * @reader:  the xmlTextReaderPtr used
  *
- * Hacking interface allowing to get the xmlNodePtr correponding to the
+ * Hacking interface allowing to get the xmlNodePtr corresponding to the
  * current node being accessed by the xmlTextReader. This is dangerous
  * because the underlying node may be destroyed on the next Reads.
  *
@@ -4032,7 +4053,7 @@ xmlTextReaderPreservePattern(xmlTextReaderPtr reader, const xmlChar *pattern,
  * xmlTextReaderCurrentDoc:
  * @reader:  the xmlTextReaderPtr used
  *
- * Hacking interface allowing to get the xmlDocPtr correponding to the
+ * Hacking interface allowing to get the xmlDocPtr corresponding to the
  * current document being accessed by the xmlTextReader.
  * NOTE: as a result of this call, the reader will not destroy the
  *       associated XML document and calling xmlFreeDoc() on the result
@@ -4135,11 +4156,11 @@ xmlTextReaderValidityStructuredRelay(void *userData, xmlErrorPtr error)
  *
  * Use RelaxNG to validate the document as it is processed.
  * Activation is only possible before the first Read().
- * if @schema is NULL, then RelaxNG validation is desactivated.
+ * if @schema is NULL, then RelaxNG validation is deactivated.
  @ The @schema should not be freed until the reader is deallocated
  * or its use has been deactivated.
  *
- * Returns 0 in case the RelaxNG validation could be (des)activated and
+ * Returns 0 in case the RelaxNG validation could be (de)activated and
  *         -1 in case of error.
  */
 int
@@ -4199,7 +4220,7 @@ xmlTextReaderRelaxNGSetSchema(xmlTextReaderPtr reader, xmlRelaxNGPtr schema) {
  *
  * Internal locator function for the readers
  *
- * Returns 0 in case the Schema validation could be (des)activated and
+ * Returns 0 in case the Schema validation could be (de)activated and
  *         -1 in case of error.
  */
 static int
@@ -4252,11 +4273,11 @@ xmlTextReaderLocator(void *ctx, const char **file, unsigned long *line) {
  *
  * Use XSD Schema to validate the document as it is processed.
  * Activation is only possible before the first Read().
- * if @schema is NULL, then Schema validation is desactivated.
- @ The @schema should not be freed until the reader is deallocated
+ * if @schema is NULL, then Schema validation is deactivated.
+ * The @schema should not be freed until the reader is deallocated
  * or its use has been deactivated.
  *
- * Returns 0 in case the Schema validation could be (des)activated and
+ * Returns 0 in case the Schema validation could be (de)activated and
  *         -1 in case of error.
  */
 int
diff --git a/xmlregexp.c b/xmlregexp.c
index d255fbf063e..c119ff1fb7f 100644
--- a/xmlregexp.c
+++ b/xmlregexp.c
@@ -2,7 +2,7 @@
  * regexp.c: generic and extensible Regular Expression engine
  *
  * Basically designed with the purpose of compiling regexps for
- * the variety of validation/shemas mechanisms now available in
+ * the variety of validation/schemas mechanisms now available in
  * XML related specifications these include:
  *    - XML-1.0 DTD validation
  *    - XML Schemas structure part 1
@@ -228,7 +228,7 @@ struct _xmlAutomataState {
     int maxTrans;
     int nbTrans;
     xmlRegTrans *trans;
-    /*  knowing states ponting to us can speed things up */
+    /*  knowing states pointing to us can speed things up */
     int maxTransTo;
     int nbTransTo;
     int *transTo;
@@ -545,6 +545,8 @@ xmlRegEpxFromParse(xmlRegParserCtxtPtr ctxt) {
 	if (transitions == NULL) {
 	    xmlFree(stateRemap);
 	    xmlFree(stringRemap);
+            for (i = 0;i < nbatoms;i++)
+		xmlFree(stringMap[i]);
 	    xmlFree(stringMap);
 	    xmlFree(ret);
 	    return(NULL);
@@ -588,7 +590,7 @@ xmlRegEpxFromParse(xmlRegParserCtxtPtr ctxt) {
 		targetno = stateRemap[trans->to];
 		/*
 		 * if the same atom can generate transitions to 2 different
-		 * states then it means the automata is not determinist and
+		 * states then it means the automata is not deterministic and
 		 * the compact form can't be used !
 		 */
 		prev = transitions[stateno * (nbatoms + 1) + atomno + 1];
@@ -829,7 +831,7 @@ xmlRegFreeAtom(xmlRegAtomPtr atom) {
 /**
  * xmlRegCopyAtom:
  * @ctxt:  the regexp parser context
- * @atom:  the oiginal atom
+ * @atom:  the original atom
  *
  * Allocate a new regexp range
  *
@@ -1547,7 +1549,7 @@ xmlFAGenerateTransitions(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr from,
     int nullable = 0;
 
     if (atom == NULL) {
-	ERROR("genrate transition: atom == NULL");
+	ERROR("generate transition: atom == NULL");
 	return(-1);
     }
     if (atom->type == XML_REGEXP_SUBREG) {
@@ -1622,7 +1624,7 @@ xmlFAGenerateTransitions(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr from,
 		    xmlRegAtomPtr copy;
 		    /*
 		     * duplicate a transition based on atom to count next
-		     * occurences after 1. We cannot loop to atom->start
+		     * occurrences after 1. We cannot loop to atom->start
 		     * directly because we need an epsilon transition to
 		     * newstate.
 		     */
@@ -1655,7 +1657,7 @@ xmlFAGenerateTransitions(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr from,
 		} else {
 		    /*
 		     * either we need the atom at least once or there
-		     * is an atom->start0 allowing to easilly plug the
+		     * is an atom->start0 allowing to easily plug the
 		     * epsilon transition.
 		     */
 		    counter = xmlRegGetCounter(ctxt);
@@ -1955,7 +1957,7 @@ xmlFAEliminateEpsilonTransitions(xmlRegParserCtxtPtr ctxt) {
      * Build the completed transitions bypassing the epsilons
      * Use a marking algorithm to avoid loops
      * Mark sink states too.
-     * Process from the latests states backward to the start when
+     * Process from the latest states backward to the start when
      * there is long cascading epsilon chains this minimize the
      * recursions and transition compares when adding the new ones
      */
@@ -2143,7 +2145,7 @@ xmlFACompareRanges(xmlRegRangePtr range1, xmlRegRangePtr range2) {
 	} else {
 	    /*
 	     * comparing a block range with anything else is way
-	     * too costly, and maintining the table is like too much
+	     * too costly, and maintaining the table is like too much
 	     * memory too, so let's force the automata to save state
 	     * here.
 	     */
@@ -2277,7 +2279,7 @@ xmlFACompareAtomTypes(xmlRegAtomType type1, xmlRegAtomType type2) {
     }
     switch (type1) {
         case XML_REGEXP_ANYSPACE: /* \s */
-	    /* can't be a letter, number, mark, pontuation, symbol */
+	    /* can't be a letter, number, mark, punctuation, symbol */
 	    if ((type2 == XML_REGEXP_NOTSPACE) ||
 		((type2 >= XML_REGEXP_LETTER) &&
 		 (type2 <= XML_REGEXP_LETTER_OTHERS)) ||
@@ -2294,7 +2296,7 @@ xmlFACompareAtomTypes(xmlRegAtomType type1, xmlRegAtomType type2) {
         case XML_REGEXP_NOTSPACE: /* \S */
 	    break;
         case XML_REGEXP_INITNAME: /* \l */
-	    /* can't be a number, mark, separator, pontuation, symbol or other */
+	    /* can't be a number, mark, separator, punctuation, symbol or other */
 	    if ((type2 == XML_REGEXP_NOTINITNAME) ||
 	        ((type2 >= XML_REGEXP_NUMBER) &&
 		 (type2 <= XML_REGEXP_NUMBER_OTHERS)) ||
@@ -2313,7 +2315,7 @@ xmlFACompareAtomTypes(xmlRegAtomType type1, xmlRegAtomType type2) {
         case XML_REGEXP_NOTINITNAME: /* \L */
 	    break;
         case XML_REGEXP_NAMECHAR: /* \c */
-	    /* can't be a mark, separator, pontuation, symbol or other */
+	    /* can't be a mark, separator, punctuation, symbol or other */
 	    if ((type2 == XML_REGEXP_NOTNAMECHAR) ||
 	        ((type2 >= XML_REGEXP_MARK) &&
 		 (type2 <= XML_REGEXP_MARK_ENCLOSING)) ||
@@ -2330,7 +2332,7 @@ xmlFACompareAtomTypes(xmlRegAtomType type1, xmlRegAtomType type2) {
         case XML_REGEXP_NOTNAMECHAR: /* \C */
 	    break;
         case XML_REGEXP_DECIMAL: /* \d */
-	    /* can't be a letter, mark, separator, pontuation, symbol or other */
+	    /* can't be a letter, mark, separator, punctuation, symbol or other */
 	    if ((type2 == XML_REGEXP_NOTDECIMAL) ||
 	        (type2 == XML_REGEXP_REALCHAR) ||
 		((type2 >= XML_REGEXP_LETTER) &&
@@ -2350,7 +2352,7 @@ xmlFACompareAtomTypes(xmlRegAtomType type1, xmlRegAtomType type2) {
         case XML_REGEXP_NOTDECIMAL: /* \D */
 	    break;
         case XML_REGEXP_REALCHAR: /* \w */
-	    /* can't be a mark, separator, pontuation, symbol or other */
+	    /* can't be a mark, separator, punctuation, symbol or other */
 	    if ((type2 == XML_REGEXP_NOTDECIMAL) ||
 	        ((type2 >= XML_REGEXP_MARK) &&
 		 (type2 <= XML_REGEXP_MARK_ENCLOSING)) ||
@@ -2526,9 +2528,18 @@ xmlFACompareAtoms(xmlRegAtomPtr atom1, xmlRegAtomPtr atom2, int deep) {
         case XML_REGEXP_STRING:
             if (!deep)
                 ret = (atom1->valuep != atom2->valuep);
-            else
-                ret = xmlRegStrEqualWildcard((xmlChar *)atom1->valuep,
-                                             (xmlChar *)atom2->valuep);
+            else {
+                xmlChar *val1 = (xmlChar *)atom1->valuep;
+                xmlChar *val2 = (xmlChar *)atom2->valuep;
+                int compound1 = (xmlStrchr(val1, '|') != NULL);
+                int compound2 = (xmlStrchr(val2, '|') != NULL);
+
+                /* Ignore negative match flag for ##other namespaces */
+                if (compound1 != compound2)
+                    return(0);
+
+                ret = xmlRegStrEqualWildcard(val1, val2);
+            }
 	    break;
         case XML_REGEXP_EPSILON:
 	    goto not_determinist;
@@ -3564,9 +3575,9 @@ xmlRegNewExecCtxt(xmlRegexpPtr comp, xmlRegExecCallbacks callback, void *data) {
 
 /**
  * xmlRegFreeExecCtxt:
- * @exec: a regular expression evaulation context
+ * @exec: a regular expression evaluation context
  *
- * Free the structures associated to a regular expression evaulation context.
+ * Free the structures associated to a regular expression evaluation context.
  */
 void
 xmlRegFreeExecCtxt(xmlRegExecCtxtPtr exec) {
@@ -3640,7 +3651,7 @@ xmlFARegExecSaveInputString(xmlRegExecCtxtPtr exec, const xmlChar *value,
  * @valStr:  the validation string
  *
  * Checks if both strings are equal or have the same content. "*"
- * can be used as a wildcard in @valStr; "|" is used as a seperator of
+ * can be used as a wildcard in @valStr; "|" is used as a separator of
  * substrings in both @expStr and @valStr.
  *
  * Returns 1 if the comparison is satisfied and the number of substrings
@@ -5347,9 +5358,12 @@ xmlFAParseBranch(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr to) {
 
     previous = ctxt->state;
     ret = xmlFAParsePiece(ctxt);
-    if (ret != 0) {
+    if (ret == 0) {
+        /* Empty branch */
+	xmlFAGenerateEpsilonTransition(ctxt, previous, to);
+    } else {
 	if (xmlFAGenerateTransitions(ctxt, previous,
-	        (CUR=='|' || CUR==')') ? to : NULL, ctxt->atom) < 0)
+	        (CUR=='|' || CUR==')' || CUR==0) ? to : NULL, ctxt->atom) < 0)
 	    return(-1);
 	previous = ctxt->state;
 	ctxt->atom = NULL;
@@ -5358,7 +5372,8 @@ xmlFAParseBranch(xmlRegParserCtxtPtr ctxt, xmlRegStatePtr to) {
 	ret = xmlFAParsePiece(ctxt);
 	if (ret != 0) {
 	    if (xmlFAGenerateTransitions(ctxt, previous,
-	            (CUR=='|' || CUR==')') ? to : NULL, ctxt->atom) < 0)
+	            (CUR=='|' || CUR==')' || CUR==0) ? to : NULL,
+                    ctxt->atom) < 0)
 		    return(-1);
 	    previous = ctxt->state;
 	    ctxt->atom = NULL;
@@ -5395,10 +5410,6 @@ xmlFAParseRegExp(xmlRegParserCtxtPtr ctxt, int top) {
     end = ctxt->state;
     while ((CUR == '|') && (ctxt->error == 0)) {
 	NEXT;
-	if (CUR == 0) {
-	    ERROR("expecting a branch after |")
-	    return;
-	}
 	ctxt->state = start;
 	ctxt->end = NULL;
 	xmlFAParseBranch(ctxt, end);
@@ -5537,6 +5548,8 @@ xmlRegexpIsDeterminist(xmlRegexpPtr comp) {
 	return(comp->determinist);
 
     am = xmlNewAutomata();
+    if (am == NULL)
+        return(-1);
     if (am->states != NULL) {
 	int i;
 
@@ -5864,8 +5877,8 @@ xmlAutomataNewNegTrans(xmlAutomataPtr am, xmlAutomataStatePtr from,
  * @to: the target point of the transition or NULL
  * @token: the input string associated to that transition
  * @token2: the second input string associated to that transition
- * @min:  the minimum successive occurences of token
- * @max:  the maximum successive occurences of token
+ * @min:  the minimum successive occurrences of token
+ * @max:  the maximum successive occurrences of token
  * @data:  data associated to the transition
  *
  * If @to is NULL, this creates first a new target state in the automata
@@ -5951,8 +5964,8 @@ xmlAutomataNewCountTrans2(xmlAutomataPtr am, xmlAutomataStatePtr from,
  * @from: the starting point of the transition
  * @to: the target point of the transition or NULL
  * @token: the input string associated to that transition
- * @min:  the minimum successive occurences of token
- * @max:  the maximum successive occurences of token
+ * @min:  the minimum successive occurrences of token
+ * @max:  the maximum successive occurrences of token
  * @data:  data associated to the transition
  *
  * If @to is NULL, this creates first a new target state in the automata
@@ -6018,8 +6031,8 @@ xmlAutomataNewCountTrans(xmlAutomataPtr am, xmlAutomataStatePtr from,
  * @to: the target point of the transition or NULL
  * @token: the input string associated to that transition
  * @token2: the second input string associated to that transition
- * @min:  the minimum successive occurences of token
- * @max:  the maximum successive occurences of token
+ * @min:  the minimum successive occurrences of token
+ * @max:  the maximum successive occurrences of token
  * @data:  data associated to the transition
  *
  * If @to is NULL, this creates first a new target state in the automata
@@ -6098,8 +6111,8 @@ xmlAutomataNewOnceTrans2(xmlAutomataPtr am, xmlAutomataStatePtr from,
  * @from: the starting point of the transition
  * @to: the target point of the transition or NULL
  * @token: the input string associated to that transition
- * @min:  the minimum successive occurences of token
- * @max:  the maximum successive occurences of token
+ * @min:  the minimum successive occurrences of token
+ * @max:  the maximum successive occurrences of token
  * @data:  data associated to the transition
  *
  * If @to is NULL, this creates first a new target state in the automata
@@ -6616,7 +6629,7 @@ xmlExpHashGetEntry(xmlExpCtxtPtr ctxt, xmlExpNodeType type,
         /* OR reduction rule 1 */
 	/* a | a reduced to a */
         if (left == right) {
-	    left->ref--;
+	    xmlExpFree(ctxt, right);
 	    return(left);
 	}
         /* OR canonicalization rule 1 */
@@ -7075,7 +7088,7 @@ xmlExpGetStart(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp,
  * xmlExpIsNillable:
  * @exp: the expression
  *
- * Finds if the expression is nillable, i.e. if it accepts the empty sequqnce
+ * Finds if the expression is nillable, i.e. if it accepts the empty sequence
  *
  * Returns 1 if nillable, 0 if not and -1 in case of error
  */
@@ -7258,7 +7271,7 @@ static xmlExpNodePtr xmlExpExpDeriveInt(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp,
  * so that sub{n} subsume exp
  *
  * Returns the multiple value if successful, 0 if it is not a multiple
- *         and -1 in case of internel error.
+ *         and -1 in case of internal error.
  */
 
 static int
@@ -7426,7 +7439,7 @@ xmlExpExpDeriveInt(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, xmlExpNodePtr sub) {
 	        return(forbiddenExp);
 	    }
 #ifdef DEBUG_DERIV
-	    printf("Compex exp vs Atom -> Forbid\n");
+	    printf("Complex exp vs Atom -> Forbid\n");
 #endif
 	    return(forbiddenExp);
         case XML_EXP_SEQ:
@@ -7770,7 +7783,7 @@ xmlExpExpDeriveInt(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, xmlExpNodePtr sub) {
  *
  * Evaluates the expression resulting from @exp consuming a sub expression @sub
  * Based on algebraic derivation and sometimes direct Brzozowski derivation
- * it usually tatkes less than linear time and can handle expressions generating
+ * it usually takes less than linear time and can handle expressions generating
  * infinite languages.
  *
  * Returns the resulting expression or NULL in case of internal error, the
@@ -7792,7 +7805,7 @@ xmlExpExpDerive(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, xmlExpNodePtr sub) {
     }
     if (xmlExpCheckCard(exp, sub) == 0) {
 #ifdef DEBUG_DERIV
-	printf("sub generate longuer sequances than exp : can't subsume\n");
+	printf("sub generate longer sequences than exp : can't subsume\n");
 #endif
         return(forbiddenExp);
     }
@@ -7805,7 +7818,7 @@ xmlExpExpDerive(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, xmlExpNodePtr sub) {
  * @exp: the englobing expression
  * @sub: the subexpression
  *
- * Check whether @exp accepts all the languages accexpted by @sub
+ * Check whether @exp accepts all the languages accepted by @sub
  * the input being a subexpression.
  *
  * Returns 1 if true 0 if false and -1 in case of failure.
@@ -7832,7 +7845,7 @@ xmlExpSubsume(xmlExpCtxtPtr ctxt, xmlExpNodePtr exp, xmlExpNodePtr sub) {
     }
     if (xmlExpCheckCard(exp, sub) == 0) {
 #ifdef DEBUG_DERIV
-	printf("sub generate longuer sequances than exp : can't subsume\n");
+	printf("sub generate longer sequences than exp : can't subsume\n");
 #endif
         return(0);
     }
diff --git a/xmlsave.c b/xmlsave.c
index 7a05d832495..fa009153718 100644
--- a/xmlsave.c
+++ b/xmlsave.c
@@ -1,5 +1,5 @@
 /*
- * xmlsave.c: Implemetation of the document serializer
+ * xmlsave.c: Implementation of the document serializer
  *
  * See Copyright for the status of this software.
  *
@@ -83,7 +83,6 @@ struct _xmlSaveCtxt {
     const xmlChar *encoding;
     xmlCharEncodingHandlerPtr handler;
     xmlOutputBufferPtr buf;
-    xmlDocPtr doc;
     int options;
     int level;
     int format;
@@ -356,7 +355,7 @@ xmlSaveCtxtInit(xmlSaveCtxtPtr ctxt)
 /**
  * xmlFreeSaveCtxt:
  *
- * Free a saving context, destroying the ouptut in any remaining buffer
+ * Free a saving context, destroying the output in any remaining buffer
  */
 static void
 xmlFreeSaveCtxt(xmlSaveCtxtPtr ctxt)
@@ -707,7 +706,6 @@ static void
 xmlDtdDumpOutput(xmlSaveCtxtPtr ctxt, xmlDtdPtr dtd) {
     xmlOutputBufferPtr buf;
     int format, level;
-    xmlDocPtr doc;
 
     if (dtd == NULL) return;
     if ((ctxt == NULL) || (ctxt->buf == NULL))
@@ -742,14 +740,11 @@ xmlDtdDumpOutput(xmlSaveCtxtPtr ctxt, xmlDtdPtr dtd) {
     }
     format = ctxt->format;
     level = ctxt->level;
-    doc = ctxt->doc;
     ctxt->format = 0;
     ctxt->level = -1;
-    ctxt->doc = dtd->doc;
     xmlNodeListDumpOutput(ctxt, dtd->children);
     ctxt->format = format;
     ctxt->level = level;
-    ctxt->doc = doc;
     xmlOutputBufferWrite(buf, 2, "]>");
 }
 
@@ -2191,9 +2186,9 @@ xmlAttrSerializeTxtContent(xmlBufferPtr buf, xmlDocPtr doc,
  *
  * Dump an XML node, recursive behaviour,children are printed too.
  * Note that @format = 1 provide node indenting only if xmlIndentTreeOutput = 1
- * or xmlKeepBlanksDefault(0) was called
+ * or xmlKeepBlanksDefault(0) was called.
  * Since this is using xmlBuffer structures it is limited to 2GB and somehow
- * deprecated, use xmlBufNodeDump() instead.
+ * deprecated, use xmlNodeDumpOutput() instead.
  *
  * Returns the number of bytes written to the buffer or -1 in case of error
  */
@@ -2360,7 +2355,6 @@ xmlNodeDumpOutput(xmlOutputBufferPtr buf, xmlDocPtr doc, xmlNodePtr cur,
         encoding = "UTF-8";
 
     memset(&ctxt, 0, sizeof(ctxt));
-    ctxt.doc = doc;
     ctxt.buf = buf;
     ctxt.level = level;
     ctxt.format = format ? 1 : 0;
@@ -2446,7 +2440,6 @@ xmlDocDumpFormatMemoryEnc(xmlDocPtr out_doc, xmlChar **doc_txt_ptr,
     }
 
     memset(&ctxt, 0, sizeof(ctxt));
-    ctxt.doc = out_doc;
     ctxt.buf = out_buff;
     ctxt.level = 0;
     ctxt.format = format ? 1 : 0;
@@ -2565,7 +2558,6 @@ xmlDocFormatDump(FILE *f, xmlDocPtr cur, int format) {
     buf = xmlOutputBufferCreateFile(f, handler);
     if (buf == NULL) return(-1);
     memset(&ctxt, 0, sizeof(ctxt));
-    ctxt.doc = cur;
     ctxt.buf = buf;
     ctxt.level = 0;
     ctxt.format = format ? 1 : 0;
@@ -2596,7 +2588,7 @@ xmlDocDump(FILE *f, xmlDocPtr cur) {
  * xmlSaveFileTo:
  * @buf:  an output I/O buffer
  * @cur:  the document
- * @encoding:  the encoding if any assuming the I/O layer handles the trancoding
+ * @encoding:  the encoding if any assuming the I/O layer handles the transcoding
  *
  * Dump an XML document to an I/O buffer.
  * Warning ! This call xmlOutputBufferClose() on buf which is not available
@@ -2615,7 +2607,6 @@ xmlSaveFileTo(xmlOutputBufferPtr buf, xmlDocPtr cur, const char *encoding) {
 	return(-1);
     }
     memset(&ctxt, 0, sizeof(ctxt));
-    ctxt.doc = cur;
     ctxt.buf = buf;
     ctxt.level = 0;
     ctxt.format = 0;
@@ -2631,7 +2622,7 @@ xmlSaveFileTo(xmlOutputBufferPtr buf, xmlDocPtr cur, const char *encoding) {
  * xmlSaveFormatFileTo:
  * @buf:  an output I/O buffer
  * @cur:  the document
- * @encoding:  the encoding if any assuming the I/O layer handles the trancoding
+ * @encoding:  the encoding if any assuming the I/O layer handles the transcoding
  * @format: should formatting spaces been added
  *
  * Dump an XML document to an I/O buffer.
@@ -2655,7 +2646,6 @@ xmlSaveFormatFileTo(xmlOutputBufferPtr buf, xmlDocPtr cur,
 	return(-1);
     }
     memset(&ctxt, 0, sizeof(ctxt));
-    ctxt.doc = cur;
     ctxt.buf = buf;
     ctxt.level = 0;
     ctxt.format = format ? 1 : 0;
@@ -2710,7 +2700,6 @@ xmlSaveFormatFileEnc( const char * filename, xmlDocPtr cur,
     buf = xmlOutputBufferCreateFilename(filename, handler, cur->compression);
     if (buf == NULL) return(-1);
     memset(&ctxt, 0, sizeof(ctxt));
-    ctxt.doc = cur;
     ctxt.buf = buf;
     ctxt.level = 0;
     ctxt.format = format ? 1 : 0;
diff --git a/xmlschemas.c b/xmlschemas.c
index 019988aafdc..d19de6df5f5 100644
--- a/xmlschemas.c
+++ b/xmlschemas.c
@@ -22,7 +22,7 @@
  *     acquisition episode (xmlSchemaAugmentIDC).
  *
  * NOTES:
- *   - Elimated item creation for: <restriction>, <extension>,
+ *   - Eliminated item creation for: <restriction>, <extension>,
  *     <simpleContent>, <complexContent>, <list>, <union>
  *
  * PROBLEMS:
@@ -2780,8 +2780,6 @@ xmlSchemaFacetErr(xmlSchemaAbstractCtxtPtr actxt,
 /**
  * xmlSchemaPMissingAttrErr:
  * @ctxt: the schema validation context
- * @ownerDes: the designation of  the owner
- * @ownerName: the name of the owner
  * @ownerItem: the owner as a schema object
  * @ownerElem: the owner as an element node
  * @node: the parent element node of the missing attribute node
@@ -2815,7 +2813,6 @@ xmlSchemaPMissingAttrErr(xmlSchemaParserCtxtPtr ctxt,
  * xmlSchemaPResCompAttrErr:
  * @ctxt: the schema validation context
  * @error: the error code
- * @ownerDes: the designation of  the owner
  * @ownerItem: the owner as a schema object
  * @ownerElem: the owner as an element node
  * @name: the name of the attribute holding the QName
@@ -2897,7 +2894,6 @@ xmlSchemaPCustomAttrErr(xmlSchemaParserCtxtPtr ctxt,
  * xmlSchemaPIllegalAttrErr:
  * @ctxt: the schema parser context
  * @error: the error code
- * @ownerDes: the designation of the attribute's owner
  * @ownerItem: the attribute's owner item
  * @attr: the illegal attribute node
  *
@@ -3109,7 +3105,6 @@ xmlSchemaPMutualExclAttrErr(xmlSchemaParserCtxtPtr ctxt,
  * @ctxt:  the schema validation context
  * @error: the error code
  * @type: the type specifier
- * @ownerDes: the designation of the owner
  * @ownerItem: the schema object if existent
  * @node: the validated node
  * @value: the validated value
@@ -3202,7 +3197,6 @@ xmlSchemaPSimpleTypeErr(xmlSchemaParserCtxtPtr ctxt,
  * xmlSchemaPContentErr:
  * @ctxt: the schema parser context
  * @error: the error code
- * @onwerDes: the designation of the holder of the content
  * @ownerItem: the owner item of the holder of the content
  * @ownerElem: the node of the holder of the content
  * @child: the invalid child node
@@ -4307,7 +4301,7 @@ xmlSchemaAnnotDump(FILE * output, xmlSchemaAnnotPtr annot)
  * xmlSchemaContentModelDump:
  * @particle: the schema particle
  * @output: the file output
- * @depth: the depth used for intentation
+ * @depth: the depth used for indentation
  *
  * Dump a SchemaType structure
  */
@@ -5155,7 +5149,7 @@ subschemas:
  * Add an XML schema annotation declaration
  * *WARNING* this interface is highly subject to change
  *
- * Returns the new struture or NULL in case of error
+ * Returns the new structure or NULL in case of error
  */
 static xmlSchemaNotationPtr
 xmlSchemaAddNotation(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema,
@@ -5189,10 +5183,10 @@ xmlSchemaAddNotation(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema,
  * @name:  the item name
  * @namespace:  the namespace
  *
- * Add an XML schema Attrribute declaration
+ * Add an XML schema Attribute declaration
  * *WARNING* this interface is highly subject to change
  *
- * Returns the new struture or NULL in case of error
+ * Returns the new structure or NULL in case of error
  */
 static xmlSchemaAttributePtr
 xmlSchemaAddAttribute(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema,
@@ -5230,10 +5224,10 @@ xmlSchemaAddAttribute(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema,
  * @name:  the item name
  * @namespace:  the namespace
  *
- * Add an XML schema Attrribute declaration
+ * Add an XML schema Attribute declaration
  * *WARNING* this interface is highly subject to change
  *
- * Returns the new struture or NULL in case of error
+ * Returns the new structure or NULL in case of error
  */
 static xmlSchemaAttributeUsePtr
 xmlSchemaAddAttributeUse(xmlSchemaParserCtxtPtr pctxt,
@@ -5301,9 +5295,9 @@ xmlSchemaAddRedef(xmlSchemaParserCtxtPtr pctxt,
  * @nsName:  the target namespace
  * @node: the corresponding node
  *
- * Add an XML schema Attrribute Group definition.
+ * Add an XML schema Attribute Group definition.
  *
- * Returns the new struture or NULL in case of error
+ * Returns the new structure or NULL in case of error
  */
 static xmlSchemaAttributeGroupPtr
 xmlSchemaAddAttributeGroupDefinition(xmlSchemaParserCtxtPtr pctxt,
@@ -5355,7 +5349,7 @@ xmlSchemaAddAttributeGroupDefinition(xmlSchemaParserCtxtPtr pctxt,
  * Add an XML schema Element declaration
  * *WARNING* this interface is highly subject to change
  *
- * Returns the new struture or NULL in case of error
+ * Returns the new structure or NULL in case of error
  */
 static xmlSchemaElementPtr
 xmlSchemaAddElement(xmlSchemaParserCtxtPtr ctxt,
@@ -5396,7 +5390,7 @@ xmlSchemaAddElement(xmlSchemaParserCtxtPtr ctxt,
  * Add an XML schema item
  * *WARNING* this interface is highly subject to change
  *
- * Returns the new struture or NULL in case of error
+ * Returns the new structure or NULL in case of error
  */
 static xmlSchemaTypePtr
 xmlSchemaAddType(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema,
@@ -5493,7 +5487,7 @@ xmlSchemaAddAttributeUseProhib(xmlSchemaParserCtxtPtr pctxt)
  * Adds a schema model group
  * *WARNING* this interface is highly subject to change
  *
- * Returns the new struture or NULL in case of error
+ * Returns the new structure or NULL in case of error
  */
 static xmlSchemaModelGroupPtr
 xmlSchemaAddModelGroup(xmlSchemaParserCtxtPtr ctxt,
@@ -5535,7 +5529,7 @@ xmlSchemaAddModelGroup(xmlSchemaParserCtxtPtr ctxt,
  * Adds an XML schema particle component.
  * *WARNING* this interface is highly subject to change
  *
- * Returns the new struture or NULL in case of error
+ * Returns the new structure or NULL in case of error
  */
 static xmlSchemaParticlePtr
 xmlSchemaAddParticle(xmlSchemaParserCtxtPtr ctxt,
@@ -5581,7 +5575,7 @@ xmlSchemaAddParticle(xmlSchemaParserCtxtPtr ctxt,
  *
  * Add an XML schema Group definition
  *
- * Returns the new struture or NULL in case of error
+ * Returns the new structure or NULL in case of error
  */
 static xmlSchemaModelGroupDefPtr
 xmlSchemaAddModelGroupDefinition(xmlSchemaParserCtxtPtr ctxt,
@@ -5627,7 +5621,7 @@ xmlSchemaAddModelGroupDefinition(xmlSchemaParserCtxtPtr ctxt,
  *
  * Creates a new wildcard namespace constraint.
  *
- * Returns the new struture or NULL in case of error
+ * Returns the new structure or NULL in case of error
  */
 static xmlSchemaWildcardNsPtr
 xmlSchemaNewWildcardNsConstraint(xmlSchemaParserCtxtPtr ctxt)
@@ -5685,7 +5679,7 @@ xmlSchemaAddIDC(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema,
  * Adds a wildcard.
  * It corresponds to a xsd:anyAttribute and xsd:any.
  *
- * Returns the new struture or NULL in case of error
+ * Returns the new structure or NULL in case of error
  */
 static xmlSchemaWildcardPtr
 xmlSchemaAddWildcard(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema,
@@ -5813,11 +5807,10 @@ xmlSchemaAddElementSubstitutionMember(xmlSchemaParserCtxtPtr pctxt,
  * xmlSchemaPValAttrNodeQNameValue:
  * @ctxt:  a schema parser context
  * @schema: the schema context
- * @ownerDes: the designation of the parent element
  * @ownerItem: the parent as a schema object
  * @value:  the QName value
- * @local: the resulting local part if found, the attribute value otherwise
  * @uri:  the resulting namespace URI if found
+ * @local: the resulting local part if found, the attribute value otherwise
  *
  * Extracts the local name and the URI of a QName value and validates it.
  * This one is intended to be used on attribute values that
@@ -5894,11 +5887,10 @@ xmlSchemaPValAttrNodeQNameValue(xmlSchemaParserCtxtPtr ctxt,
  * xmlSchemaPValAttrNodeQName:
  * @ctxt:  a schema parser context
  * @schema: the schema context
- * @ownerDes: the designation of the owner element
  * @ownerItem: the owner as a schema object
  * @attr:  the attribute node
- * @local: the resulting local part if found, the attribute value otherwise
  * @uri:  the resulting namespace URI if found
+ * @local: the resulting local part if found, the attribute value otherwise
  *
  * Extracts and validates the QName of an attribute value.
  * This one is intended to be used on attribute values that
@@ -5926,12 +5918,11 @@ xmlSchemaPValAttrNodeQName(xmlSchemaParserCtxtPtr ctxt,
  * xmlSchemaPValAttrQName:
  * @ctxt:  a schema parser context
  * @schema: the schema context
- * @ownerDes: the designation of the parent element
  * @ownerItem: the owner as a schema object
  * @ownerElem:  the parent node of the attribute
  * @name:  the name of the attribute
- * @local: the resulting local part if found, the attribute value otherwise
  * @uri:  the resulting namespace URI if found
+ * @local: the resulting local part if found, the attribute value otherwise
  *
  * Extracts and validates the QName of an attribute value.
  *
@@ -5962,11 +5953,6 @@ xmlSchemaPValAttrQName(xmlSchemaParserCtxtPtr ctxt,
 /**
  * xmlSchemaPValAttrID:
  * @ctxt:  a schema parser context
- * @schema: the schema context
- * @ownerDes: the designation of the parent element
- * @ownerItem: the owner as a schema object
- * @ownerElem:  the parent node of the attribute
- * @name:  the name of the attribute
  *
  * Extracts and validates the ID of an attribute value.
  *
@@ -6162,7 +6148,6 @@ xmlGetMinOccurs(xmlSchemaParserCtxtPtr ctxt, xmlNodePtr node,
 /**
  * xmlSchemaPGetBoolNodeValue:
  * @ctxt:  a schema validation context
- * @ownerDes:  owner designation
  * @ownerItem:  the owner as a schema item
  * @node: the node holding the value
  *
@@ -6253,7 +6238,7 @@ xmlGetBooleanProp(xmlSchemaParserCtxtPtr ctxt,
 
 /************************************************************************
  *									*
- *		Shema extraction from an Infoset			*
+ *		Schema extraction from an Infoset			*
  *									*
  ************************************************************************/
 static xmlSchemaTypePtr xmlSchemaParseSimpleType(xmlSchemaParserCtxtPtr
@@ -6286,8 +6271,7 @@ xmlSchemaParseAnyAttribute(xmlSchemaParserCtxtPtr ctxt,
 /**
  * xmlSchemaPValAttrNodeValue:
  *
- * @ctxt:  a schema parser context
- * @ownerDes: the designation of the parent element
+ * @pctxt:  a schema parser context
  * @ownerItem: the schema object owner if existent
  * @attr:  the schema attribute node being validated
  * @value: the value
@@ -6360,7 +6344,6 @@ xmlSchemaPValAttrNodeValue(xmlSchemaParserCtxtPtr pctxt,
  * xmlSchemaPValAttrNode:
  *
  * @ctxt:  a schema parser context
- * @ownerDes: the designation of the parent element
  * @ownerItem: the schema object owner if existent
  * @attr:  the schema attribute node being validated
  * @type: the built-in type to be validated against
@@ -6398,7 +6381,6 @@ xmlSchemaPValAttrNode(xmlSchemaParserCtxtPtr ctxt,
  *
  * @ctxt:  a schema parser context
  * @node: the element node of the attribute
- * @ownerDes: the designation of the parent element
  * @ownerItem: the schema object owner if existent
  * @ownerElem: the owner element node
  * @name:  the name of the schema attribute node
@@ -6543,7 +6525,7 @@ xmlSchemaParseLocalAttributes(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema,
  * @schema:  the schema being built
  * @node:  a subtree containing XML Schema informations
  *
- * parse a XML schema Attrribute declaration
+ * parse a XML schema Attribute declaration
  * *WARNING* this interface is highly subject to change
  *
  * Returns -1 in case of error, 0 if the declaration is improper and
@@ -6840,7 +6822,7 @@ xmlSchemaParseWildcardNs(xmlSchemaParserCtxtPtr ctxt,
 		    dictnsItem = xmlDictLookup(ctxt->dict, nsItem, -1);
 		}
 		/*
-		* Avoid dublicate namespaces.
+		* Avoid duplicate namespaces.
 		*/
 		tmp = wildc->nsSet;
 		while (tmp != NULL) {
@@ -7063,7 +7045,7 @@ xmlSchemaParseNotation(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema,
  * @schema:  the schema being built
  * @node:  a subtree containing XML Schema informations
  *
- * parse a XML schema AnyAttrribute declaration
+ * parse a XML schema AnyAttribute declaration
  * *WARNING* this interface is highly subject to change
  *
  * Returns a wildcard or NULL.
@@ -7133,7 +7115,7 @@ xmlSchemaParseAnyAttribute(xmlSchemaParserCtxtPtr ctxt,
  * @schema:  the schema being built
  * @node:  a subtree containing XML Schema informations
  *
- * parse a XML schema Attrribute declaration
+ * parse a XML schema Attribute declaration
  * *WARNING* this interface is highly subject to change
  *
  * Returns the attribute declaration.
@@ -7953,7 +7935,7 @@ xmlSchemaPValAttrBlockFinal(const xmlChar *value,
     int ret = 0;
 
     /*
-    * TODO: This does not check for dublicate entries.
+    * TODO: This does not check for duplicate entries.
     */
     if ((flags == NULL) || (value == NULL))
 	return (-1);
@@ -8145,7 +8127,7 @@ xmlSchemaCheckCSelectorXPath(xmlSchemaParserCtxtPtr ctxt,
  *
  * Adds the annotation to the given schema component.
  *
- * Returns the given annotaion.
+ * Returns the given annotation.
  */
 static xmlSchemaAnnotPtr
 xmlSchemaAddAnnotation(xmlSchemaAnnotItemPtr annItem,
@@ -8240,7 +8222,7 @@ xmlSchemaAddAnnotation(xmlSchemaAnnotItemPtr annItem,
  * @schema:  the schema being built
  * @node:  a subtree containing XML Schema informations
  *
- * Parses a XML Schema identity-contraint definition's
+ * Parses a XML Schema identity-constraint definition's
  * <selector> and <field> elements.
  *
  * Returns the parsed identity-constraint definition.
@@ -8338,7 +8320,7 @@ xmlSchemaParseIDCSelectorAndField(xmlSchemaParserCtxtPtr ctxt,
  * @schema:  the schema being built
  * @node:  a subtree containing XML Schema informations
  *
- * Parses a XML Schema identity-contraint definition.
+ * Parses a XML Schema identity-constraint definition.
  *
  * Returns the parsed identity-constraint definition.
  */
@@ -9477,7 +9459,7 @@ xmlSchemaParseModelGroupDefRef(xmlSchemaParserCtxtPtr ctxt,
  *
  * Parses a XML schema model group definition.
  *
- * Note that the contraint src-redefine (6.2) can't be applied until
+ * Note that the constraint src-redefine (6.2) can't be applied until
  * references have been resolved. So we will do this at the
  * component fixup level.
  *
@@ -10185,7 +10167,7 @@ xmlSchemaParseNewDocWithContext(xmlSchemaParserCtxtPtr pctxt,
 	goto exit;
     /*
     * TODO: Not nice, but I'm not 100% sure we will get always an error
-    * as a result of the obove functions; so better rely on pctxt->err
+    * as a result of the above functions; so better rely on pctxt->err
     * as well.
     */
     if ((ret == 0) && (oldErrs != pctxt->nberrors)) {
@@ -10279,7 +10261,7 @@ xmlSchemaBuildAbsoluteURI(xmlDictPtr dict, const xmlChar* location,
 			  xmlNodePtr ctxtNode)
 {
     /*
-    * Build an absolue location URI.
+    * Build an absolute location URI.
     */
     if (location != NULL) {
 	if (ctxtNode == NULL)
@@ -10361,7 +10343,7 @@ xmlSchemaAddSchemaDoc(xmlSchemaParserCtxtPtr pctxt,
     if ((type == XML_SCHEMA_SCHEMA_MAIN) || (! WXS_HAS_BUCKETS(pctxt)))
 	goto doc_load;
 
-    /* Note that we expect the location to be an absulute URI. */
+    /* Note that we expect the location to be an absolute URI. */
     if (schemaLocation != NULL) {
 	bkt = xmlSchemaGetSchemaBucket(pctxt, schemaLocation);
 	if ((bkt != NULL) &&
@@ -10508,7 +10490,7 @@ xmlSchemaAddSchemaDoc(xmlSchemaParserCtxtPtr pctxt,
 
 		/*
 		* Chameleon include/redefine: skip loading only if it was
-		* aleady build for the targetNamespace of the including
+		* already build for the targetNamespace of the including
 		* schema.
 		*/
 		/*
@@ -10516,7 +10498,7 @@ xmlSchemaAddSchemaDoc(xmlSchemaParserCtxtPtr pctxt,
 		* the components into the including schema and modify the
 		* targetNamespace of those components, do nothing otherwise.
 		* NOTE: This is currently worked-around by compiling the
-		* chameleon for every destinct including targetNamespace; thus
+		* chameleon for every distinct including targetNamespace; thus
 		* not performant at the moment.
 		* TODO: Check when the namespace in wildcards for chameleons
 		* needs to be converted: before we built wildcard intersections
@@ -10707,7 +10689,7 @@ doc_load:
 
 exit:
     /*
-    * Return the bucket explicitely; this is needed for the
+    * Return the bucket explicitly; this is needed for the
     * main schema.
     */
     if (bucket != NULL)
@@ -12888,7 +12870,7 @@ xmlSchemaBuildAContentModel(xmlSchemaParserCtxtPtr pctxt,
 
             ret = 1;
             /*
-             * If max and min occurances are default (1) then
+             * If max and min occurrences are default (1) then
              * simply iterate over the particles of the <sequence>.
              */
             if ((particle->minOccurs == 1) && (particle->maxOccurs == 1)) {
@@ -13047,7 +13029,7 @@ xmlSchemaBuildAContentModel(xmlSchemaParserCtxtPtr pctxt,
                     particle->minOccurs < 1 ? 0 : particle->minOccurs - 1;
 
                 /*
-                 * use a counter to keep track of the number of transtions
+                 * use a counter to keep track of the number of transitions
                  * which went through the choice.
                  */
                 counter =
@@ -13512,7 +13494,7 @@ xmlSchemaGetBuiltInTypeAncestor(xmlSchemaTypePtr type)
  * @source: the source wildcard
  *
  * Clones the namespace constraints of source
- * and assignes them to dest.
+ * and assigns them to dest.
  * Returns -1 on internal error, 0 otherwise.
  */
 static int
@@ -13735,7 +13717,7 @@ xmlSchemaUnionWildcards(xmlSchemaParserCtxtPtr ctxt,
 	    */
 	    xmlSchemaPErr(ctxt, completeWild->node,
 		XML_SCHEMAP_UNION_NOT_EXPRESSIBLE,
-		"The union of the wilcard is not expressible.\n",
+		"The union of the wildcard is not expressible.\n",
 		NULL, NULL);
 	    return(XML_SCHEMAP_UNION_NOT_EXPRESSIBLE);
 	} else if ((!nsFound) && (!absentFound)) {
@@ -13972,7 +13954,7 @@ xmlSchemaIntersectWildcards(xmlSchemaParserCtxtPtr ctxt,
 	(curWild->negNsSet->value != NULL)) {
 
 	xmlSchemaPErr(ctxt, completeWild->node, XML_SCHEMAP_INTERSECTION_NOT_EXPRESSIBLE,
-	    "The intersection of the wilcard is not expressible.\n",
+	    "The intersection of the wildcard is not expressible.\n",
 	    NULL, NULL);
 	return(XML_SCHEMAP_INTERSECTION_NOT_EXPRESSIBLE);
     }
@@ -14443,7 +14425,7 @@ xmlSchemaExpandAttributeGroupRefs(xmlSchemaParserCtxtPtr pctxt,
  * Builds the wildcard and the attribute uses on the given complex type.
  * Returns -1 if an internal error occurs, 0 otherwise.
  *
- * ATTENTION TODO: Experimantally this uses pointer comparisons for
+ * ATTENTION TODO: Experimentally this uses pointer comparisons for
  * strings, so recheck this if we start to hardcode some schemata, since
  * they might not be in the same dict.
  * NOTE: It is allowed to "extend" the xs:anyType type.
@@ -14643,7 +14625,7 @@ exit_failure:
  * Evaluates if a type definition contains the given "final".
  * This does take "finalDefault" into account as well.
  *
- * Returns 1 if the type does containt the given "final",
+ * Returns 1 if the type does contain the given "final",
  * 0 otherwise.
  */
 static int
@@ -14683,7 +14665,7 @@ xmlSchemaGetUnionSimpleTypeMemberTypes(xmlSchemaTypePtr type)
  * Schema Component Constraint: Effective Total Range
  * (all and sequence) + (choice)
  *
- * Returns the minimun Effective Total Range.
+ * Returns the minimum Effective Total Range.
  */
 static int
 xmlSchemaGetParticleTotalRangeMin(xmlSchemaParticlePtr particle)
@@ -14827,12 +14809,12 @@ xmlSchemaIsParticleEmptiable(xmlSchemaParticlePtr particle)
  * @actxt: a context
  * @type:  the derived simple type definition
  * @baseType:  the base type definition
- * @subset: the subset of ('restriction', ect.)
+ * @subset: the subset of ('restriction', etc.)
  *
  * Schema Component Constraint:
  * Type Derivation OK (Simple) (cos-st-derived-OK)
  *
- * Checks wheter @type can be validly
+ * Checks whether @type can be validly
  * derived from @baseType.
  *
  * Returns 0 on success, an positive error code otherwise.
@@ -14845,7 +14827,7 @@ xmlSchemaCheckCOSSTDerivedOK(xmlSchemaAbstractCtxtPtr actxt,
 {
     /*
     * 1 They are the same type definition.
-    * TODO: The identy check might have to be more complex than this.
+    * TODO: The identity check might have to be more complex than this.
     */
     if (type == baseType)
 	return (0);
@@ -15055,7 +15037,7 @@ xmlSchemaCheckUnionTypeDefCircular(xmlSchemaParserCtxtPtr pctxt,
  * @ctxt:  the parser context
  * @name:  the name
  *
- * Resolvese type definition references
+ * Resolves type definition references
  */
 static void
 xmlSchemaResolveTypeReferences(xmlSchemaTypePtr typeDef,
@@ -16132,7 +16114,7 @@ xmlSchemaCheckCOSCTDerivedOK(xmlSchemaAbstractCtxtPtr actxt,
  * Calls:
  * Type Derivation OK (Simple) AND Type Derivation OK (Complex)
  *
- * Checks wheter @type can be validly derived from @baseType.
+ * Checks whether @type can be validly derived from @baseType.
  *
  * Returns 0 on success, an positive error code otherwise.
  */
@@ -16265,7 +16247,7 @@ xmlSchemaCheckCOSCTExtends(xmlSchemaParserCtxtPtr ctxt,
 	* if created the type via a schema construction API.
 	*/
 	if (base->attributeWildcard != NULL) {
-	    if (type->attributeWilcard == NULL) {
+	    if (type->attributeWildcard == NULL) {
 		xmlChar *str = NULL;
 
 		xmlSchemaCustomErr(ACTXT_CAST pctxt,
@@ -16494,7 +16476,7 @@ xmlSchemaCheckDerivationOKRestriction(xmlSchemaParserCtxtPtr ctxt,
 	    * the {content type} is validly derived given the empty
 	    * set as defined in Type Derivation OK (Simple) ($3.14.6)."
 	    *
-	    * ATTENTION TODO: This seems not needed if the type implicitely
+	    * ATTENTION TODO: This seems not needed if the type implicitly
 	    * derived from the base type.
 	    *
 	    */
@@ -17719,7 +17701,7 @@ xmlSchemaDeriveAndValidateFacets(xmlSchemaParserCtxtPtr pctxt,
     *
     * *Patterns*: won't be add here, since they are ORed at
     * type level and ANDed at ancestor level. This will
-    * happed during validation by walking the base axis
+    * happen during validation by walking the base axis
     * of the type.
     */
     for (cur = base->facetSet; cur != NULL; cur = cur->next) {
@@ -18319,7 +18301,7 @@ xmlSchemaFixupComplexType(xmlSchemaParserCtxtPtr pctxt,
 		    WXS_BASIC_CAST type, NULL,
 		    "Internal error: xmlSchemaTypeFixup, "
 		    "complex type '%s': the <simpleContent><restriction> "
-		    "is missing a <simpleType> child, but was not catched "
+		    "is missing a <simpleType> child, but was not caught "
 		    "by xmlSchemaCheckSRCCT()", type->name);
 		goto exit_failure;
 	    }
@@ -18332,7 +18314,7 @@ xmlSchemaFixupComplexType(xmlSchemaParserCtxtPtr pctxt,
 	    if (baseType->contentTypeDef == NULL) {
 		/*
 		* TODO: Check if this ever happens. xmlSchemaCheckSRCCT
-		* should have catched this already.
+		* should have caught this already.
 		*/
 		xmlSchemaPCustomErr(pctxt,
 		    XML_SCHEMAP_INTERNAL,
@@ -18575,7 +18557,7 @@ xmlSchemaFixupComplexType(xmlSchemaParserCtxtPtr pctxt,
 		    * NOTE that, although we miss to add an intermediate
 		    * <sequence>, this should produce no difference to
 		    * neither the regex compilation of the content model,
-		    * nor to the complex type contraints.
+		    * nor to the complex type constraints.
 		    */
 		    particle->children->children =
 			(xmlSchemaTreeItemPtr) baseType->subtypes;
@@ -19000,7 +18982,7 @@ xmlSchemaCheckGroupDefCircular(xmlSchemaModelGroupDefPtr item,
 	    * is defined for model groups but not definitions, but since
 	    * there cannot be any circular model groups without a model group
 	    * definition (if not using a construction API), we check those
-	    * defintions only.
+	    * definitions only.
 	    */
 	    xmlSchemaPCustomErr(ctxt,
 		XML_SCHEMAP_MG_PROPS_CORRECT_2,
@@ -19073,7 +19055,7 @@ xmlSchemaModelGroupToModelGroupDefFixup(
  * This one is intended to be used by
  * xmlSchemaCheckAttrGroupCircular only.
  *
- * Returns the circular attribute grou reference, otherwise NULL.
+ * Returns the circular attribute group reference, otherwise NULL.
  */
 static xmlSchemaQNameRefPtr
 xmlSchemaCheckAttrGroupCircularRecur(xmlSchemaAttributeGroupPtr ctxtGr,
@@ -19187,7 +19169,7 @@ xmlSchemaAttributeGroupExpandRefs(xmlSchemaParserCtxtPtr pctxt,
  * @list: the attribute uses
  *
  * Substitutes contained attribute group references
- * for their attribute uses. Wilcards are intersected.
+ * for their attribute uses. Wildcards are intersected.
  * Attribute use prohibitions are removed from the list
  * and returned via the @prohibs list.
  * Pointlessness of attr. prohibs, if a matching attr. decl
@@ -19361,7 +19343,7 @@ xmlSchemaExpandAttributeGroupRefs(xmlSchemaParserCtxtPtr pctxt,
  * {attribute wildcard} property
  *
  * Substitutes contained attribute group references
- * for their attribute uses. Wilcards are intersected.
+ * for their attribute uses. Wildcards are intersected.
  */
 static int
 xmlSchemaAttributeGroupExpandRefs(xmlSchemaParserCtxtPtr pctxt,
@@ -19384,7 +19366,7 @@ xmlSchemaAttributeGroupExpandRefs(xmlSchemaParserCtxtPtr pctxt,
  * @attrGr:  the attribute group definition
  *
  * Substitutes contained attribute group references
- * for their attribute uses. Wilcards are intersected.
+ * for their attribute uses. Wildcards are intersected.
  *
  * Schema Component Constraint:
  *    Attribute Group Definition Properties Correct (ag-props-correct)
@@ -19520,8 +19502,8 @@ xmlSchemaResolveAttrGroupReferences(xmlSchemaQNameRefPtr ref,
  *    Attribute Declaration Properties Correct (a-props-correct)
  *
  * Validates the value constraints of an attribute declaration/use.
- * NOTE that this needs the simle type definitions to be already
- *   builded and checked.
+ * NOTE that this needs the simple type definitions to be already
+ *   built and checked.
  */
 static int
 xmlSchemaCheckAttrPropsCorrect(xmlSchemaParserCtxtPtr pctxt,
@@ -20508,7 +20490,7 @@ xmlSchemaCheckSRCRedefineFirst(xmlSchemaParserCtxtPtr pctxt)
 	*   it's not clear if the referenced component needs to originate
 	*   from the <redefine>d schema _document_ or the schema; the latter
 	*   would include all imported and included sub-schemas of the
-	*   <redefine>d schema. Currenlty we latter approach is used.
+	*   <redefine>d schema. Currently the latter approach is used.
 	*   SUPPLEMENT: It seems that the WG moves towards the latter
 	*   approach, so we are doing it right.
 	*
@@ -20623,8 +20605,8 @@ xmlSchemaCheckSRCRedefineFirst(xmlSchemaParserCtxtPtr pctxt)
 		    * This is the complicated case: we need
 		    * to apply src-redefine (7.2.2) at a later
 		    * stage, i.e. when attribute group references
-		    * have beed expanded and simple types have
-		    * beed fixed.
+		    * have been expanded and simple types have
+		    * been fixed.
 		    */
 		    redef->target = prev;
 		}
@@ -20999,7 +20981,7 @@ xmlSchemaFixupComponents(xmlSchemaParserCtxtPtr pctxt,
     * 1. the base axis of type definitions
     * 2. nested model group definitions
     * 3. nested attribute group definitions
-    * TODO: check for circual substitution groups.
+    * TODO: check for circular substitution groups.
     */
     for (i = 0; i < nbItems; i++) {
 	item = items[i];
@@ -21080,7 +21062,7 @@ xmlSchemaFixupComponents(xmlSchemaParserCtxtPtr pctxt,
 	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
+    * a separate step, since otherwise we won't be able to detect
     * circular union types in all cases.
     */
     for (i = 0; i < nbItems; i++) {
@@ -21142,7 +21124,7 @@ xmlSchemaFixupComponents(xmlSchemaParserCtxtPtr pctxt,
     * At this point we need build and check all simple types.
     */
     /*
-    * Apply contraints for attribute declarations.
+    * Apply constraints for attribute declarations.
     */
     for (i = 0; i < nbItems; i++) {
 	item = items[i];
@@ -21207,7 +21189,7 @@ xmlSchemaFixupComponents(xmlSchemaParserCtxtPtr pctxt,
 	goto exit_error;
 
     /*
-    * Complex types are builded and checked.
+    * Complex types are built and checked.
     */
     for (i = 0; i < nbItems; i++) {
 	item = con->pending->items[i];
@@ -21324,7 +21306,7 @@ exit:
  * @ctxt:  a schema validation context
  *
  * parse a schema definition resource and build an internal
- * XML Shema struture which can be used to validate instances.
+ * XML Schema structure which can be used to validate instances.
  *
  * Returns the internal XML Schema structure built from the resource or
  *         NULL in case of error
@@ -21426,7 +21408,7 @@ exit:
 exit_failure:
     /*
     * Quite verbose, but should catch internal errors, which were
-    * not communitated.
+    * not communicated.
     */
     if (mainSchema) {
         xmlSchemaFree(mainSchema);
@@ -21893,7 +21875,7 @@ xmlSchemaLookupNamespace(xmlSchemaValidCtxtPtr vctxt,
 	if ((vctxt->inode->node == NULL) ||
 	    (vctxt->inode->node->doc == NULL)) {
 	    VERROR_INT("xmlSchemaLookupNamespace",
-		"no node or node's doc avaliable");
+		"no node or node's doc available");
 	    return (NULL);
 	}
 	ns = xmlSearchNs(vctxt->inode->node->doc,
@@ -22106,7 +22088,7 @@ xmlSchemaIDCStoreNodeTableItem(xmlSchemaValidCtxtPtr vctxt,
 			       xmlSchemaPSVIIDCNodePtr item)
 {
     /*
-    * Add to gobal list.
+    * Add to global list.
     */
     if (vctxt->idcNodes == NULL) {
 	vctxt->idcNodes = (xmlSchemaPSVIIDCNodePtr *)
@@ -22147,7 +22129,7 @@ xmlSchemaIDCStoreKey(xmlSchemaValidCtxtPtr vctxt,
 		     xmlSchemaPSVIIDCKeyPtr key)
 {
     /*
-    * Add to gobal list.
+    * Add to global list.
     */
     if (vctxt->idcKeys == NULL) {
 	vctxt->idcKeys = (xmlSchemaPSVIIDCKeyPtr *)
@@ -22804,7 +22786,7 @@ xmlSchemaXPathProcessHistory(xmlSchemaValidCtxtPtr vctxt,
 		VERROR(XML_SCHEMAV_CVC_IDC,
 		    WXS_BASIC_CAST sto->matcher->aidc->def,
 		    "Warning: No precomputed value available, the value "
-		    "was either invalid or something strange happend");
+		    "was either invalid or something strange happened");
 		sto->nbHistory--;
 		goto deregister_check;
 	    } else {
@@ -22825,7 +22807,7 @@ xmlSchemaXPathProcessHistory(xmlSchemaValidCtxtPtr vctxt,
 		*   <bar>
                 * </scope>
 		*
-		* The size of the list is only dependant on the depth of
+		* The size of the list is only dependent on the depth of
 		* the tree.
 		* An entry will be NULLed in selector_leave, i.e. when
 		* we hit the target's
@@ -23366,6 +23348,8 @@ xmlSchemaIDCFillNodeTables(xmlSchemaValidCtxtPtr vctxt,
 	* Get/create the IDC binding on this element for the IDC definition.
 	*/
 	bind = xmlSchemaIDCAcquireBinding(vctxt, matcher);
+	if (bind == NULL)
+	   goto internal_error;
 
 	if (! WXS_ILIST_IS_EMPTY(bind->dupls)) {
 	    dupls = (xmlSchemaPSVIIDCNodePtr *) bind->dupls->items;
@@ -24118,7 +24102,7 @@ xmlSchemaClearElemInfo(xmlSchemaValidCtxtPtr vctxt,
  * @vctxt: the schema validation context
  *
  * Creates/reuses and initializes the element info item for
- * the currect tree depth.
+ * the current tree depth.
  *
  * Returns the element info item or NULL on API or internal errors.
  */
@@ -24391,7 +24375,7 @@ pattern_and_enum:
 		found = 1;
 		/*
 		* NOTE that for patterns, @value needs to be the
-		* normalized vaule.
+		* normalized value.
 		*/
 		ret = xmlRegexpExec(facetLink->facet->regexp, value);
 		if (ret == 1)
@@ -24665,7 +24649,7 @@ xmlSchemaVCheckCVCSimpleType(xmlSchemaAbstractCtxtPtr actxt,
 		    ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_1;
 	    }
 	}
-	if (fireErrors && (ret > 0))
+	else if (fireErrors && (ret > 0))
 	    xmlSchemaSimpleTypeErr(actxt, ret, node, value, type, 1);
     } else if (WXS_IS_LIST(type)) {
 
@@ -24928,7 +24912,7 @@ xmlSchemaProcessXSIType(xmlSchemaValidCtxtPtr vctxt,
     else {
 	const xmlChar *nsName = NULL, *local = NULL;
 	/*
-	* TODO: We should report a *warning* that the type was overriden
+	* TODO: We should report a *warning* that the type was overridden
 	* by the instance.
 	*/
 	ACTIVATE_ATTRIBUTE(iattr);
@@ -26347,7 +26331,7 @@ default_psvi:
 		    XML_SCHEMA_ELEM_INFO_HAS_ELEM_CONTENT) {
 		ret = XML_SCHEMAV_CVC_ELT_5_2_2_1;
 		VERROR(ret, NULL,
-		    "The content must not containt element nodes since "
+		    "The content must not contain element nodes since "
 		    "there is a fixed value constraint");
 		goto end_elem;
 	    } else {
@@ -26554,7 +26538,7 @@ xmlSchemaValidateChildElem(xmlSchemaValidCtxtPtr vctxt)
     if (ptype->builtInType == XML_SCHEMAS_ANYTYPE) {
 	/*
 	* Workaround for "anyType": we have currently no content model
-	* assigned for "anyType", so handle it explicitely.
+	* assigned for "anyType", so handle it explicitly.
 	* "anyType" has an unbounded, lax "any" wildcard.
 	*/
 	vctxt->inode->decl = xmlSchemaGetElem(vctxt->schema,
@@ -26629,7 +26613,7 @@ xmlSchemaValidateChildElem(xmlSchemaValidCtxtPtr vctxt)
 		return (-1);
 	    }
 	    /*
-	    * Safety belf for evaluation if the cont. model was already
+	    * Safety belt for evaluation if the cont. model was already
 	    * examined to be invalid.
 	    */
 	    if (pielem->flags & XML_SCHEMA_ELEM_INFO_ERR_BAD_CONTENT) {
@@ -28818,7 +28802,7 @@ xmlSchemaValidateSetLocator(xmlSchemaValidCtxtPtr vctxt,
  *
  * Internal locator function for the readers
  *
- * Returns 0 in case the Schema validation could be (des)activated and
+ * Returns 0 in case the Schema validation could be (de)activated and
  *         -1 in case of error.
  */
 static int
diff --git a/xmlschemastypes.c b/xmlschemastypes.c
index ca381d38066..e7764d90581 100644
--- a/xmlschemastypes.c
+++ b/xmlschemastypes.c
@@ -70,7 +70,7 @@ struct _xmlSchemaValDate {
     unsigned int	hour	:5;	/* 0 <=  hour   <= 24   */
     unsigned int	min	:6;	/* 0 <=  min    <= 59	*/
     double		sec;
-    unsigned int	tz_flag	:1;	/* is tzo explicitely set? */
+    unsigned int	tz_flag	:1;	/* is tzo explicitly set? */
     signed int		tzo	:12;	/* -1440 <= tzo <= 1440;
 					   currently only -840 to +840 are needed */
 };
@@ -1129,7 +1129,7 @@ xmlSchemaGetBuiltInListSimpleTypeItemType(xmlSchemaTypePtr type)
 #define VALID_HOUR(hr)          ((hr >= 0) && (hr <= 23))
 #define VALID_MIN(min)          ((min >= 0) && (min <= 59))
 #define VALID_SEC(sec)          ((sec >= 0) && (sec < 60))
-#define VALID_TZO(tzo)          ((tzo > -840) && (tzo < 840))
+#define VALID_TZO(tzo)          ((tzo >= -840) && (tzo <= 840))
 #define IS_LEAP(y)						\
 	(((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0))
 
@@ -2130,7 +2130,7 @@ xmlSchemaParseUInt(const xmlChar **str, unsigned long *llo,
  * @value: the value to check
  * @val:  the return computed value
  * @node:  the node containing the value
- * flags:  flags to control the vlidation
+ * flags:  flags to control the validation
  *
  * Check that a value conforms to the lexical space of the atomic type.
  * if true a value is computed and returned in @val.
@@ -2155,7 +2155,7 @@ xmlSchemaValAtomicType(xmlSchemaTypePtr type, const xmlChar * value,
         return (-1);
 
     /*
-     * validating a non existant text node is similar to validating
+     * validating a non existent text node is similar to validating
      * an empty one.
      */
     if (value == NULL)
@@ -2925,7 +2925,7 @@ xmlSchemaValAtomicType(xmlSchemaTypePtr type, const xmlChar * value,
                 if (*value != 0) {
 		    xmlURIPtr uri;
 		    xmlChar *tmpval, *cur;
-		    if (normOnTheFly) {
+		    if ((norm == NULL) && (normOnTheFly)) {
 			norm = xmlSchemaCollapseString(value);
 			if (norm != NULL)
 			    value = norm;
@@ -3067,7 +3067,7 @@ xmlSchemaValAtomicType(xmlSchemaTypePtr type, const xmlChar * value,
                  * following cases can arise: (1) the final quantum of
                  * encoding input is an integral multiple of 24 bits; here,
                  * the final unit of encoded output will be an integral
-                 * multiple ofindent: Standard input:701: Warning:old style
+                 * multiple of indent: Standard input:701: Warning:old style
 		 * assignment ambiguity in "=*".  Assuming "= *" 4 characters
 		 * with no "=" padding, (2) the final
                  * quantum of encoding input is exactly 8 bits; here, the
@@ -3628,8 +3628,10 @@ xmlSchemaCompareDurations(xmlSchemaValPtr x, xmlSchemaValPtr y)
 	minday = 0;
 	maxday = 0;
     } else {
-	maxday = 366 * ((myear + 3) / 4) +
-	         365 * ((myear - 1) % 4);
+        /* FIXME: This doesn't take leap year exceptions every 100/400 years
+           into account. */
+	maxday = 365 * myear + (myear + 3) / 4;
+        /* FIXME: Needs to be calculated separately */
 	minday = maxday - 1;
     }
 
@@ -3877,7 +3879,7 @@ _xmlSchemaDateAdd (xmlSchemaValPtr dt, xmlSchemaValPtr dur)
 
         temp = r->mon + carry;
         r->mon = (unsigned int) MODULO_RANGE(temp, 1, 13);
-        r->year = r->year + (unsigned int) FQUOTIENT_RANGE(temp, 1, 13);
+        r->year = r->year + (long) FQUOTIENT_RANGE(temp, 1, 13);
         if (r->year == 0) {
             if (temp < 1)
                 r->year--;
diff --git a/xmlwriter.c b/xmlwriter.c
index b5cd171f5bc..58445c84c86 100644
--- a/xmlwriter.c
+++ b/xmlwriter.c
@@ -541,8 +541,8 @@ xmlTextWriterStartDocument(xmlTextWriterPtr writer, const char *version,
     if (encoding != NULL) {
         encoder = xmlFindCharEncodingHandler(encoding);
         if (encoder == NULL) {
-            xmlWriterErrMsg(writer, XML_ERR_NO_MEMORY,
-                            "xmlTextWriterStartDocument : out of memory!\n");
+            xmlWriterErrMsg(writer, XML_ERR_UNSUPPORTED_ENCODING,
+                            "xmlTextWriterStartDocument : unsupported encoding\n");
             return -1;
         }
     }
@@ -801,7 +801,7 @@ xmlTextWriterStartComment(xmlTextWriterPtr writer)
  * xmlTextWriterEndComment:
  * @writer:  the xmlTextWriterPtr
  *
- * End the current xml coment.
+ * End the current xml comment.
  *
  * Returns the bytes written (may be 0 because of buffering) or -1 in case of error
  */
diff --git a/xpath.c b/xpath.c
index 5e3bb9ff640..9f64ab9ab49 100644
--- a/xpath.c
+++ b/xpath.c
@@ -343,7 +343,7 @@ xmlXPathCmpNodesExt(xmlNodePtr node1, xmlNodePtr node2) {
     }
 
     /*
-     * Speedup using document order if availble.
+     * Speedup using document order if available.
      */
     if ((node1->type == XML_ELEMENT_NODE) &&
 	(node2->type == XML_ELEMENT_NODE) &&
@@ -411,7 +411,7 @@ turtle_comparison:
     if (node1 == node2->next)
 	return(-1);
     /*
-     * Speedup using document order if availble.
+     * Speedup using document order if available.
      */
     if ((node1->type == XML_ELEMENT_NODE) &&
 	(node2->type == XML_ELEMENT_NODE) &&
@@ -435,7 +435,7 @@ turtle_comparison:
 #endif /* XP_OPTIMIZED_NON_ELEM_COMPARISON */
 
 /*
- * Wrapper for the Timsort argorithm from timsort.h
+ * Wrapper for the Timsort algorithm from timsort.h
  */
 #ifdef WITH_TIM_SORT
 #define SORT_NAME libxml_domnode
@@ -610,6 +610,8 @@ static const char *xmlXPathErrorMessages[] = {
     "Invalid or incomplete context\n",
     "Stack usage error\n",
     "Forbidden variable\n",
+    "Operation limit exceeded\n",
+    "Recursion limit exceeded\n",
     "?? Unknown error ??\n"	/* Must be last in the list! */
 };
 #define MAXERRNO ((int)(sizeof(xmlXPathErrorMessages) /	\
@@ -625,6 +627,7 @@ static void
 xmlXPathErrMemory(xmlXPathContextPtr ctxt, const char *extra)
 {
     if (ctxt != NULL) {
+        xmlResetError(&ctxt->lastError);
         if (extra) {
             xmlChar buf[200];
 
@@ -747,6 +750,32 @@ xmlXPatherror(xmlXPathParserContextPtr ctxt, const char *file ATTRIBUTE_UNUSED,
     xmlXPathErr(ctxt, no);
 }
 
+/**
+ * xmlXPathCheckOpLimit:
+ * @ctxt:  the XPath Parser context
+ * @opCount:  the number of operations to be added
+ *
+ * Adds opCount to the running total of operations and returns -1 if the
+ * operation limit is exceeded. Returns 0 otherwise.
+ */
+static int
+xmlXPathCheckOpLimit(xmlXPathParserContextPtr ctxt, unsigned long opCount) {
+    xmlXPathContextPtr xpctxt = ctxt->context;
+
+    if ((opCount > xpctxt->opLimit) ||
+        (xpctxt->opCount > xpctxt->opLimit - opCount)) {
+        xpctxt->opCount = xpctxt->opLimit;
+        xmlXPathErr(ctxt, XPATH_OP_LIMIT_EXCEEDED);
+        return(-1);
+    }
+
+    xpctxt->opCount += opCount;
+    return(0);
+}
+
+#define OP_LIMIT_EXCEEDED(ctxt, n) \
+    ((ctxt->context->opLimit != 0) && (xmlXPathCheckOpLimit(ctxt, n) < 0))
+
 /************************************************************************
  *									*
  *			Utilities					*
@@ -1076,14 +1105,15 @@ xmlXPathFreeCompExpr(xmlXPathCompExprPtr comp)
  * Returns -1 in case of failure, the index otherwise
  */
 static int
-xmlXPathCompExprAdd(xmlXPathCompExprPtr comp, int ch1, int ch2,
+xmlXPathCompExprAdd(xmlXPathParserContextPtr ctxt, int ch1, int ch2,
    xmlXPathOp op, int value,
    int value2, int value3, void *value4, void *value5) {
+    xmlXPathCompExprPtr comp = ctxt->comp;
     if (comp->nbStep >= comp->maxStep) {
 	xmlXPathStepOp *real;
 
         if (comp->maxStep >= XPATH_MAX_STEPS) {
-	    xmlXPathErrMemory(NULL, "adding step\n");
+	    xmlXPathPErrMemory(ctxt, "adding step\n");
 	    return(-1);
         }
 	comp->maxStep *= 2;
@@ -1091,7 +1121,7 @@ xmlXPathCompExprAdd(xmlXPathCompExprPtr comp, int ch1, int ch2,
 		                      comp->maxStep * sizeof(xmlXPathStepOp));
 	if (real == NULL) {
 	    comp->maxStep /= 2;
-	    xmlXPathErrMemory(NULL, "adding step\n");
+	    xmlXPathPErrMemory(ctxt, "adding step\n");
 	    return(-1);
 	}
 	comp->steps = real;
@@ -1153,20 +1183,20 @@ xmlXPathCompSwap(xmlXPathStepOpPtr op) {
 }
 
 #define PUSH_FULL_EXPR(op, op1, op2, val, val2, val3, val4, val5)	\
-    xmlXPathCompExprAdd(ctxt->comp, (op1), (op2),			\
+    xmlXPathCompExprAdd(ctxt, (op1), (op2),			\
 	                (op), (val), (val2), (val3), (val4), (val5))
 #define PUSH_LONG_EXPR(op, val, val2, val3, val4, val5)			\
-    xmlXPathCompExprAdd(ctxt->comp, ctxt->comp->last, -1,		\
+    xmlXPathCompExprAdd(ctxt, ctxt->comp->last, -1,		\
 	                (op), (val), (val2), (val3), (val4), (val5))
 
 #define PUSH_LEAVE_EXPR(op, val, val2)					\
-xmlXPathCompExprAdd(ctxt->comp, -1, -1, (op), (val), (val2), 0 ,NULL ,NULL)
+xmlXPathCompExprAdd(ctxt, -1, -1, (op), (val), (val2), 0 ,NULL ,NULL)
 
 #define PUSH_UNARY_EXPR(op, ch, val, val2)				\
-xmlXPathCompExprAdd(ctxt->comp, (ch), -1, (op), (val), (val2), 0 ,NULL ,NULL)
+xmlXPathCompExprAdd(ctxt, (ch), -1, (op), (val), (val2), 0 ,NULL ,NULL)
 
 #define PUSH_BINARY_EXPR(op, ch1, ch2, val, val2)			\
-xmlXPathCompExprAdd(ctxt->comp, (ch1), (ch2), (op),			\
+xmlXPathCompExprAdd(ctxt, (ch1), (ch2), (op),			\
 			(val), (val2), 0 ,NULL ,NULL)
 
 /************************************************************************
@@ -2226,7 +2256,7 @@ xmlXPathFreeCache(xmlXPathContextCachePtr cache)
  *
  * @ctxt:  the XPath context
  * @active: enables/disables (creates/frees) the cache
- * @value: a value with semantics dependant on @options
+ * @value: a value with semantics dependent on @options
  * @options: options (currently only the value 0 is used)
  *
  * Creates/frees an object cache on the XPath context.
@@ -2386,7 +2416,7 @@ xmlXPathCacheNewNodeSet(xmlXPathContextPtr ctxt, xmlNodePtr val)
 	{
 	    xmlXPathObjectPtr ret;
 	    /*
-	    * Use the nodset-cache.
+	    * Use the nodeset-cache.
 	    */
 	    ret = (xmlXPathObjectPtr)
 		cache->nodesetObjs->items[--cache->nodesetObjs->number];
@@ -2396,6 +2426,7 @@ xmlXPathCacheNewNodeSet(xmlXPathContextPtr ctxt, xmlNodePtr val)
 		if ((ret->nodesetval->nodeMax == 0) ||
 		    (val->type == XML_NAMESPACE_DECL))
 		{
+                    /* TODO: Check memory error. */
 		    xmlXPathNodeSetAddUnique(ret->nodesetval, val);
 		} else {
 		    ret->nodesetval->nodeTab[0] = val;
@@ -2842,29 +2873,36 @@ valuePop(xmlXPathParserContextPtr ctxt)
  * @ctxt:  an XPath evaluation context
  * @value:  the XPath object
  *
- * Pushes a new XPath object on top of the value stack
+ * Pushes a new XPath object on top of the value stack. If value is NULL,
+ * a memory error is recorded in the parser context.
  *
- * returns the number of items on the value stack
+ * Returns the number of items on the value stack, or -1 in case of error.
  */
 int
 valuePush(xmlXPathParserContextPtr ctxt, xmlXPathObjectPtr value)
 {
-    if ((ctxt == NULL) || (value == NULL)) return(-1);
+    if (ctxt == NULL) return(-1);
+    if (value == NULL) {
+        /*
+         * A NULL value typically indicates that a memory allocation failed,
+         * so we set ctxt->error here to propagate the error.
+         */
+	ctxt->error = XPATH_MEMORY_ERROR;
+        return(-1);
+    }
     if (ctxt->valueNr >= ctxt->valueMax) {
         xmlXPathObjectPtr *tmp;
 
         if (ctxt->valueMax >= XPATH_MAX_STACK_DEPTH) {
-            xmlXPathErrMemory(NULL, "XPath stack depth limit reached\n");
-            ctxt->error = XPATH_MEMORY_ERROR;
-            return (0);
+            xmlXPathPErrMemory(ctxt, "XPath stack depth limit reached\n");
+            return (-1);
         }
         tmp = (xmlXPathObjectPtr *) xmlRealloc(ctxt->valueTab,
                                              2 * ctxt->valueMax *
                                              sizeof(ctxt->valueTab[0]));
         if (tmp == NULL) {
-            xmlXPathErrMemory(NULL, "pushing value\n");
-            ctxt->error = XPATH_MEMORY_ERROR;
-            return (0);
+            xmlXPathPErrMemory(ctxt, "pushing value\n");
+            return (-1);
         }
         ctxt->valueMax *= 2;
 	ctxt->valueTab = tmp;
@@ -3320,7 +3358,7 @@ xmlXPathCmpNodes(xmlNodePtr node1, xmlNodePtr node2) {
 	return(-1);
 
     /*
-     * Speedup using document order if availble.
+     * Speedup using document order if available.
      */
     if ((node1->type == XML_ELEMENT_NODE) &&
 	(node2->type == XML_ELEMENT_NODE) &&
@@ -3383,7 +3421,7 @@ xmlXPathCmpNodes(xmlNodePtr node1, xmlNodePtr node2) {
     if (node1 == node2->next)
 	return(-1);
     /*
-     * Speedup using document order if availble.
+     * Speedup using document order if available.
      */
     if ((node1->type == XML_ELEMENT_NODE) &&
 	(node2->type == XML_ELEMENT_NODE) &&
@@ -3547,6 +3585,7 @@ xmlXPathNodeSetCreate(xmlNodePtr val) {
 	if (val->type == XML_NAMESPACE_DECL) {
 	    xmlNsPtr ns = (xmlNsPtr) val;
 
+            /* TODO: Check memory error. */
 	    ret->nodeTab[ret->nodeNr++] =
 		xmlXPathNodeSetDupNs((xmlNodePtr) ns->next, ns);
 	} else
@@ -3555,37 +3594,6 @@ xmlXPathNodeSetCreate(xmlNodePtr val) {
     return(ret);
 }
 
-/**
- * xmlXPathNodeSetCreateSize:
- * @size:  the initial size of the set
- *
- * Create a new xmlNodeSetPtr of type double and of value @val
- *
- * Returns the newly created object.
- */
-static xmlNodeSetPtr
-xmlXPathNodeSetCreateSize(int size) {
-    xmlNodeSetPtr ret;
-
-    ret = (xmlNodeSetPtr) xmlMalloc(sizeof(xmlNodeSet));
-    if (ret == NULL) {
-        xmlXPathErrMemory(NULL, "creating nodeset\n");
-	return(NULL);
-    }
-    memset(ret, 0 , (size_t) sizeof(xmlNodeSet));
-    if (size < XML_NODESET_DEFAULT)
-	size = XML_NODESET_DEFAULT;
-    ret->nodeTab = (xmlNodePtr *) xmlMalloc(size * sizeof(xmlNodePtr));
-    if (ret->nodeTab == NULL) {
-	xmlXPathErrMemory(NULL, "creating nodeset\n");
-	xmlFree(ret);
-	return(NULL);
-    }
-    memset(ret->nodeTab, 0 , size * (size_t) sizeof(xmlNodePtr));
-    ret->nodeMax = size;
-    return(ret);
-}
-
 /**
  * xmlXPathNodeSetContains:
  * @cur:  the node-set
@@ -3684,6 +3692,7 @@ xmlXPathNodeSetAddNs(xmlNodeSetPtr cur, xmlNodePtr node, xmlNsPtr ns) {
         cur->nodeMax *= 2;
 	cur->nodeTab = temp;
     }
+    /* TODO: Check memory error. */
     cur->nodeTab[cur->nodeNr++] = xmlXPathNodeSetDupNs(node, ns);
     return(0);
 }
@@ -3742,6 +3751,7 @@ xmlXPathNodeSetAdd(xmlNodeSetPtr cur, xmlNodePtr val) {
     if (val->type == XML_NAMESPACE_DECL) {
 	xmlNsPtr ns = (xmlNsPtr) val;
 
+        /* TODO: Check memory error. */
 	cur->nodeTab[cur->nodeNr++] =
 	    xmlXPathNodeSetDupNs((xmlNodePtr) ns->next, ns);
     } else
@@ -3796,6 +3806,7 @@ xmlXPathNodeSetAddUnique(xmlNodeSetPtr cur, xmlNodePtr val) {
     if (val->type == XML_NAMESPACE_DECL) {
 	xmlNsPtr ns = (xmlNsPtr) val;
 
+        /* TODO: Check memory error. */
 	cur->nodeTab[cur->nodeNr++] =
 	    xmlXPathNodeSetDupNs((xmlNodePtr) ns->next, ns);
     } else
@@ -3830,7 +3841,7 @@ xmlXPathNodeSetMerge(xmlNodeSetPtr val1, xmlNodeSetPtr val2) {
 	*  xmlXPathNodeSetDupNs() to the set; thus a pure
 	*  memcpy is not possible.
 	*  If there was a flag on the nodesetval, indicating that
-	*  some temporary nodes are in, that would be helpfull.
+	*  some temporary nodes are in, that would be helpful.
 	*/
 	/*
 	* Optimization: Create an equally sized node-set
@@ -3912,6 +3923,7 @@ xmlXPathNodeSetMerge(xmlNodeSetPtr val1, xmlNodeSetPtr val2) {
 	if (n2->type == XML_NAMESPACE_DECL) {
 	    xmlNsPtr ns = (xmlNsPtr) n2;
 
+            /* TODO: Check memory error. */
 	    val1->nodeTab[val1->nodeNr++] =
 		xmlXPathNodeSetDupNs((xmlNodePtr) ns->next, ns);
 	} else
@@ -3926,49 +3938,23 @@ xmlXPathNodeSetMerge(xmlNodeSetPtr val1, xmlNodeSetPtr val2) {
  * xmlXPathNodeSetMergeAndClear:
  * @set1:  the first NodeSet or NULL
  * @set2:  the second NodeSet
- * @hasSet2NsNodes: 1 if set2 contains namespaces nodes
  *
- * Merges two nodesets, all nodes from @set2 are added to @set1
- * if @set1 is NULL, a new set is created and copied from @set2.
+ * Merges two nodesets, all nodes from @set2 are added to @set1.
  * Checks for duplicate nodes. Clears set2.
  *
  * Returns @set1 once extended or NULL in case of error.
  */
 static xmlNodeSetPtr
-xmlXPathNodeSetMergeAndClear(xmlNodeSetPtr set1, xmlNodeSetPtr set2,
-			     int hasNullEntries)
+xmlXPathNodeSetMergeAndClear(xmlNodeSetPtr set1, xmlNodeSetPtr set2)
 {
-    if ((set1 == NULL) && (hasNullEntries == 0)) {
-	/*
-	* Note that doing a memcpy of the list, namespace nodes are
-	* just assigned to set1, since set2 is cleared anyway.
-	*/
-	set1 = xmlXPathNodeSetCreateSize(set2->nodeNr);
-	if (set1 == NULL)
-	    return(NULL);
-	if (set2->nodeNr != 0) {
-	    memcpy(set1->nodeTab, set2->nodeTab,
-		set2->nodeNr * sizeof(xmlNodePtr));
-	    set1->nodeNr = set2->nodeNr;
-	}
-    } else {
+    {
 	int i, j, initNbSet1;
 	xmlNodePtr n1, n2;
 
-	if (set1 == NULL)
-            set1 = xmlXPathNodeSetCreate(NULL);
-        if (set1 == NULL)
-            return (NULL);
-
 	initNbSet1 = set1->nodeNr;
 	for (i = 0;i < set2->nodeNr;i++) {
 	    n2 = set2->nodeTab[i];
 	    /*
-	    * Skip NULLed entries.
-	    */
-	    if (n2 == NULL)
-		continue;
-	    /*
 	    * Skip duplicates.
 	    */
 	    for (j = 0; j < initNbSet1; j++) {
@@ -4033,49 +4019,21 @@ skip_node:
  * xmlXPathNodeSetMergeAndClearNoDupls:
  * @set1:  the first NodeSet or NULL
  * @set2:  the second NodeSet
- * @hasSet2NsNodes: 1 if set2 contains namespaces nodes
  *
- * Merges two nodesets, all nodes from @set2 are added to @set1
- * if @set1 is NULL, a new set is created and copied from @set2.
- * Doesn't chack for duplicate nodes. Clears set2.
+ * Merges two nodesets, all nodes from @set2 are added to @set1.
+ * Doesn't check for duplicate nodes. Clears set2.
  *
  * Returns @set1 once extended or NULL in case of error.
  */
 static xmlNodeSetPtr
-xmlXPathNodeSetMergeAndClearNoDupls(xmlNodeSetPtr set1, xmlNodeSetPtr set2,
-				    int hasNullEntries)
+xmlXPathNodeSetMergeAndClearNoDupls(xmlNodeSetPtr set1, xmlNodeSetPtr set2)
 {
-    if (set2 == NULL)
-	return(set1);
-    if ((set1 == NULL) && (hasNullEntries == 0)) {
-	/*
-	* Note that doing a memcpy of the list, namespace nodes are
-	* just assigned to set1, since set2 is cleared anyway.
-	*/
-	set1 = xmlXPathNodeSetCreateSize(set2->nodeNr);
-	if (set1 == NULL)
-	    return(NULL);
-	if (set2->nodeNr != 0) {
-	    memcpy(set1->nodeTab, set2->nodeTab,
-		set2->nodeNr * sizeof(xmlNodePtr));
-	    set1->nodeNr = set2->nodeNr;
-	}
-    } else {
+    {
 	int i;
 	xmlNodePtr n2;
 
-	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;
 	    if (set1->nodeMax == 0) {
 		set1->nodeTab = (xmlNodePtr *) xmlMalloc(
 		    XML_NODESET_DEFAULT * sizeof(xmlNodePtr));
@@ -4346,6 +4304,7 @@ xmlXPathNewNodeSet(xmlNodePtr val) {
     memset(ret, 0 , (size_t) sizeof(xmlXPathObject));
     ret->type = XPATH_NODESET;
     ret->boolval = 0;
+    /* TODO: Check memory error. */
     ret->nodesetval = xmlXPathNodeSetCreate(val);
     /* @@ with_ns to check whether namespace nodes should be looked at @@ */
 #ifdef XP_DEBUG_OBJ_USAGE
@@ -4406,6 +4365,7 @@ xmlXPathNewNodeSetList(xmlNodeSetPtr val)
         ret = xmlXPathNewNodeSet(val->nodeTab[0]);
         if (ret) {
             for (i = 1; i < val->nodeNr; ++i) {
+                /* TODO: Propagate memory error. */
                 if (xmlXPathNodeSetAddUnique(ret->nodesetval, val->nodeTab[i])
 		    < 0) break;
 	    }
@@ -4477,6 +4437,7 @@ xmlXPathDifference (xmlNodeSetPtr nodes1, xmlNodeSetPtr nodes2) {
     if (xmlXPathNodeSetIsEmpty(nodes2))
 	return(nodes1);
 
+    /* TODO: Check memory error. */
     ret = xmlXPathNodeSetCreate(NULL);
     if (xmlXPathNodeSetIsEmpty(nodes1))
 	return(ret);
@@ -4486,6 +4447,7 @@ xmlXPathDifference (xmlNodeSetPtr nodes1, xmlNodeSetPtr nodes2) {
     for (i = 0; i < l1; i++) {
 	cur = xmlXPathNodeSetItem(nodes1, i);
 	if (!xmlXPathNodeSetContains(nodes2, cur)) {
+            /* TODO: Propagate memory error. */
 	    if (xmlXPathNodeSetAddUnique(ret, cur) < 0)
 	        break;
 	}
@@ -4522,6 +4484,7 @@ xmlXPathIntersection (xmlNodeSetPtr nodes1, xmlNodeSetPtr nodes2) {
     for (i = 0; i < l1; i++) {
 	cur = xmlXPathNodeSetItem(nodes1, i);
 	if (xmlXPathNodeSetContains(nodes2, cur)) {
+            /* TODO: Propagate memory error. */
 	    if (xmlXPathNodeSetAddUnique(ret, cur) < 0)
 	        break;
 	}
@@ -4560,6 +4523,7 @@ xmlXPathDistinctSorted (xmlNodeSetPtr nodes) {
 	strval = xmlXPathCastNodeToString(cur);
 	if (xmlHashLookup(hash, strval) == NULL) {
 	    xmlHashAddEntry(hash, strval, strval);
+            /* TODO: Propagate memory error. */
 	    if (xmlXPathNodeSetAddUnique(ret, cur) < 0)
 	        break;
 	} else {
@@ -4653,6 +4617,7 @@ xmlXPathNodeLeadingSorted (xmlNodeSetPtr nodes, xmlNodePtr node) {
 	cur = xmlXPathNodeSetItem(nodes, i);
 	if (cur == node)
 	    break;
+        /* TODO: Propagate memory error. */
 	if (xmlXPathNodeSetAddUnique(ret, cur) < 0)
 	    break;
     }
@@ -4758,6 +4723,7 @@ xmlXPathNodeTrailingSorted (xmlNodeSetPtr nodes, xmlNodePtr node) {
 	cur = xmlXPathNodeSetItem(nodes, i);
 	if (cur == node)
 	    break;
+        /* TODO: Propagate memory error. */
 	if (xmlXPathNodeSetAddUnique(ret, cur) < 0)
 	    break;
     }
@@ -5457,6 +5423,7 @@ xmlXPathObjectCopy(xmlXPathObjectPtr val) {
 	    break;
 #endif
 	case XPATH_NODESET:
+            /* TODO: Check memory error. */
 	    ret->nodesetval = xmlXPathNodeSetMerge(NULL, val->nodesetval);
 	    /* Do not deallocate the copied tree value */
 	    ret->boolval = 0;
@@ -5944,7 +5911,7 @@ xmlXPathCastToNumber(xmlXPathObjectPtr val) {
 	return(NAN);
     switch (val->type) {
     case XPATH_UNDEFINED:
-#ifdef DEGUB_EXPR
+#ifdef DEBUG_EXPR
 	xmlGenericError(xmlGenericErrorContext, "NUMBER: undefined\n");
 #endif
 	ret = NAN;
@@ -6153,6 +6120,9 @@ xmlXPathNewContext(xmlDocPtr doc) {
     ret->contextSize = -1;
     ret->proximityPosition = -1;
 
+    ret->maxDepth = INT_MAX;
+    ret->maxParserDepth = INT_MAX;
+
 #ifdef XP_DEFAULT_CACHE_ON
     if (xmlXPathContextSetCache(ret, 1, -1, 0) == -1) {
 	xmlXPathFreeContext(ret);
@@ -6643,6 +6613,7 @@ xmlXPathCompareNodeSets(int inf, int strict,
 
     values2 = (double *) xmlMalloc(ns2->nodeNr * sizeof(double));
     if (values2 == NULL) {
+        /* TODO: Propagate memory error. */
         xmlXPathErrMemory(NULL, "comparing nodesets\n");
 	xmlXPathFreeObject(arg1);
 	xmlXPathFreeObject(arg2);
@@ -6903,11 +6874,13 @@ xmlXPathEqualNodeSets(xmlXPathObjectPtr arg1, xmlXPathObjectPtr arg2, int neq) {
 
     values1 = (xmlChar **) xmlMalloc(ns1->nodeNr * sizeof(xmlChar *));
     if (values1 == NULL) {
+        /* TODO: Propagate memory error. */
         xmlXPathErrMemory(NULL, "comparing nodesets\n");
 	return(0);
     }
     hashs1 = (unsigned int *) xmlMalloc(ns1->nodeNr * sizeof(unsigned int));
     if (hashs1 == NULL) {
+        /* TODO: Propagate memory error. */
         xmlXPathErrMemory(NULL, "comparing nodesets\n");
 	xmlFree(values1);
 	return(0);
@@ -6915,6 +6888,7 @@ xmlXPathEqualNodeSets(xmlXPathObjectPtr arg1, xmlXPathObjectPtr arg2, int neq) {
     memset(values1, 0, ns1->nodeNr * sizeof(xmlChar *));
     values2 = (xmlChar **) xmlMalloc(ns2->nodeNr * sizeof(xmlChar *));
     if (values2 == NULL) {
+        /* TODO: Propagate memory error. */
         xmlXPathErrMemory(NULL, "comparing nodesets\n");
 	xmlFree(hashs1);
 	xmlFree(values1);
@@ -6922,6 +6896,7 @@ xmlXPathEqualNodeSets(xmlXPathObjectPtr arg1, xmlXPathObjectPtr arg2, int neq) {
     }
     hashs2 = (unsigned int *) xmlMalloc(ns2->nodeNr * sizeof(unsigned int));
     if (hashs2 == NULL) {
+        /* TODO: Propagate memory error. */
         xmlXPathErrMemory(NULL, "comparing nodesets\n");
 	xmlFree(hashs1);
 	xmlFree(values1);
@@ -7551,6 +7526,7 @@ xmlXPathMultValues(xmlXPathParserContextPtr ctxt) {
  * The numeric operators convert their operands to numbers as if
  * by calling the number function.
  */
+ATTRIBUTE_NO_SANITIZE("float-divide-by-zero")
 void
 xmlXPathDivValues(xmlXPathParserContextPtr ctxt) {
     xmlXPathObjectPtr arg;
@@ -7623,7 +7599,7 @@ typedef xmlNodePtr (*xmlXPathTraversalFunctionExt)
  * Used for merging node sets in xmlXPathCollectAndTest().
  */
 typedef xmlNodeSetPtr (*xmlXPathNodeSetMergeFunction)
-		    (xmlNodeSetPtr, xmlNodeSetPtr, int);
+		    (xmlNodeSetPtr, xmlNodeSetPtr);
 
 
 /**
@@ -8562,28 +8538,9 @@ xmlXPathCountFunction(xmlXPathParserContextPtr ctxt, int nargs) {
 
     if ((cur == NULL) || (cur->nodesetval == NULL))
 	valuePush(ctxt, xmlXPathCacheNewFloat(ctxt->context, (double) 0));
-    else if ((cur->type == XPATH_NODESET) || (cur->type == XPATH_XSLT_TREE)) {
+    else
 	valuePush(ctxt, xmlXPathCacheNewFloat(ctxt->context,
 	    (double) cur->nodesetval->nodeNr));
-    } else {
-	if ((cur->nodesetval->nodeNr != 1) ||
-	    (cur->nodesetval->nodeTab == NULL)) {
-	    valuePush(ctxt, xmlXPathCacheNewFloat(ctxt->context, (double) 0));
-	} else {
-	    xmlNodePtr tmp;
-	    int i = 0;
-
-	    tmp = cur->nodesetval->nodeTab[0];
-	    if ((tmp != NULL) && (tmp->type != XML_NAMESPACE_DECL)) {
-		tmp = tmp->children;
-		while (tmp != NULL) {
-		    tmp = tmp->next;
-		    i++;
-		}
-	    }
-	    valuePush(ctxt, xmlXPathCacheNewFloat(ctxt->context, (double) i));
-	}
-    }
     xmlXPathReleaseObject(ctxt->context, cur);
 }
 
@@ -8621,7 +8578,7 @@ xmlXPathGetElementsByIds (xmlDocPtr doc, const xmlChar *ids) {
 	     * We used to check the fact that the value passed
 	     * was an NCName, but this generated much troubles for
 	     * me and Aleksey Sanin, people blatantly violated that
-	     * constaint, like Visa3D spec.
+	     * constraint, like Visa3D spec.
 	     * if (xmlValidateNCName(ID, 1) == 0)
 	     */
 	    attr = xmlGetID(doc, ID);
@@ -8632,6 +8589,7 @@ xmlXPathGetElementsByIds (xmlDocPtr doc, const xmlChar *ids) {
 		    elem = (xmlNodePtr) attr;
 		else
 		    elem = NULL;
+                /* TODO: Check memory error. */
 		if (elem != NULL)
 		    xmlXPathNodeSetAdd(ret, elem);
 	    }
@@ -8675,18 +8633,15 @@ xmlXPathIdFunction(xmlXPathParserContextPtr ctxt, int nargs) {
 	xmlNodeSetPtr ns;
 	int i;
 
+        /* TODO: Check memory error. */
 	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++) {
 		tokens =
 		    xmlXPathCastNodeToString(obj->nodesetval->nodeTab[i]);
 		ns = xmlXPathGetElementsByIds(ctxt->context->doc, tokens);
+                /* TODO: Check memory error. */
 		ret = xmlXPathNodeSetMerge(ret, ns);
 		xmlXPathFreeNodeSet(ns);
 		if (tokens != NULL)
@@ -8698,6 +8653,7 @@ xmlXPathIdFunction(xmlXPathParserContextPtr ctxt, int nargs) {
 	return;
     }
     obj = xmlXPathCacheConvertString(ctxt->context, obj);
+    if (obj == NULL) return;
     ret = xmlXPathGetElementsByIds(ctxt->context->doc, obj->stringval);
     valuePush(ctxt, xmlXPathCacheWrapNodeSet(ctxt->context, ret));
     xmlXPathReleaseObject(ctxt->context, obj);
@@ -9135,8 +9091,7 @@ void
 xmlXPathSubstringFunction(xmlXPathParserContextPtr ctxt, int nargs) {
     xmlXPathObjectPtr str, start, len;
     double le=0, in;
-    int i, l, m;
-    xmlChar *ret;
+    int i = 1, j = INT_MAX;
 
     if (nargs < 2) {
 	CHECK_ARITY(2);
@@ -9163,67 +9118,42 @@ xmlXPathSubstringFunction(xmlXPathParserContextPtr ctxt, int nargs) {
     CAST_TO_STRING;
     CHECK_TYPE(XPATH_STRING);
     str = valuePop(ctxt);
-    m = xmlUTF8Strlen((const unsigned char *)str->stringval);
 
-    /*
-     * If last pos not present, calculate last position
-    */
-    if (nargs != 3) {
-	le = (double)m;
-	if (in < 1.0)
-	    in = 1.0;
+    if (!(in < INT_MAX)) { /* Logical NOT to handle NaNs */
+        i = INT_MAX;
+    } else if (in >= 1.0) {
+        i = (int)in;
+        if (in - floor(in) >= 0.5)
+            i += 1;
     }
 
-    /* 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 (!xmlXPathIsInf(in) && !xmlXPathIsNaN(in + le)) {
-        /*
-         * To meet the requirements of the spec, the arguments
-	 * must be converted to integer format before
-	 * initial index calculations are done
-         *
-         * First we go to integer form, rounding up
-	 * and checking for special cases
-         */
-        i = (int) in;
-        if (((double)i)+0.5 <= in) i++;
-
-	if (xmlXPathIsInf(le) == 1) {
-	    l = m;
-	    if (i < 1)
-		i = 1;
-	}
-	else if (xmlXPathIsInf(le) == -1 || le < 0.0)
-	    l = 0;
-	else {
-	    l = (int) le;
-	    if (((double)l)+0.5 <= le) l++;
-	}
+    if (nargs == 3) {
+        double rin, rle, end;
 
-	/* Now we normalize inidices */
-        i -= 1;
-        l += i;
-        if (i < 0)
-            i = 0;
-        if (l > m)
-            l = m;
+        rin = floor(in);
+        if (in - rin >= 0.5)
+            rin += 1.0;
 
-        /* number of chars to copy */
-        l -= i;
+        rle = floor(le);
+        if (le - rle >= 0.5)
+            rle += 1.0;
 
-        ret = xmlUTF8Strsub(str->stringval, i, l);
-    }
-    else {
-        ret = NULL;
+        end = rin + rle;
+        if (!(end >= 1.0)) { /* Logical NOT to handle NaNs */
+            j = 1;
+        } else if (end < INT_MAX) {
+            j = (int)end;
+        }
     }
-    if (ret == NULL)
-	valuePush(ctxt, xmlXPathCacheNewCString(ctxt->context, ""));
-    else {
+
+    if (i < j) {
+        xmlChar *ret = xmlUTF8Strsub(str->stringval, i - 1, j - i);
 	valuePush(ctxt, xmlXPathCacheNewString(ctxt->context, ret));
 	xmlFree(ret);
+    } else {
+	valuePush(ctxt, xmlXPathCacheNewCString(ctxt->context, ""));
     }
+
     xmlXPathReleaseObject(ctxt->context, str);
 }
 
@@ -9682,7 +9612,12 @@ xmlXPathCeilingFunction(xmlXPathParserContextPtr ctxt, int nargs) {
     CAST_TO_NUMBER;
     CHECK_TYPE(XPATH_NUMBER);
 
+#ifdef _AIX
+    /* Work around buggy ceil() function on AIX */
+    ctxt->value->floatval = copysign(ceil(ctxt->value->floatval), ctxt->value->floatval);
+#else
     ctxt->value->floatval = ceil(ctxt->value->floatval);
+#endif
 }
 
 /**
@@ -9999,15 +9934,19 @@ xmlXPathParseNameComplex(xmlXPathParserContextPtr ctxt, int qualified) {
 		   (IS_COMBINING(c)) ||
 		   (IS_EXTENDER(c))) {
 		if (len + 10 > max) {
+                    xmlChar *tmp;
                     if (max > XML_MAX_NAME_LENGTH) {
+                        xmlFree(buffer);
                         XP_ERRORNULL(XPATH_EXPR_ERROR);
                     }
 		    max *= 2;
-		    buffer = (xmlChar *) xmlRealloc(buffer,
-			                            max * sizeof(xmlChar));
-		    if (buffer == NULL) {
+		    tmp = (xmlChar *) xmlRealloc(buffer,
+			                         max * sizeof(xmlChar));
+		    if (tmp == NULL) {
+                        xmlFree(buffer);
 			XP_ERRORNULL(XPATH_MEMORY_ERROR);
 		    }
+                    buffer = tmp;
 		}
 		COPY_BUF(l,buffer,len,c);
 		NEXTL(l);
@@ -10899,10 +10838,7 @@ xmlXPathCompRelationalExpr(xmlXPathParserContextPtr ctxt) {
     xmlXPathCompAdditiveExpr(ctxt);
     CHECK_ERROR;
     SKIP_BLANKS;
-    while ((CUR == '<') ||
-           (CUR == '>') ||
-           ((CUR == '<') && (NXT(1) == '=')) ||
-           ((CUR == '>') && (NXT(1) == '='))) {
+    while ((CUR == '<') || (CUR == '>')) {
 	int inf, strict;
 	int op1 = ctxt->comp->last;
 
@@ -10995,6 +10931,14 @@ xmlXPathCompAndExpr(xmlXPathParserContextPtr ctxt) {
  */
 static void
 xmlXPathCompileExpr(xmlXPathParserContextPtr ctxt, int sort) {
+    xmlXPathContextPtr xpctxt = ctxt->context;
+
+    if (xpctxt != NULL) {
+        if (xpctxt->depth >= xpctxt->maxParserDepth)
+            XP_ERROR(XPATH_RECURSION_LIMIT_EXCEEDED);
+        xpctxt->depth += 1;
+    }
+
     xmlXPathCompAndExpr(ctxt);
     CHECK_ERROR;
     SKIP_BLANKS;
@@ -11016,6 +10960,9 @@ xmlXPathCompileExpr(xmlXPathParserContextPtr ctxt, int sort) {
 	*/
 	PUSH_UNARY_EXPR(XPATH_OP_SORT, ctxt->comp->last , 0, 0);
     }
+
+    if (xpctxt != NULL)
+        xpctxt->depth -= 1;
 }
 
 /**
@@ -11634,366 +11581,300 @@ xmlXPathDebugDumpStepAxis(xmlXPathStepOpPtr op,
 }
 #endif /* DEBUG_STEP */
 
-static int
-xmlXPathCompOpEvalPredicate(xmlXPathParserContextPtr ctxt,
-			    xmlXPathStepOpPtr op,
-			    xmlNodeSetPtr set,
-			    int contextSize,
-			    int hasNsNodes)
+/**
+ * xmlXPathNodeSetFilter:
+ * @ctxt:  the XPath Parser context
+ * @set: the node set to filter
+ * @filterOpIndex: the index of the predicate/filter op
+ * @minPos: minimum position in the filtered set (1-based)
+ * @maxPos: maximum position in the filtered set (1-based)
+ * @hasNsNodes: true if the node set may contain namespace nodes
+ *
+ * Filter a node set, keeping only nodes for which the predicate expression
+ * matches. Afterwards, keep only nodes between minPos and maxPos in the
+ * filtered result.
+ */
+static void
+xmlXPathNodeSetFilter(xmlXPathParserContextPtr ctxt,
+		      xmlNodeSetPtr set,
+		      int filterOpIndex,
+                      int minPos, int maxPos,
+		      int hasNsNodes)
 {
-    if (op->ch1 != -1) {
-	xmlXPathCompExprPtr comp = ctxt->comp;
-	/*
-	* Process inner predicates first.
-	*/
-	if (comp->steps[op->ch1].op != XPATH_OP_PREDICATE) {
-	    /*
-	    * TODO: raise an internal error.
-	    */
-	}
-	contextSize = xmlXPathCompOpEvalPredicate(ctxt,
-	    &comp->steps[op->ch1], set, contextSize, hasNsNodes);
-	CHECK_ERROR0;
-	if (contextSize <= 0)
-	    return(0);
+    xmlXPathContextPtr xpctxt;
+    xmlNodePtr oldnode;
+    xmlDocPtr olddoc;
+    xmlXPathStepOpPtr filterOp;
+    int oldcs, oldpp;
+    int i, j, pos;
+
+    if ((set == NULL) || (set->nodeNr == 0))
+        return;
+
+    /*
+    * Check if the node set contains a sufficient number of nodes for
+    * the requested range.
+    */
+    if (set->nodeNr < minPos) {
+        xmlXPathNodeSetClear(set, hasNsNodes);
+        return;
     }
-    if (op->ch2 != -1) {
-	xmlXPathContextPtr xpctxt = ctxt->context;
-	xmlNodePtr contextNode, oldContextNode;
-	xmlDocPtr oldContextDoc;
-        int oldcs, oldpp;
-	int i, res, contextPos = 0, newContextSize;
-	xmlXPathStepOpPtr exprOp;
-	xmlXPathObjectPtr contextObj = NULL, exprRes = NULL;
 
-#ifdef LIBXML_XPTR_ENABLED
-	/*
-	* URGENT TODO: Check the following:
-	*  We don't expect location sets if evaluating prediates, right?
-	*  Only filters should expect location sets, right?
-	*/
-#endif
-	/*
-	* SPEC XPath 1.0:
-	*  "For each node in the node-set to be filtered, the
-	*  PredicateExpr is evaluated with that node as the
-	*  context node, with the number of nodes in the
-	*  node-set as the context size, and with the proximity
-	*  position of the node in the node-set with respect to
-	*  the axis as the context position;"
-	* @oldset is the node-set" to be filtered.
-	*
-	* SPEC XPath 1.0:
-	*  "only predicates change the context position and
-	*  context size (see [2.4 Predicates])."
-	* Example:
-	*   node-set  context pos
-	*    nA         1
-	*    nB         2
-	*    nC         3
-	*   After applying predicate [position() > 1] :
-	*   node-set  context pos
-	*    nB         1
-	*    nC         2
-	*/
-	oldContextNode = xpctxt->node;
-	oldContextDoc = xpctxt->doc;
-        oldcs = xpctxt->contextSize;
-        oldpp = xpctxt->proximityPosition;
-	/*
-	* Get the expression of this predicate.
-	*/
-	exprOp = &ctxt->comp->steps[op->ch2];
-	newContextSize = 0;
-	for (i = 0; i < set->nodeNr; i++) {
-	    if (set->nodeTab[i] == NULL)
-		continue;
+    xpctxt = ctxt->context;
+    oldnode = xpctxt->node;
+    olddoc = xpctxt->doc;
+    oldcs = xpctxt->contextSize;
+    oldpp = xpctxt->proximityPosition;
+    filterOp = &ctxt->comp->steps[filterOpIndex];
 
-	    contextNode = set->nodeTab[i];
-	    xpctxt->node = contextNode;
-	    xpctxt->contextSize = contextSize;
-	    xpctxt->proximityPosition = ++contextPos;
+    xpctxt->contextSize = set->nodeNr;
 
-	    /*
-	    * Also set the xpath document in case things like
-	    * key() are evaluated in the predicate.
-	    */
-	    if ((contextNode->type != XML_NAMESPACE_DECL) &&
-		(contextNode->doc != NULL))
-		xpctxt->doc = contextNode->doc;
-	    /*
-	    * Evaluate the predicate expression with 1 context node
-	    * at a time; this node is packaged into a node set; this
-	    * node set is handed over to the evaluation mechanism.
-	    */
-	    if (contextObj == NULL)
-		contextObj = xmlXPathCacheNewNodeSet(xpctxt, contextNode);
-	    else {
-		if (xmlXPathNodeSetAddUnique(contextObj->nodesetval,
-		    contextNode) < 0) {
-		    ctxt->error = XPATH_MEMORY_ERROR;
-		    goto evaluation_exit;
-		}
-	    }
+    for (i = 0, j = 0, pos = 1; i < set->nodeNr; i++) {
+        xmlNodePtr node = set->nodeTab[i];
+        int res;
 
-	    valuePush(ctxt, contextObj);
+        xpctxt->node = node;
+        xpctxt->proximityPosition = i + 1;
 
-	    res = xmlXPathCompOpEvalToBoolean(ctxt, exprOp, 1);
+        /*
+        * Also set the xpath document in case things like
+        * key() are evaluated in the predicate.
+        *
+        * TODO: Get real doc for namespace nodes.
+        */
+        if ((node->type != XML_NAMESPACE_DECL) &&
+            (node->doc != NULL))
+            xpctxt->doc = node->doc;
 
-	    if ((ctxt->error != XPATH_EXPRESSION_OK) || (res == -1)) {
-		xmlXPathNodeSetClear(set, hasNsNodes);
-		newContextSize = 0;
-		goto evaluation_exit;
-	    }
+        res = xmlXPathCompOpEvalToBoolean(ctxt, filterOp, 1);
 
-	    if (res != 0) {
-		newContextSize++;
-	    } else {
-		/*
-		* Remove the entry from the initial node set.
-		*/
-		set->nodeTab[i] = NULL;
-		if (contextNode->type == XML_NAMESPACE_DECL)
-		    xmlXPathNodeSetFreeNs((xmlNsPtr) contextNode);
-	    }
-	    if (ctxt->value == contextObj) {
-		/*
-		* Don't free the temporary XPath object holding the
-		* context node, in order to avoid massive recreation
-		* inside this loop.
-		*/
-		valuePop(ctxt);
-		xmlXPathNodeSetClear(contextObj->nodesetval, hasNsNodes);
-	    } else {
-		/*
-		* TODO: The object was lost in the evaluation machinery.
-		*  Can this happen? Maybe in internal-error cases.
-		*/
-		contextObj = NULL;
-	    }
-	}
+        if (ctxt->error != XPATH_EXPRESSION_OK)
+            goto exit;
+        if (res < 0) {
+            /* Shouldn't happen */
+            xmlXPathErr(ctxt, XPATH_EXPR_ERROR);
+            goto exit;
+        }
 
-	if (contextObj != NULL) {
-	    if (ctxt->value == contextObj)
-		valuePop(ctxt);
-	    xmlXPathReleaseObject(xpctxt, contextObj);
-	}
-evaluation_exit:
-	if (exprRes != NULL)
-	    xmlXPathReleaseObject(ctxt->context, exprRes);
-	/*
-	* Reset/invalidate the context.
-	*/
-	xpctxt->node = oldContextNode;
-	xpctxt->doc = oldContextDoc;
-	xpctxt->contextSize = oldcs;
-	xpctxt->proximityPosition = oldpp;
-	return(newContextSize);
-    }
-    return(contextSize);
-}
+        if ((res != 0) && ((pos >= minPos) && (pos <= maxPos))) {
+            if (i != j) {
+                set->nodeTab[j] = node;
+                set->nodeTab[i] = NULL;
+            }
 
-static int
-xmlXPathCompOpEvalPositionalPredicate(xmlXPathParserContextPtr ctxt,
-				      xmlXPathStepOpPtr op,
-				      xmlNodeSetPtr set,
-				      int contextSize,
-				      int minPos,
-				      int maxPos,
-				      int hasNsNodes)
-{
-    if (op->ch1 != -1) {
-	xmlXPathCompExprPtr comp = ctxt->comp;
-	if (comp->steps[op->ch1].op != XPATH_OP_PREDICATE) {
-	    /*
-	    * TODO: raise an internal error.
-	    */
-	}
-	contextSize = xmlXPathCompOpEvalPredicate(ctxt,
-	    &comp->steps[op->ch1], set, contextSize, hasNsNodes);
-	CHECK_ERROR0;
-	if (contextSize <= 0)
-	    return(0);
+            j += 1;
+        } else {
+            /* Remove the entry from the initial node set. */
+            set->nodeTab[i] = NULL;
+            if (node->type == XML_NAMESPACE_DECL)
+                xmlXPathNodeSetFreeNs((xmlNsPtr) node);
+        }
+
+        if (res != 0) {
+            if (pos == maxPos) {
+                /* Clear remaining nodes and exit loop. */
+                if (hasNsNodes) {
+                    for (i++; i < set->nodeNr; i++) {
+                        node = set->nodeTab[i];
+                        if ((node != NULL) &&
+                            (node->type == XML_NAMESPACE_DECL))
+                            xmlXPathNodeSetFreeNs((xmlNsPtr) node);
+                    }
+                }
+                break;
+            }
+
+            pos += 1;
+        }
     }
-    /*
-    * Check if the node set contains a sufficient number of nodes for
-    * the requested range.
-    */
-    if (contextSize < minPos) {
-	xmlXPathNodeSetClear(set, hasNsNodes);
-	return(0);
+
+    set->nodeNr = j;
+
+    /* If too many elements were removed, shrink table to preserve memory. */
+    if ((set->nodeMax > XML_NODESET_DEFAULT) &&
+        (set->nodeNr < set->nodeMax / 2)) {
+        xmlNodePtr *tmp;
+        int nodeMax = set->nodeNr;
+
+        if (nodeMax < XML_NODESET_DEFAULT)
+            nodeMax = XML_NODESET_DEFAULT;
+        tmp = (xmlNodePtr *) xmlRealloc(set->nodeTab,
+                nodeMax * sizeof(xmlNodePtr));
+        if (tmp == NULL) {
+            xmlXPathPErrMemory(ctxt, "shrinking nodeset\n");
+        } else {
+            set->nodeTab = tmp;
+            set->nodeMax = nodeMax;
+        }
     }
-    if (op->ch2 == -1) {
-	/*
-	* TODO: Can this ever happen?
-	*/
-	return (contextSize);
-    } else {
-	xmlDocPtr oldContextDoc;
-        int oldcs, oldpp;
-	int i, pos = 0, newContextSize = 0, contextPos = 0, res;
-	xmlXPathStepOpPtr exprOp;
-	xmlXPathObjectPtr contextObj = NULL, exprRes = NULL;
-	xmlNodePtr oldContextNode, contextNode = NULL;
-	xmlXPathContextPtr xpctxt = ctxt->context;
-        int frame;
+
+exit:
+    xpctxt->node = oldnode;
+    xpctxt->doc = olddoc;
+    xpctxt->contextSize = oldcs;
+    xpctxt->proximityPosition = oldpp;
+}
 
 #ifdef LIBXML_XPTR_ENABLED
-	    /*
-	    * URGENT TODO: Check the following:
-	    *  We don't expect location sets if evaluating prediates, right?
-	    *  Only filters should expect location sets, right?
-	*/
-#endif /* LIBXML_XPTR_ENABLED */
+/**
+ * xmlXPathLocationSetFilter:
+ * @ctxt:  the XPath Parser context
+ * @locset: the location set to filter
+ * @filterOpIndex: the index of the predicate/filter op
+ * @minPos: minimum position in the filtered set (1-based)
+ * @maxPos: maximum position in the filtered set (1-based)
+ *
+ * Filter a location set, keeping only nodes for which the predicate
+ * expression matches. Afterwards, keep only nodes between minPos and maxPos
+ * in the filtered result.
+ */
+static void
+xmlXPathLocationSetFilter(xmlXPathParserContextPtr ctxt,
+		          xmlLocationSetPtr locset,
+		          int filterOpIndex,
+                          int minPos, int maxPos)
+{
+    xmlXPathContextPtr xpctxt;
+    xmlNodePtr oldnode;
+    xmlDocPtr olddoc;
+    xmlXPathStepOpPtr filterOp;
+    int oldcs, oldpp;
+    int i, j, pos;
 
-	/*
-	* Save old context.
-	*/
-	oldContextNode = xpctxt->node;
-	oldContextDoc = xpctxt->doc;
-        oldcs = xpctxt->contextSize;
-        oldpp = xpctxt->proximityPosition;
-	/*
-	* Get the expression of this predicate.
-	*/
-	exprOp = &ctxt->comp->steps[op->ch2];
-	for (i = 0; i < set->nodeNr; i++) {
-            xmlXPathObjectPtr tmp;
+    if ((locset == NULL) || (locset->locNr == 0) || (filterOpIndex == -1))
+        return;
 
-	    if (set->nodeTab[i] == NULL)
-		continue;
+    xpctxt = ctxt->context;
+    oldnode = xpctxt->node;
+    olddoc = xpctxt->doc;
+    oldcs = xpctxt->contextSize;
+    oldpp = xpctxt->proximityPosition;
+    filterOp = &ctxt->comp->steps[filterOpIndex];
 
-	    contextNode = set->nodeTab[i];
-	    xpctxt->node = contextNode;
-	    xpctxt->contextSize = contextSize;
-	    xpctxt->proximityPosition = ++contextPos;
+    xpctxt->contextSize = locset->locNr;
 
-	    /*
-	    * Initialize the new set.
-	    * Also set the xpath document in case things like
-	    * key() evaluation are attempted on the predicate
-	    */
-	    if ((contextNode->type != XML_NAMESPACE_DECL) &&
-		(contextNode->doc != NULL))
-		xpctxt->doc = contextNode->doc;
-	    /*
-	    * Evaluate the predicate expression with 1 context node
-	    * at a time; this node is packaged into a node set; this
-	    * node set is handed over to the evaluation mechanism.
-	    */
-	    if (contextObj == NULL)
-		contextObj = xmlXPathCacheNewNodeSet(xpctxt, contextNode);
-	    else {
-		if (xmlXPathNodeSetAddUnique(contextObj->nodesetval,
-		    contextNode) < 0) {
-		    ctxt->error = XPATH_MEMORY_ERROR;
-		    goto evaluation_exit;
-		}
-	    }
+    for (i = 0, j = 0, pos = 1; i < locset->locNr; i++) {
+        xmlNodePtr contextNode = locset->locTab[i]->user;
+        int res;
 
-	    valuePush(ctxt, contextObj);
-            frame = xmlXPathSetFrame(ctxt);
-	    res = xmlXPathCompOpEvalToBoolean(ctxt, exprOp, 1);
-            xmlXPathPopFrame(ctxt, frame);
-            tmp = valuePop(ctxt);
+        xpctxt->node = contextNode;
+        xpctxt->proximityPosition = i + 1;
 
-	    if ((ctxt->error != XPATH_EXPRESSION_OK) || (res == -1)) {
-                while (tmp != contextObj) {
-                    /*
-                     * Free up the result
-                     * then pop off contextObj, which will be freed later
-                     */
-                    xmlXPathReleaseObject(xpctxt, tmp);
-                    tmp = valuePop(ctxt);
+        /*
+        * Also set the xpath document in case things like
+        * key() are evaluated in the predicate.
+        *
+        * TODO: Get real doc for namespace nodes.
+        */
+        if ((contextNode->type != XML_NAMESPACE_DECL) &&
+            (contextNode->doc != NULL))
+            xpctxt->doc = contextNode->doc;
+
+        res = xmlXPathCompOpEvalToBoolean(ctxt, filterOp, 1);
+
+        if (ctxt->error != XPATH_EXPRESSION_OK)
+            goto exit;
+        if (res < 0) {
+            /* Shouldn't happen */
+            xmlXPathErr(ctxt, XPATH_EXPR_ERROR);
+            goto exit;
+        }
+
+        if ((res != 0) && ((pos >= minPos) && (pos <= maxPos))) {
+            if (i != j) {
+                locset->locTab[j] = locset->locTab[i];
+                locset->locTab[i] = NULL;
+            }
+
+            j += 1;
+        } else {
+            /* Remove the entry from the initial location set. */
+            xmlXPathFreeObject(locset->locTab[i]);
+            locset->locTab[i] = NULL;
+        }
+
+        if (res != 0) {
+            if (pos == maxPos) {
+                /* Clear remaining nodes and exit loop. */
+                for (i++; i < locset->locNr; i++) {
+                    xmlXPathFreeObject(locset->locTab[i]);
                 }
-		goto evaluation_error;
-	    }
-            /* push the result back onto the stack */
-            valuePush(ctxt, tmp);
+                break;
+            }
 
-	    if (res)
-		pos++;
+            pos += 1;
+        }
+    }
 
-	    if (res && (pos >= minPos) && (pos <= maxPos)) {
-		/*
-		* Fits in the requested range.
-		*/
-		newContextSize++;
-		if (minPos == maxPos) {
-		    /*
-		    * Only 1 node was requested.
-		    */
-		    if (contextNode->type == XML_NAMESPACE_DECL) {
-			/*
-			* As always: take care of those nasty
-			* namespace nodes.
-			*/
-			set->nodeTab[i] = NULL;
-		    }
-		    xmlXPathNodeSetClear(set, hasNsNodes);
-		    set->nodeNr = 1;
-		    set->nodeTab[0] = contextNode;
-		    goto evaluation_exit;
-		}
-		if (pos == maxPos) {
-		    /*
-		    * We are done.
-		    */
-		    xmlXPathNodeSetClearFromPos(set, i +1, hasNsNodes);
-		    goto evaluation_exit;
-		}
-	    } else {
-		/*
-		* Remove the entry from the initial node set.
-		*/
-		set->nodeTab[i] = NULL;
-		if (contextNode->type == XML_NAMESPACE_DECL)
-		    xmlXPathNodeSetFreeNs((xmlNsPtr) contextNode);
-	    }
-	    if (exprRes != NULL) {
-		xmlXPathReleaseObject(ctxt->context, exprRes);
-		exprRes = NULL;
-	    }
-	    if (ctxt->value == contextObj) {
-		/*
-		* Don't free the temporary XPath object holding the
-		* context node, in order to avoid massive recreation
-		* inside this loop.
-		*/
-		valuePop(ctxt);
-		xmlXPathNodeSetClear(contextObj->nodesetval, hasNsNodes);
-	    } else {
-		/*
-		* The object was lost in the evaluation machinery.
-		* Can this happen? Maybe in case of internal-errors.
-		*/
-		contextObj = NULL;
-	    }
-	}
-	goto evaluation_exit;
+    locset->locNr = j;
 
-evaluation_error:
-	xmlXPathNodeSetClear(set, hasNsNodes);
-	newContextSize = 0;
+    /* If too many elements were removed, shrink table to preserve memory. */
+    if ((locset->locMax > XML_NODESET_DEFAULT) &&
+        (locset->locNr < locset->locMax / 2)) {
+        xmlXPathObjectPtr *tmp;
+        int locMax = locset->locNr;
 
-evaluation_exit:
-	if (contextObj != NULL) {
-	    if (ctxt->value == contextObj)
-		valuePop(ctxt);
-	    xmlXPathReleaseObject(xpctxt, contextObj);
-	}
-	if (exprRes != NULL)
-	    xmlXPathReleaseObject(ctxt->context, exprRes);
+        if (locMax < XML_NODESET_DEFAULT)
+            locMax = XML_NODESET_DEFAULT;
+        tmp = (xmlXPathObjectPtr *) xmlRealloc(locset->locTab,
+                locMax * sizeof(xmlXPathObjectPtr));
+        if (tmp == NULL) {
+            xmlXPathPErrMemory(ctxt, "shrinking locset\n");
+        } else {
+            locset->locTab = tmp;
+            locset->locMax = locMax;
+        }
+    }
+
+exit:
+    xpctxt->node = oldnode;
+    xpctxt->doc = olddoc;
+    xpctxt->contextSize = oldcs;
+    xpctxt->proximityPosition = oldpp;
+}
+#endif /* LIBXML_XPTR_ENABLED */
+
+/**
+ * xmlXPathCompOpEvalPredicate:
+ * @ctxt:  the XPath Parser context
+ * @op: the predicate op
+ * @set: the node set to filter
+ * @minPos: minimum position in the filtered set (1-based)
+ * @maxPos: maximum position in the filtered set (1-based)
+ * @hasNsNodes: true if the node set may contain namespace nodes
+ *
+ * Filter a node set, keeping only nodes for which the sequence of predicate
+ * expressions matches. Afterwards, keep only nodes between minPos and maxPos
+ * in the filtered result.
+ */
+static void
+xmlXPathCompOpEvalPredicate(xmlXPathParserContextPtr ctxt,
+			    xmlXPathStepOpPtr op,
+			    xmlNodeSetPtr set,
+                            int minPos, int maxPos,
+			    int hasNsNodes)
+{
+    if (op->ch1 != -1) {
+	xmlXPathCompExprPtr comp = ctxt->comp;
 	/*
-	* Reset/invalidate the context.
+	* Process inner predicates first.
 	*/
-	xpctxt->node = oldContextNode;
-	xpctxt->doc = oldContextDoc;
-	xpctxt->contextSize = oldcs;
-	xpctxt->proximityPosition = oldpp;
-	return(newContextSize);
+	if (comp->steps[op->ch1].op != XPATH_OP_PREDICATE) {
+            xmlGenericError(xmlGenericErrorContext,
+                "xmlXPathCompOpEvalPredicate: Expected a predicate\n");
+            XP_ERROR(XPATH_INVALID_OPERAND);
+	}
+        if (ctxt->context->depth >= ctxt->context->maxDepth)
+            XP_ERROR(XPATH_RECURSION_LIMIT_EXCEEDED);
+        ctxt->context->depth += 1;
+	xmlXPathCompOpEvalPredicate(ctxt, &comp->steps[op->ch1], set,
+                                    1, set->nodeNr, hasNsNodes);
+        ctxt->context->depth -= 1;
+	CHECK_ERROR;
     }
-    return(contextSize);
+
+    if (op->ch2 != -1)
+        xmlXPathNodeSetFilter(ctxt, set, op->ch2, minPos, maxPos, hasNsNodes);
 }
 
 static int
@@ -12013,7 +11894,7 @@ xmlXPathIsPositionalPredicate(xmlXPathParserContextPtr ctxt,
     * 1) For predicates (XPATH_OP_PREDICATE):
     *    - an inner predicate operator
     * 2) For filters (XPATH_OP_FILTER):
-    *    - an inner filter operater OR
+    *    - an inner filter operator OR
     *    - an expression selecting the node set.
     *      E.g. "key('a', 'b')" or "(//foo | //bar)".
     */
@@ -12111,7 +11992,7 @@ xmlXPathNodeCollectAndTest(xmlXPathParserContextPtr ctxt,
     /* First predicate operator */
     xmlXPathStepOpPtr predOp;
     int maxPos; /* The requested position() (when a "[n]" predicate) */
-    int hasPredicateRange, hasAxisRange, pos, size, newSize;
+    int hasPredicateRange, hasAxisRange, pos;
     int breakOnFirstHit;
 
     xmlXPathTraversalFunction next = NULL;
@@ -12304,6 +12185,7 @@ xmlXPathNodeCollectAndTest(xmlXPathParserContextPtr ctxt,
 	if (seq == NULL) {
 	    seq = xmlXPathNodeSetCreate(NULL);
 	    if (seq == NULL) {
+                /* TODO: Propagate memory error. */
 		total = 0;
 		goto error;
 	    }
@@ -12315,6 +12197,9 @@ xmlXPathNodeCollectAndTest(xmlXPathParserContextPtr ctxt,
 	cur = NULL;
 	hasNsNodes = 0;
         do {
+            if (OP_LIMIT_EXCEEDED(ctxt, 1))
+                goto error;
+
             cur = next(ctxt, cur);
             if (cur == NULL)
                 break;
@@ -12522,7 +12407,8 @@ axis_range_end: /* ----------------------------------------------------- */
 	    outSeq = seq;
 	    seq = NULL;
 	} else
-	    outSeq = mergeAndClear(outSeq, seq, 0);
+            /* TODO: Check memory error. */
+	    outSeq = mergeAndClear(outSeq, seq);
 	/*
 	* Break if only a true/false result was requested.
 	*/
@@ -12539,7 +12425,8 @@ first_hit: /* ---------------------------------------------------------- */
 	    outSeq = seq;
 	    seq = NULL;
 	} else
-	    outSeq = mergeAndClear(outSeq, seq, 0);
+            /* TODO: Check memory error. */
+	    outSeq = mergeAndClear(outSeq, seq);
 	break;
 
 #ifdef DEBUG_STEP
@@ -12583,51 +12470,20 @@ apply_predicates: /* --------------------------------------------------- */
 	    * For the moment, I'll try to solve this with a recursive
 	    * function: xmlXPathCompOpEvalPredicate().
 	    */
-	    size = seq->nodeNr;
 	    if (hasPredicateRange != 0)
-		newSize = xmlXPathCompOpEvalPositionalPredicate(ctxt,
-		    predOp, seq, size, maxPos, maxPos, hasNsNodes);
+		xmlXPathCompOpEvalPredicate(ctxt, predOp, seq, maxPos, maxPos,
+					    hasNsNodes);
 	    else
-		newSize = xmlXPathCompOpEvalPredicate(ctxt,
-		    predOp, seq, size, hasNsNodes);
+		xmlXPathCompOpEvalPredicate(ctxt, predOp, seq, 1, seq->nodeNr,
+					    hasNsNodes);
 
 	    if (ctxt->error != XPATH_EXPRESSION_OK) {
 		total = 0;
 		goto error;
 	    }
-	    /*
-	    * Add the filtered set of nodes to the result node set.
-	    */
-	    if (newSize == 0) {
-		/*
-		* The predicates filtered all nodes out.
-		*/
-		xmlXPathNodeSetClear(seq, hasNsNodes);
-	    } else if (seq->nodeNr > 0) {
-		/*
-		* Add to result set.
-		*/
-		if (outSeq == NULL) {
-		    if (size != newSize) {
-			/*
-			* We need to merge and clear here, since
-			* the sequence will contained NULLed entries.
-			*/
-			outSeq = mergeAndClear(NULL, seq, 1);
-		    } else {
-			outSeq = seq;
-			seq = NULL;
-		    }
-		} else
-		    outSeq = mergeAndClear(outSeq, seq,
-			(size != newSize) ? 1: 0);
-		/*
-		* Break if only a true/false result was requested.
-		*/
-		if (toBool)
-		    break;
-	    }
-        } else if (seq->nodeNr > 0) {
+        }
+
+        if (seq->nodeNr > 0) {
 	    /*
 	    * Add to result set.
 	    */
@@ -12635,8 +12491,12 @@ apply_predicates: /* --------------------------------------------------- */
 		outSeq = seq;
 		seq = NULL;
 	    } else {
-		outSeq = mergeAndClear(outSeq, seq, 0);
+                /* TODO: Check memory error. */
+		outSeq = mergeAndClear(outSeq, seq);
 	    }
+
+            if (toBool)
+                break;
 	}
     }
 
@@ -12655,14 +12515,14 @@ error:
     xmlXPathReleaseObject(xpctxt, obj);
 
     /*
-    * Ensure we return at least an emtpy set.
+    * Ensure we return at least an empty set.
     */
     if (outSeq == NULL) {
 	if ((seq != NULL) && (seq->nodeNr == 0))
 	    outSeq = seq;
 	else
+            /* TODO: Check memory error. */
 	    outSeq = xmlXPathNodeSetCreate(NULL);
-        /* XXX what if xmlXPathNodeSetCreate returned NULL here? */
     }
     if ((seq != NULL) && (seq != outSeq)) {
 	 xmlXPathFreeNodeSet(seq);
@@ -12718,10 +12578,15 @@ xmlXPathCompOpEvalFirst(xmlXPathParserContextPtr ctxt,
     xmlXPathObjectPtr arg1, arg2;
 
     CHECK_ERROR0;
+    if (OP_LIMIT_EXCEEDED(ctxt, 1))
+        return(0);
+    if (ctxt->context->depth >= ctxt->context->maxDepth)
+        XP_ERROR0(XPATH_RECURSION_LIMIT_EXCEEDED);
+    ctxt->context->depth += 1;
     comp = ctxt->comp;
     switch (op->op) {
         case XPATH_OP_END:
-            return (0);
+            break;
         case XPATH_OP_UNION:
             total =
                 xmlXPathCompOpEvalFirst(ctxt, &comp->steps[op->ch1],
@@ -12735,11 +12600,11 @@ xmlXPathCompOpEvalFirst(xmlXPathParserContextPtr ctxt,
                  * limit tree traversing to first node in the result
                  */
 		/*
-		* OPTIMIZE TODO: This implicitely sorts
+		* OPTIMIZE TODO: This implicitly sorts
 		*  the result, even if not needed. E.g. if the argument
 		*  of the count() function, no sorting is needed.
 		* OPTIMIZE TODO: How do we know if the node-list wasn't
-		*  aready sorted?
+		*  already sorted?
 		*/
 		if (ctxt->value->nodesetval->nodeNr > 1)
 		    xmlXPathNodeSetSort(ctxt->value->nodesetval);
@@ -12758,7 +12623,19 @@ xmlXPathCompOpEvalFirst(xmlXPathParserContextPtr ctxt,
 	        xmlXPathReleaseObject(ctxt->context, arg2);
                 XP_ERROR0(XPATH_INVALID_TYPE);
             }
+            if ((ctxt->context->opLimit != 0) &&
+                (((arg1->nodesetval != NULL) &&
+                  (xmlXPathCheckOpLimit(ctxt,
+                                        arg1->nodesetval->nodeNr) < 0)) ||
+                 ((arg2->nodesetval != NULL) &&
+                  (xmlXPathCheckOpLimit(ctxt,
+                                        arg2->nodesetval->nodeNr) < 0)))) {
+	        xmlXPathReleaseObject(ctxt->context, arg1);
+	        xmlXPathReleaseObject(ctxt->context, arg2);
+                break;
+            }
 
+            /* TODO: Check memory error. */
             arg1->nodesetval = xmlXPathNodeSetMerge(arg1->nodesetval,
                                                     arg2->nodesetval);
             valuePush(ctxt, arg1);
@@ -12766,10 +12643,11 @@ xmlXPathCompOpEvalFirst(xmlXPathParserContextPtr ctxt,
             /* optimizer */
 	    if (total > cur)
 		xmlXPathCompSwap(op);
-            return (total + cur);
+            total += cur;
+            break;
         case XPATH_OP_ROOT:
             xmlXPathRoot(ctxt);
-            return (0);
+            break;
         case XPATH_OP_NODE:
             if (op->ch1 != -1)
                 total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
@@ -12779,22 +12657,22 @@ xmlXPathCompOpEvalFirst(xmlXPathParserContextPtr ctxt,
 	    CHECK_ERROR0;
 	    valuePush(ctxt, xmlXPathCacheNewNodeSet(ctxt->context,
 		ctxt->context->node));
-            return (total);
+            break;
         case XPATH_OP_COLLECT:{
                 if (op->ch1 == -1)
-                    return (total);
+                    break;
 
                 total = xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
 		CHECK_ERROR0;
 
                 total += xmlXPathNodeCollectAndTest(ctxt, op, first, NULL, 0);
-                return (total);
+                break;
             }
         case XPATH_OP_VALUE:
             valuePush(ctxt,
                       xmlXPathCacheObjectCopy(ctxt->context,
 			(xmlXPathObjectPtr) op->value4));
-            return (0);
+            break;
         case XPATH_OP_SORT:
             if (op->ch1 != -1)
                 total +=
@@ -12806,15 +12684,19 @@ xmlXPathCompOpEvalFirst(xmlXPathParserContextPtr ctxt,
                 && (ctxt->value->nodesetval != NULL)
 		&& (ctxt->value->nodesetval->nodeNr > 1))
                 xmlXPathNodeSetSort(ctxt->value->nodesetval);
-            return (total);
+            break;
 #ifdef XP_OPTIMIZED_FILTER_FIRST
 	case XPATH_OP_FILTER:
                 total += xmlXPathCompOpEvalFilterFirst(ctxt, op, first);
-            return (total);
+            break;
 #endif
         default:
-            return (xmlXPathCompOpEval(ctxt, op));
+            total += xmlXPathCompOpEval(ctxt, op);
+            break;
     }
+
+    ctxt->context->depth -= 1;
+    return(total);
 }
 
 /**
@@ -12837,10 +12719,15 @@ xmlXPathCompOpEvalLast(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op,
     xmlXPathObjectPtr arg1, arg2;
 
     CHECK_ERROR0;
+    if (OP_LIMIT_EXCEEDED(ctxt, 1))
+        return(0);
+    if (ctxt->context->depth >= ctxt->context->maxDepth)
+        XP_ERROR0(XPATH_RECURSION_LIMIT_EXCEEDED);
+    ctxt->context->depth += 1;
     comp = ctxt->comp;
     switch (op->op) {
         case XPATH_OP_END:
-            return (0);
+            break;
         case XPATH_OP_UNION:
             total =
                 xmlXPathCompOpEvalLast(ctxt, &comp->steps[op->ch1], last);
@@ -12876,7 +12763,19 @@ xmlXPathCompOpEvalLast(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op,
 	        xmlXPathReleaseObject(ctxt->context, arg2);
                 XP_ERROR0(XPATH_INVALID_TYPE);
             }
+            if ((ctxt->context->opLimit != 0) &&
+                (((arg1->nodesetval != NULL) &&
+                  (xmlXPathCheckOpLimit(ctxt,
+                                        arg1->nodesetval->nodeNr) < 0)) ||
+                 ((arg2->nodesetval != NULL) &&
+                  (xmlXPathCheckOpLimit(ctxt,
+                                        arg2->nodesetval->nodeNr) < 0)))) {
+	        xmlXPathReleaseObject(ctxt->context, arg1);
+	        xmlXPathReleaseObject(ctxt->context, arg2);
+                break;
+            }
 
+            /* TODO: Check memory error. */
             arg1->nodesetval = xmlXPathNodeSetMerge(arg1->nodesetval,
                                                     arg2->nodesetval);
             valuePush(ctxt, arg1);
@@ -12884,10 +12783,11 @@ xmlXPathCompOpEvalLast(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op,
             /* optimizer */
 	    if (total > cur)
 		xmlXPathCompSwap(op);
-            return (total + cur);
+            total += cur;
+            break;
         case XPATH_OP_ROOT:
             xmlXPathRoot(ctxt);
-            return (0);
+            break;
         case XPATH_OP_NODE:
             if (op->ch1 != -1)
                 total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
@@ -12897,22 +12797,22 @@ xmlXPathCompOpEvalLast(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op,
 	    CHECK_ERROR0;
 	    valuePush(ctxt, xmlXPathCacheNewNodeSet(ctxt->context,
 		ctxt->context->node));
-            return (total);
+            break;
         case XPATH_OP_COLLECT:{
                 if (op->ch1 == -1)
-                    return (0);
+                    break;
 
                 total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
 		CHECK_ERROR0;
 
                 total += xmlXPathNodeCollectAndTest(ctxt, op, NULL, last, 0);
-                return (total);
+                break;
             }
         case XPATH_OP_VALUE:
             valuePush(ctxt,
                       xmlXPathCacheObjectCopy(ctxt->context,
 			(xmlXPathObjectPtr) op->value4));
-            return (0);
+            break;
         case XPATH_OP_SORT:
             if (op->ch1 != -1)
                 total +=
@@ -12924,10 +12824,14 @@ xmlXPathCompOpEvalLast(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op,
                 && (ctxt->value->nodesetval != NULL)
 		&& (ctxt->value->nodesetval->nodeNr > 1))
                 xmlXPathNodeSetSort(ctxt->value->nodesetval);
-            return (total);
+            break;
         default:
-            return (xmlXPathCompOpEval(ctxt, op));
+            total += xmlXPathCompOpEval(ctxt, op);
+            break;
     }
+
+    ctxt->context->depth -= 1;
+    return (total);
 }
 
 #ifdef XP_OPTIMIZED_FILTER_FIRST
@@ -12937,13 +12841,7 @@ xmlXPathCompOpEvalFilterFirst(xmlXPathParserContextPtr ctxt,
 {
     int total = 0;
     xmlXPathCompExprPtr comp;
-    xmlXPathObjectPtr res;
-    xmlXPathObjectPtr obj;
-    xmlNodeSetPtr oldset;
-    xmlNodePtr oldnode;
-    xmlDocPtr oldDoc;
-    int oldcs, oldpp;
-    int i;
+    xmlNodeSetPtr set;
 
     CHECK_ERROR0;
     comp = ctxt->comp;
@@ -12998,205 +12896,27 @@ xmlXPathCompOpEvalFilterFirst(xmlXPathParserContextPtr ctxt,
     * Hum are we filtering the result of an XPointer expression
     */
     if (ctxt->value->type == XPATH_LOCATIONSET) {
-	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
-	* up a new locset.
-	*/
-	CHECK_TYPE0(XPATH_LOCATIONSET);
+        xmlLocationSetPtr locset = ctxt->value->user;
 
-	if ((ctxt->value->user == NULL) ||
-            (((xmlLocationSetPtr) ctxt->value->user)->locNr == 0))
-	    return (total);
-
-	obj = valuePop(ctxt);
-	oldlocset = obj->user;
-        oldnode = ctxt->context->node;
-        oldcs = ctxt->context->contextSize;
-        oldpp = ctxt->context->proximityPosition;
-
-	newlocset = xmlXPtrLocationSetCreate(NULL);
+        if (locset != NULL) {
+            xmlXPathLocationSetFilter(ctxt, locset, op->ch2, 1, 1);
+            if (locset->locNr > 0)
+                *first = (xmlNodePtr) locset->locTab[0]->user;
+        }
 
-	for (i = 0; i < oldlocset->locNr; i++) {
-	    /*
-	    * Run the evaluation with a node list made of a
-	    * single item in the nodelocset.
-	    */
-	    ctxt->context->node = oldlocset->locTab[i]->user;
-	    ctxt->context->contextSize = oldlocset->locNr;
-	    ctxt->context->proximityPosition = i + 1;
-	    if (tmp == NULL) {
-		tmp = xmlXPathCacheNewNodeSet(ctxt->context,
-		    ctxt->context->node);
-	    } else {
-		if (xmlXPathNodeSetAddUnique(tmp->nodesetval,
-		                             ctxt->context->node) < 0) {
-		    ctxt->error = XPATH_MEMORY_ERROR;
-		}
-	    }
-	    valuePush(ctxt, tmp);
-	    if (op->ch2 != -1)
-		total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
-	    if (ctxt->error != XPATH_EXPRESSION_OK) {
-                xmlXPtrFreeLocationSet(newlocset);
-                goto xptr_error;
-	    }
-	    /*
-	    * The result of the evaluation need to be tested to
-	    * decided whether the filter succeeded or not
-	    */
-	    res = valuePop(ctxt);
-	    if (xmlXPathEvaluatePredicateResult(ctxt, res)) {
-		xmlXPtrLocationSetAdd(newlocset,
-		    xmlXPathCacheObjectCopy(ctxt->context,
-			oldlocset->locTab[i]));
-	    }
-	    /*
-	    * Cleanup
-	    */
-	    if (res != NULL) {
-		xmlXPathReleaseObject(ctxt->context, res);
-	    }
-	    if (ctxt->value == tmp) {
-		valuePop(ctxt);
-		xmlXPathNodeSetClear(tmp->nodesetval, 1);
-		/*
-		* REVISIT TODO: Don't create a temporary nodeset
-		* for everly iteration.
-		*/
-		/* OLD: xmlXPathFreeObject(res); */
-	    } else
-		tmp = NULL;
-	    /*
-	    * Only put the first node in the result, then leave.
-	    */
-	    if (newlocset->locNr > 0) {
-		*first = (xmlNodePtr) oldlocset->locTab[i]->user;
-		break;
-	    }
-	}
-	if (tmp != NULL) {
-	    xmlXPathReleaseObject(ctxt->context, tmp);
-	}
-	/*
-	* The result is used as the new evaluation locset.
-	*/
-	valuePush(ctxt, xmlXPtrWrapLocationSet(newlocset));
-xptr_error:
-	xmlXPathReleaseObject(ctxt->context, obj);
-	ctxt->context->node = oldnode;
-	ctxt->context->contextSize = oldcs;
-	ctxt->context->proximityPosition = oldpp;
 	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
-    * up a new set.
-    */
     CHECK_TYPE0(XPATH_NODESET);
-
-    if ((ctxt->value->nodesetval != NULL) &&
-        (ctxt->value->nodesetval->nodeNr != 0)) {
-	xmlNodeSetPtr newset;
-	xmlXPathObjectPtr tmp = NULL;
-
-        obj = valuePop(ctxt);
-        oldset = obj->nodesetval;
-        oldnode = ctxt->context->node;
-        oldDoc = ctxt->context->doc;
-        oldcs = ctxt->context->contextSize;
-        oldpp = ctxt->context->proximityPosition;
-
-	/*
-	* 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
-	    * a single item in the nodeset.
-	    */
-	    ctxt->context->node = oldset->nodeTab[i];
-	    if ((oldset->nodeTab[i]->type != XML_NAMESPACE_DECL) &&
-		(oldset->nodeTab[i]->doc != NULL))
-		ctxt->context->doc = oldset->nodeTab[i]->doc;
-	    if (tmp == NULL) {
-		tmp = xmlXPathCacheNewNodeSet(ctxt->context,
-		    ctxt->context->node);
-	    } else {
-		if (xmlXPathNodeSetAddUnique(tmp->nodesetval,
-		                             ctxt->context->node) < 0) {
-		    ctxt->error = XPATH_MEMORY_ERROR;
-		}
-	    }
-	    valuePush(ctxt, tmp);
-	    ctxt->context->contextSize = oldset->nodeNr;
-	    ctxt->context->proximityPosition = i + 1;
-	    if (op->ch2 != -1)
-		total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
-	    if (ctxt->error != XPATH_EXPRESSION_OK) {
-		xmlXPathFreeNodeSet(newset);
-                goto error;
-	    }
-	    /*
-	    * The result of the evaluation needs to be tested to
-	    * decide whether the filter succeeded or not
-	    */
-	    res = valuePop(ctxt);
-	    if (xmlXPathEvaluatePredicateResult(ctxt, res)) {
-		if (xmlXPathNodeSetAdd(newset, oldset->nodeTab[i]) < 0)
-		    ctxt->error = XPATH_MEMORY_ERROR;
-	    }
-	    /*
-	    * Cleanup
-	    */
-	    if (res != NULL) {
-		xmlXPathReleaseObject(ctxt->context, res);
-	    }
-	    if (ctxt->value == tmp) {
-		valuePop(ctxt);
-		/*
-		* Don't free the temporary nodeset
-		* in order to avoid massive recreation inside this
-		* loop.
-		*/
-		xmlXPathNodeSetClear(tmp->nodesetval, 1);
-	    } else
-		tmp = NULL;
-	    /*
-	    * Only put the first node in the result, then leave.
-	    */
-	    if (newset->nodeNr > 0) {
-		*first = *(newset->nodeTab);
-		break;
-	    }
-	}
-	if (tmp != NULL) {
-	    xmlXPathReleaseObject(ctxt->context, tmp);
-	}
-	/*
-	* The result is used as the new evaluation set.
-	*/
-	valuePush(ctxt, xmlXPathCacheWrapNodeSet(ctxt->context, newset));
-error:
-	xmlXPathReleaseObject(ctxt->context, obj);
-	ctxt->context->node = oldnode;
-	ctxt->context->doc = oldDoc;
-	ctxt->context->contextSize = oldcs;
-	ctxt->context->proximityPosition = oldpp;
+    set = ctxt->value->nodesetval;
+    if (set != NULL) {
+        xmlXPathNodeSetFilter(ctxt, set, op->ch2, 1, 1, 1);
+        if (set->nodeNr > 0)
+            *first = set->nodeTab[0];
     }
-    return(total);
+
+    return (total);
 }
 #endif /* XP_OPTIMIZED_FILTER_FIRST */
 
@@ -13217,44 +12937,49 @@ xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op)
     xmlXPathObjectPtr arg1, arg2;
 
     CHECK_ERROR0;
+    if (OP_LIMIT_EXCEEDED(ctxt, 1))
+        return(0);
+    if (ctxt->context->depth >= ctxt->context->maxDepth)
+        XP_ERROR0(XPATH_RECURSION_LIMIT_EXCEEDED);
+    ctxt->context->depth += 1;
     comp = ctxt->comp;
     switch (op->op) {
         case XPATH_OP_END:
-            return (0);
+            break;
         case XPATH_OP_AND:
             total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
 	    CHECK_ERROR0;
             xmlXPathBooleanFunction(ctxt, 1);
             if ((ctxt->value == NULL) || (ctxt->value->boolval == 0))
-                return (total);
+                break;
             arg2 = valuePop(ctxt);
             total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
 	    if (ctxt->error) {
 		xmlXPathFreeObject(arg2);
-		return(0);
+		break;
 	    }
             xmlXPathBooleanFunction(ctxt, 1);
             if (ctxt->value != NULL)
                 ctxt->value->boolval &= arg2->boolval;
 	    xmlXPathReleaseObject(ctxt->context, arg2);
-            return (total);
+            break;
         case XPATH_OP_OR:
             total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
 	    CHECK_ERROR0;
             xmlXPathBooleanFunction(ctxt, 1);
             if ((ctxt->value == NULL) || (ctxt->value->boolval == 1))
-                return (total);
+                break;
             arg2 = valuePop(ctxt);
             total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
 	    if (ctxt->error) {
 		xmlXPathFreeObject(arg2);
-		return(0);
+		break;
 	    }
             xmlXPathBooleanFunction(ctxt, 1);
             if (ctxt->value != NULL)
                 ctxt->value->boolval |= arg2->boolval;
 	    xmlXPathReleaseObject(ctxt->context, arg2);
-            return (total);
+            break;
         case XPATH_OP_EQUAL:
             total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
 	    CHECK_ERROR0;
@@ -13265,7 +12990,7 @@ xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op)
 	    else
 		equal = xmlXPathNotEqualValues(ctxt);
 	    valuePush(ctxt, xmlXPathCacheNewBoolean(ctxt->context, equal));
-            return (total);
+            break;
         case XPATH_OP_CMP:
             total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
 	    CHECK_ERROR0;
@@ -13273,7 +12998,7 @@ xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op)
 	    CHECK_ERROR0;
             ret = xmlXPathCompareValues(ctxt, op->value, op->value2);
 	    valuePush(ctxt, xmlXPathCacheNewBoolean(ctxt->context, ret));
-            return (total);
+            break;
         case XPATH_OP_PLUS:
             total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
 	    CHECK_ERROR0;
@@ -13291,7 +13016,7 @@ xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op)
                 CAST_TO_NUMBER;
                 CHECK_TYPE0(XPATH_NUMBER);
             }
-            return (total);
+            break;
         case XPATH_OP_MULT:
             total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
 	    CHECK_ERROR0;
@@ -13303,7 +13028,7 @@ xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op)
                 xmlXPathDivValues(ctxt);
             else if (op->value == 2)
                 xmlXPathModValues(ctxt);
-            return (total);
+            break;
         case XPATH_OP_UNION:
             total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
 	    CHECK_ERROR0;
@@ -13318,21 +13043,33 @@ xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op)
 	        xmlXPathReleaseObject(ctxt->context, arg2);
                 XP_ERROR0(XPATH_INVALID_TYPE);
             }
+            if ((ctxt->context->opLimit != 0) &&
+                (((arg1->nodesetval != NULL) &&
+                  (xmlXPathCheckOpLimit(ctxt,
+                                        arg1->nodesetval->nodeNr) < 0)) ||
+                 ((arg2->nodesetval != NULL) &&
+                  (xmlXPathCheckOpLimit(ctxt,
+                                        arg2->nodesetval->nodeNr) < 0)))) {
+	        xmlXPathReleaseObject(ctxt->context, arg1);
+	        xmlXPathReleaseObject(ctxt->context, arg2);
+                break;
+            }
 
 	    if ((arg1->nodesetval == NULL) ||
 		((arg2->nodesetval != NULL) &&
 		 (arg2->nodesetval->nodeNr != 0)))
 	    {
+                /* TODO: Check memory error. */
 		arg1->nodesetval = xmlXPathNodeSetMerge(arg1->nodesetval,
 							arg2->nodesetval);
 	    }
 
             valuePush(ctxt, arg1);
 	    xmlXPathReleaseObject(ctxt->context, arg2);
-            return (total);
+            break;
         case XPATH_OP_ROOT:
             xmlXPathRoot(ctxt);
-            return (total);
+            break;
         case XPATH_OP_NODE:
             if (op->ch1 != -1)
                 total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
@@ -13342,22 +13079,22 @@ xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op)
 	    CHECK_ERROR0;
 	    valuePush(ctxt, xmlXPathCacheNewNodeSet(ctxt->context,
 		ctxt->context->node));
-            return (total);
+            break;
         case XPATH_OP_COLLECT:{
                 if (op->ch1 == -1)
-                    return (total);
+                    break;
 
                 total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
 		CHECK_ERROR0;
 
                 total += xmlXPathNodeCollectAndTest(ctxt, op, NULL, NULL, 0);
-                return (total);
+                break;
             }
         case XPATH_OP_VALUE:
             valuePush(ctxt,
                       xmlXPathCacheObjectCopy(ctxt->context,
 			(xmlXPathObjectPtr) op->value4));
-            return (total);
+            break;
         case XPATH_OP_VARIABLE:{
 		xmlXPathObjectPtr val;
 
@@ -13378,7 +13115,7 @@ xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op)
             "xmlXPathCompOpEval: variable %s bound to undefined prefix %s\n",
                                     (char *) op->value4, (char *)op->value5);
                         ctxt->error = XPATH_UNDEF_PREFIX_ERROR;
-                        return (total);
+                        break;
                     }
 		    val = xmlXPathVariableLookupNS(ctxt->context,
                                                        op->value4, URI);
@@ -13386,7 +13123,7 @@ xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op)
 			XP_ERROR0(XPATH_UNDEF_VARIABLE_ERROR);
                     valuePush(ctxt, val);
                 }
-                return (total);
+                break;
             }
         case XPATH_OP_FUNCTION:{
                 xmlXPathFunction func;
@@ -13400,7 +13137,7 @@ xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op)
                         xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
                     if (ctxt->error != XPATH_EXPRESSION_OK) {
                         xmlXPathPopFrame(ctxt, frame);
-                        return (total);
+                        break;
                     }
                 }
 		if (ctxt->valueNr < ctxt->valueFrame + op->value) {
@@ -13408,7 +13145,7 @@ xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op)
 			    "xmlXPathCompOpEval: parameter error\n");
 		    ctxt->error = XPATH_INVALID_OPERAND;
                     xmlXPathPopFrame(ctxt, frame);
-		    return (total);
+		    break;
 		}
 		for (i = 0; i < op->value; i++) {
 		    if (ctxt->valueTab[(ctxt->valueNr - 1) - i] == NULL) {
@@ -13416,7 +13153,7 @@ xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op)
 				"xmlXPathCompOpEval: parameter error\n");
 			ctxt->error = XPATH_INVALID_OPERAND;
                         xmlXPathPopFrame(ctxt, frame);
-			return (total);
+			break;
 		    }
                 }
                 if (op->cache != NULL)
@@ -13436,7 +13173,7 @@ xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op)
                                     (char *)op->value4, (char *)op->value5);
                             xmlXPathPopFrame(ctxt, frame);
                             ctxt->error = XPATH_UNDEF_PREFIX_ERROR;
-                            return (total);
+                            break;
                         }
                         func = xmlXPathFunctionLookupNS(ctxt->context,
                                                         op->value4, URI);
@@ -13457,8 +13194,11 @@ xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op)
                 func(ctxt, op->value);
                 ctxt->context->function = oldFunc;
                 ctxt->context->functionURI = oldFuncURI;
+                if ((ctxt->error == XPATH_EXPRESSION_OK) &&
+                    (ctxt->valueNr != ctxt->valueFrame + 1))
+                    XP_ERROR0(XPATH_STACK_ERROR);
                 xmlXPathPopFrame(ctxt, frame);
-                return (total);
+                break;
             }
         case XPATH_OP_ARG:
             if (op->ch1 != -1) {
@@ -13469,17 +13209,10 @@ xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op)
                 total += xmlXPathCompOpEval(ctxt, &comp->steps[op->ch2]);
 	        CHECK_ERROR0;
 	    }
-            return (total);
+            break;
         case XPATH_OP_PREDICATE:
         case XPATH_OP_FILTER:{
-                xmlXPathObjectPtr res;
-                xmlXPathObjectPtr obj, tmp;
-                xmlNodeSetPtr newset = NULL;
-                xmlNodeSetPtr oldset;
-                xmlNodePtr oldnode;
-		xmlDocPtr oldDoc;
-                int oldcs, oldpp;
-                int i;
+                xmlNodeSetPtr set;
 
                 /*
                  * Optimization for ()[1] selection i.e. the first elem
@@ -13491,7 +13224,7 @@ xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op)
 		    *  will result in an ordered list if we have an
 		    *  XPATH_OP_FILTER?
 		    *  What about an additional field or flag on
-		    *  xmlXPathObject like @sorted ? This way we wouln'd need
+		    *  xmlXPathObject like @sorted ? This way we wouldn't need
 		    *  to assume anything, so it would be more robust and
 		    *  easier to optimize.
 		    */
@@ -13523,7 +13256,7 @@ xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op)
                             (ctxt->value->nodesetval->nodeNr > 1))
                             xmlXPathNodeSetClearFromPos(ctxt->value->nodesetval,
                                                         1, 1);
-                        return (total);
+                        break;
                     }
                 }
                 /*
@@ -13558,7 +13291,7 @@ xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op)
                             (ctxt->value->nodesetval->nodeTab != NULL) &&
                             (ctxt->value->nodesetval->nodeNr > 1))
                             xmlXPathNodeSetKeepLast(ctxt->value->nodesetval);
-                        return (total);
+                        break;
                     }
                 }
 		/*
@@ -13577,224 +13310,28 @@ xmlXPathCompOpEval(xmlXPathParserContextPtr ctxt, xmlXPathStepOpPtr op)
                         xmlXPathCompOpEval(ctxt, &comp->steps[op->ch1]);
 		CHECK_ERROR0;
                 if (op->ch2 == -1)
-                    return (total);
+                    break;
                 if (ctxt->value == NULL)
-                    return (total);
+                    break;
 
 #ifdef LIBXML_XPTR_ENABLED
                 /*
                  * Hum are we filtering the result of an XPointer expression
                  */
                 if (ctxt->value->type == XPATH_LOCATIONSET) {
-                    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
-                     * up a new locset.
-                     */
-                    CHECK_TYPE0(XPATH_LOCATIONSET);
-
-                    if ((ctxt->value->user == NULL) ||
-                        (((xmlLocationSetPtr) ctxt->value->user)->locNr == 0))
-                        return (total);
-
-                    obj = valuePop(ctxt);
-                    oldlocset = obj->user;
-                    oldnode = ctxt->context->node;
-                    oldcs = ctxt->context->contextSize;
-                    oldpp = ctxt->context->proximityPosition;
-
-                    newlocset = xmlXPtrLocationSetCreate(NULL);
-
-                    for (i = 0; i < oldlocset->locNr; i++) {
-                        /*
-                         * Run the evaluation with a node list made of a
-                         * single item in the nodelocset.
-                         */
-                        ctxt->context->node = oldlocset->locTab[i]->user;
-                        ctxt->context->contextSize = oldlocset->locNr;
-                        ctxt->context->proximityPosition = i + 1;
-			tmp = xmlXPathCacheNewNodeSet(ctxt->context,
-			    ctxt->context->node);
-                        valuePush(ctxt, tmp);
-
-                        if (op->ch2 != -1)
-                            total +=
-                                xmlXPathCompOpEval(ctxt,
-                                                   &comp->steps[op->ch2]);
-			if (ctxt->error != XPATH_EXPRESSION_OK) {
-                            xmlXPtrFreeLocationSet(newlocset);
-                            goto filter_xptr_error;
-			}
-
-                        /*
-                         * The result of the evaluation need to be tested to
-                         * decided whether the filter succeeded or not
-                         */
-                        res = valuePop(ctxt);
-                        if (xmlXPathEvaluatePredicateResult(ctxt, res)) {
-                            xmlXPtrLocationSetAdd(newlocset,
-                                                  xmlXPathObjectCopy
-                                                  (oldlocset->locTab[i]));
-                        }
-
-                        /*
-                         * Cleanup
-                         */
-                        if (res != NULL) {
-			    xmlXPathReleaseObject(ctxt->context, res);
-			}
-                        if (ctxt->value == tmp) {
-                            res = valuePop(ctxt);
-			    xmlXPathReleaseObject(ctxt->context, res);
-                        }
-                    }
-
-                    /*
-                     * The result is used as the new evaluation locset.
-                     */
-                    valuePush(ctxt, xmlXPtrWrapLocationSet(newlocset));
-filter_xptr_error:
-		    xmlXPathReleaseObject(ctxt->context, obj);
-                    ctxt->context->node = oldnode;
-                    ctxt->context->contextSize = oldcs;
-                    ctxt->context->proximityPosition = oldpp;
-                    return (total);
+                    xmlLocationSetPtr locset = ctxt->value->user;
+                    xmlXPathLocationSetFilter(ctxt, locset, op->ch2,
+                                              1, locset->locNr);
+                    break;
                 }
 #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
-                 * up a new set.
-                 */
                 CHECK_TYPE0(XPATH_NODESET);
-
-                if ((ctxt->value->nodesetval != NULL) &&
-                    (ctxt->value->nodesetval->nodeNr != 0)) {
-                    obj = valuePop(ctxt);
-                    oldset = obj->nodesetval;
-                    oldnode = ctxt->context->node;
-                    oldDoc = ctxt->context->doc;
-                    oldcs = ctxt->context->contextSize;
-                    oldpp = ctxt->context->proximityPosition;
-		    tmp = NULL;
-                    /*
-                     * Initialize the new set.
-		     * Also set the xpath document in case things like
-		     * key() evaluation are attempted on the predicate
-                     */
-                    newset = xmlXPathNodeSetCreate(NULL);
-		    /*
-		    * SPEC XPath 1.0:
-		    *  "For each node in the node-set to be filtered, the
-		    *  PredicateExpr is evaluated with that node as the
-		    *  context node, with the number of nodes in the
-		    *  node-set as the context size, and with the proximity
-		    *  position of the node in the node-set with respect to
-		    *  the axis as the context position;"
-		    * @oldset is the node-set" to be filtered.
-		    *
-		    * SPEC XPath 1.0:
-		    *  "only predicates change the context position and
-		    *  context size (see [2.4 Predicates])."
-		    * Example:
-		    *   node-set  context pos
-		    *    nA         1
-		    *    nB         2
-		    *    nC         3
-		    *   After applying predicate [position() > 1] :
-		    *   node-set  context pos
-		    *    nB         1
-		    *    nC         2
-		    *
-		    * removed the first node in the node-set, then
-		    * the context position of the
-		    */
-                    for (i = 0; i < oldset->nodeNr; i++) {
-                        /*
-                         * Run the evaluation with a node list made of
-                         * a single item in the nodeset.
-                         */
-                        ctxt->context->node = oldset->nodeTab[i];
-			if ((oldset->nodeTab[i]->type != XML_NAMESPACE_DECL) &&
-			    (oldset->nodeTab[i]->doc != NULL))
-		            ctxt->context->doc = oldset->nodeTab[i]->doc;
-			if (tmp == NULL) {
-			    tmp = xmlXPathCacheNewNodeSet(ctxt->context,
-				ctxt->context->node);
-			} else {
-			    if (xmlXPathNodeSetAddUnique(tmp->nodesetval,
-				               ctxt->context->node) < 0) {
-				ctxt->error = XPATH_MEMORY_ERROR;
-			    }
-			}
-                        valuePush(ctxt, tmp);
-                        ctxt->context->contextSize = oldset->nodeNr;
-                        ctxt->context->proximityPosition = i + 1;
-			/*
-			* Evaluate the predicate against the context node.
-			* Can/should we optimize position() predicates
-			* here (e.g. "[1]")?
-			*/
-                        if (op->ch2 != -1)
-                            total +=
-                                xmlXPathCompOpEval(ctxt,
-                                                   &comp->steps[op->ch2]);
-			if (ctxt->error != XPATH_EXPRESSION_OK) {
-			    xmlXPathFreeNodeSet(newset);
-                            goto filter_error;
-			}
-
-                        /*
-                         * The result of the evaluation needs to be tested to
-                         * decide whether the filter succeeded or not
-                         */
-			/*
-			* OPTIMIZE TODO: Can we use
-			* xmlXPathNodeSetAdd*Unique()* instead?
-			*/
-                        res = valuePop(ctxt);
-                        if (xmlXPathEvaluatePredicateResult(ctxt, res)) {
-                            if (xmlXPathNodeSetAdd(newset, oldset->nodeTab[i])
-			        < 0)
-				ctxt->error = XPATH_MEMORY_ERROR;
-                        }
-
-                        /*
-                         * Cleanup
-                         */
-                        if (res != NULL) {
-			    xmlXPathReleaseObject(ctxt->context, res);
-			}
-                        if (ctxt->value == tmp) {
-                            valuePop(ctxt);
-			    xmlXPathNodeSetClear(tmp->nodesetval, 1);
-			    /*
-			    * Don't free the temporary nodeset
-			    * in order to avoid massive recreation inside this
-			    * loop.
-			    */
-                        } else
-			    tmp = NULL;
-                    }
-		    if (tmp != NULL)
-			xmlXPathReleaseObject(ctxt->context, tmp);
-                    /*
-                     * The result is used as the new evaluation set.
-                     */
-		    valuePush(ctxt,
-			xmlXPathCacheWrapNodeSet(ctxt->context, newset));
-filter_error:
-		    xmlXPathReleaseObject(ctxt->context, obj);
-		    ctxt->context->node = oldnode;
-		    ctxt->context->doc = oldDoc;
-                    ctxt->context->contextSize = oldcs;
-                    ctxt->context->proximityPosition = oldpp;
-                }
-                return (total);
+                set = ctxt->value->nodesetval;
+                if (set != NULL)
+                    xmlXPathNodeSetFilter(ctxt, set, op->ch2,
+                                          1, set->nodeNr, 1);
+                break;
             }
         case XPATH_OP_SORT:
             if (op->ch1 != -1)
@@ -13807,7 +13344,7 @@ filter_error:
 	    {
                 xmlXPathNodeSetSort(ctxt->value->nodesetval);
 	    }
-            return (total);
+            break;
 #ifdef LIBXML_XPTR_ENABLED
         case XPATH_OP_RANGETO:{
                 xmlXPathObjectPtr range;
@@ -13830,7 +13367,7 @@ filter_error:
                     XP_ERROR0(XPATH_INVALID_OPERAND);
                 }
                 if (op->ch2 == -1)
-                    return (total);
+                    break;
 
                 if (ctxt->value->type == XPATH_LOCATIONSET) {
                     /*
@@ -13842,7 +13379,7 @@ filter_error:
 
                     if ((ctxt->value->user == NULL) ||
                         (((xmlLocationSetPtr) ctxt->value->user)->locNr == 0))
-                        return (total);
+                        break;
 
                     obj = valuePop(ctxt);
                     oldlocset = obj->user;
@@ -13964,13 +13501,17 @@ rangeto_error:
                 ctxt->context->node = oldnode;
                 ctxt->context->contextSize = oldcs;
                 ctxt->context->proximityPosition = oldpp;
-                return (total);
+                break;
             }
 #endif /* LIBXML_XPTR_ENABLED */
+        default:
+            xmlGenericError(xmlGenericErrorContext,
+                            "XPath: unknown precompiled operation %d\n", op->op);
+            ctxt->error = XPATH_INVALID_OPERAND;
+            break;
     }
-    xmlGenericError(xmlGenericErrorContext,
-                    "XPath: unknown precompiled operation %d\n", op->op);
-    ctxt->error = XPATH_INVALID_OPERAND;
+
+    ctxt->context->depth -= 1;
     return (total);
 }
 
@@ -13990,6 +13531,8 @@ xmlXPathCompOpEvalToBoolean(xmlXPathParserContextPtr ctxt,
     xmlXPathObjectPtr resObj = NULL;
 
 start:
+    if (OP_LIMIT_EXCEEDED(ctxt, 1))
+        return(0);
     /* comp = ctxt->comp; */
     switch (op->op) {
         case XPATH_OP_END:
@@ -14116,12 +13659,14 @@ xmlXPathRunStreamEval(xmlXPathContextPtr ctxt, xmlPatternPtr comp,
 	    /* Select "/" */
 	    if (toBool)
 		return(1);
+            /* TODO: Check memory error. */
 	    xmlXPathNodeSetAddUnique((*resultSeq)->nodesetval,
 		                     (xmlNodePtr) ctxt->doc);
 	} else {
 	    /* Select "self::node()" */
 	    if (toBool)
 		return(1);
+            /* TODO: Check memory error. */
 	    xmlXPathNodeSetAddUnique((*resultSeq)->nodesetval, ctxt->node);
 	}
     }
@@ -14182,6 +13727,7 @@ xmlXPathRunStreamEval(xmlXPathContextPtr ctxt, xmlPatternPtr comp,
 	} else if (ret == 1) {
 	    if (toBool)
 		goto return_1;
+            /* TODO: Check memory error. */
 	    xmlXPathNodeSetAddUnique((*resultSeq)->nodesetval, cur);
 	}
     }
@@ -14189,6 +13735,16 @@ xmlXPathRunStreamEval(xmlXPathContextPtr ctxt, xmlPatternPtr comp,
     goto scan_children;
 next_node:
     do {
+        if (ctxt->opLimit != 0) {
+            if (ctxt->opCount >= ctxt->opLimit) {
+                xmlGenericError(xmlGenericErrorContext,
+                        "XPath operation limit exceeded\n");
+                xmlFreeStreamCtxt(patstream);
+                return(-1);
+            }
+            ctxt->opCount++;
+        }
+
         nb_nodes++;
 
 	switch (cur->type) {
@@ -14312,6 +13868,8 @@ xmlXPathRunEval(xmlXPathParserContextPtr ctxt, int toBool)
     if ((ctxt == NULL) || (ctxt->comp == NULL))
 	return(-1);
 
+    ctxt->context->depth = 0;
+
     if (ctxt->valueTab == NULL) {
 	/* Allocate the value stack */
 	ctxt->valueTab = (xmlXPathObjectPtr *)
@@ -14498,7 +14056,7 @@ xmlXPathTryStreamCompile(xmlXPathContextPtr ctxt, const xmlChar *str) {
 
 	/*
 	 * We don't try to handle expressions using the verbose axis
-	 * specifiers ("::"), just the simplied form at this point.
+	 * specifiers ("::"), just the simplified form at this point.
 	 * Additionally, if there is no list of namespaces available and
 	 *  there's a ":" in the expression, indicating a prefixed QName,
 	 *  then we won't try to compile either. xmlPatterncompile() needs
@@ -14552,8 +14110,12 @@ xmlXPathTryStreamCompile(xmlXPathContextPtr ctxt, const xmlChar *str) {
 #endif /* XPATH_STREAMING */
 
 static void
-xmlXPathOptimizeExpression(xmlXPathCompExprPtr comp, xmlXPathStepOpPtr op)
+xmlXPathOptimizeExpression(xmlXPathParserContextPtr pctxt,
+                           xmlXPathStepOpPtr op)
 {
+    xmlXPathCompExprPtr comp = pctxt->comp;
+    xmlXPathContextPtr ctxt;
+
     /*
     * Try to rewrite "descendant-or-self::node()/foo" to an optimized
     * internal representation.
@@ -14609,10 +14171,18 @@ xmlXPathOptimizeExpression(xmlXPathCompExprPtr comp, xmlXPathStepOpPtr op)
         return;
 
     /* Recurse */
+    ctxt = pctxt->context;
+    if (ctxt != NULL) {
+        if (ctxt->depth >= ctxt->maxDepth)
+            return;
+        ctxt->depth += 1;
+    }
     if (op->ch1 != -1)
-        xmlXPathOptimizeExpression(comp, &comp->steps[op->ch1]);
+        xmlXPathOptimizeExpression(pctxt, &comp->steps[op->ch1]);
     if (op->ch2 != -1)
-	xmlXPathOptimizeExpression(comp, &comp->steps[op->ch2]);
+	xmlXPathOptimizeExpression(pctxt, &comp->steps[op->ch2]);
+    if (ctxt != NULL)
+        ctxt->depth -= 1;
 }
 
 /**
@@ -14641,6 +14211,8 @@ xmlXPathCtxtCompile(xmlXPathContextPtr ctxt, const xmlChar *str) {
     pctxt = xmlXPathNewParserContext(str, ctxt);
     if (pctxt == NULL)
         return NULL;
+    if (ctxt != NULL)
+        ctxt->depth = 0;
     xmlXPathCompileExpr(pctxt, 1);
 
     if( pctxt->error != XPATH_EXPRESSION_OK )
@@ -14660,6 +14232,11 @@ xmlXPathCtxtCompile(xmlXPathContextPtr ctxt, const xmlChar *str) {
 	comp = NULL;
     } else {
 	comp = pctxt->comp;
+	if ((comp->nbStep > 1) && (comp->last >= 0)) {
+            if (ctxt != NULL)
+                ctxt->depth = 0;
+	    xmlXPathOptimizeExpression(pctxt, &comp->steps[comp->last]);
+	}
 	pctxt->comp = NULL;
     }
     xmlXPathFreeParserContext(pctxt);
@@ -14670,9 +14247,6 @@ xmlXPathCtxtCompile(xmlXPathContextPtr ctxt, const xmlChar *str) {
 	comp->string = xmlStrdup(str);
 	comp->nb = 0;
 #endif
-	if ((comp->nbStep > 1) && (comp->last >= 0)) {
-	    xmlXPathOptimizeExpression(comp, &comp->steps[comp->last]);
-	}
     }
     return(comp);
 }
@@ -14829,6 +14403,8 @@ xmlXPathEvalExpr(xmlXPathParserContextPtr ctxt) {
     } else
 #endif
     {
+        if (ctxt->context != NULL)
+            ctxt->context->depth = 0;
 	xmlXPathCompileExpr(ctxt, 1);
         CHECK_ERROR;
 
@@ -14836,9 +14412,12 @@ xmlXPathEvalExpr(xmlXPathParserContextPtr ctxt) {
         if (*ctxt->cur != 0)
             XP_ERROR(XPATH_EXPR_ERROR);
 
-	if ((ctxt->comp->nbStep > 1) && (ctxt->comp->last >= 0))
-	    xmlXPathOptimizeExpression(ctxt->comp,
+	if ((ctxt->comp->nbStep > 1) && (ctxt->comp->last >= 0)) {
+            if (ctxt->context != NULL)
+                ctxt->context->depth = 0;
+	    xmlXPathOptimizeExpression(ctxt,
 		&ctxt->comp->steps[ctxt->comp->last]);
+        }
     }
 
     xmlXPathRunEval(ctxt, 0);
diff --git a/xpointer.c b/xpointer.c
index 6a41f07977c..c1732a584a6 100644
--- a/xpointer.c
+++ b/xpointer.c
@@ -27,7 +27,7 @@
  *       be parsed beforehand instead of a progressive evaluation
  * TODO: Access into entities references are not supported now ...
  *       need a start to be able to pop out of entities refs since
- *       parent is the endity declaration, not the ref.
+ *       parent is the entity declaration, not the ref.
  */
 
 #include <string.h>
@@ -1186,7 +1186,7 @@ xmlXPtrEvalFullXPtr(xmlXPathParserContextPtr ctxt, xmlChar *name) {
 static void
 xmlXPtrEvalChildSeq(xmlXPathParserContextPtr ctxt, xmlChar *name) {
     /*
-     * XPointer don't allow by syntax to address in mutirooted trees
+     * XPointer don't allow by syntax to address in multirooted trees
      * this might prove useful in some cases, warn about it.
      */
     if ((name == NULL) && (CUR == '/') && (NXT(1) != '1')) {
@@ -1202,13 +1202,23 @@ xmlXPtrEvalChildSeq(xmlXPathParserContextPtr ctxt, xmlChar *name) {
     }
 
     while (CUR == '/') {
-	int child = 0;
+	int child = 0, overflow = 0;
 	NEXT;
 
 	while ((CUR >= '0') && (CUR <= '9')) {
-	    child = child * 10 + (CUR - '0');
+            int d = CUR - '0';
+            if (child > INT_MAX / 10)
+                overflow = 1;
+            else
+                child *= 10;
+            if (child > INT_MAX - d)
+                overflow = 1;
+            else
+                child += d;
 	    NEXT;
 	}
+        if (overflow)
+            child = 0;
 	xmlXPtrGetChildNo(ctxt, child);
     }
 }
-- 
GitLab