Simpified attribute wildcard creation and assignment to get rid of memory

* xmlschemas.c include/libxml/schemasInternals.h
  test/schemas/bug152470_1.* result/schemas/bug152470_1_1*:
  Simpified attribute wildcard creation and assignment to get rid
  of memory leaks.
  Restructured the validation process.
  Restructured and expanded parsing of <attributeGroup>.
  Added initial handing of xsi:type.
  Advanced handling of xsi:nil (should work now for simple types).
  Added construction of schemata using xsi:schemaLocation and
  xsi:noNamespaceSchemaLocation; this is not enabled, since
  no corresponding API exists yet.
  Moved the content model to complex type components.
  Resolution of types for attributes will look for simple types
  only (incl. all the built-in simple types).
  Extended parsing of 'anyAttribute'.
  Fixed content-type type for complex types if derived from
  'anyType' using the short-hand form (see bug # 152470,
  submitted by Thilo Jeremias).
* include/libxml/xmlschematypes.h: Cleaned up some comments.
* xstc/xstc.py: Workaround to accomodate case insensitive
  test definitions in ms-test.def.xml.
* result/schemas/deter0_0_0.err result/schemas/ns0_0_2.err
  result/schemas/ns0_1_2.err: Adapted.
diff --git a/xmlschemas.c b/xmlschemas.c
index 12cc8c1..000a0dd 100644
--- a/xmlschemas.c
+++ b/xmlschemas.c
@@ -99,6 +99,67 @@
 
 #define SCHEMAS_PARSE_OPTIONS XML_PARSE_NOENT
 
+/*
+ * xmlSchemaValidOption:
+ *
+ * This is the set of XML Schema validation options.
+ */
+typedef enum {
+    XML_SCHEMA_VAL_XSI_ASSEMBLE			= 1<<0
+	/* assemble schemata using
+	* xsi:schemaLocation and
+	* xsi:noNamespaceSchemaLocation */
+
+} xmlSchemaValidOption;
+
+/*
+* XML_SCHEMA_VAL_XSI_ASSEMBLE_TNS_COMPOSE	 
+* allow to assemble schemata with 
+* the same target namespace from 
+* different sources; otherwise, the first 
+* encountered schema with a specific target 
+* namespace will be used only *
+   
+* 
+* XML_SCHEMA_VAL_LOCATE_BY_NSNAME = 1<<2
+* locate schemata to be imported
+* using the namespace name; otherwise
+* the location URI will be used */
+
+/*
+* xmlSchemaParserOption:
+*
+* This is the set of XML Schema parser options.
+*/
+typedef enum {
+    XML_SCHEMA_PAR_LOCATE_BY_NSNAME	= 1<<0
+	/* locate schemata to be imported
+	* using the namespace name; otherwise
+	* the location URI will be used */
+} xmlSchemaParserOption;
+
+/*
+XMLPUBFUN int XMLCALL
+	    xmlSchemaValidCtxtSetOptions(xmlSchemaValidCtxtPtr ctxt,
+					 int options);
+XMLPUBFUN int XMLCALL
+	    xmlSchemaValidCtxtGetOptions(xmlSchemaValidCtxtPtr ctxt);
+XMLPUBFUN int XMLCALL
+	    xmlSchemaParserCtxtSetOptions(xmlSchemaParserCtxtPtr ctxt,
+					  int options);
+XMLPUBFUN int XMLCALL
+	    xmlSchemaParserCtxtGetOptions(xmlSchemaParserCtxtPtr ctxt);
+
+*/
+
+typedef struct _xmlSchemaAssemble xmlSchemaAssemble;
+typedef xmlSchemaAssemble *xmlSchemaAssemblePtr;
+struct _xmlSchemaAssemble {
+    void *items;  /* used for dynamic addition of schemata */
+    int nbItems; /* used for dynamic addition of schemata */
+    int sizeItems; /* used for dynamic addition of schemata */
+};
+
 struct _xmlSchemaParserCtxt {
     void *userData;             /* user specific data block */
     xmlSchemaValidityErrorFunc error;   /* the callback in case of errors */
@@ -133,6 +194,8 @@
     int        includes;	/* the inclusion level, 0 for root or imports */
     xmlSchemaTypePtr ctxtType; /* The current context simple/complex type */
     xmlSchemaTypePtr parentItem; /* The current parent schema item */
+    xmlSchemaAssemblePtr assemble;
+    int options;
 };
 
 
@@ -183,11 +246,10 @@
     xmlSchemaValPtr value;
 
     xmlSchemaAttrStatePtr attrTop;
-    /* xmlSchemaAttrStatePtr attrBase; */
-    /* int attrMax; */
     xmlSchemaAttrStatePtr attr;
-    xmlNodePtr scope;
+    /* xmlNodePtr scope; not used */
     int valueWS;
+    int options;
 };
 
 /*
@@ -197,8 +259,9 @@
 typedef xmlSchemaImport *xmlSchemaImportPtr;
 struct _xmlSchemaImport {
     const xmlChar *schemaLocation;
-    xmlSchemaPtr schema;
+    xmlSchemaPtr schema; /* not used any more */
     xmlDocPtr doc;
+    int isMain;
 };
 
 /*
@@ -229,10 +292,20 @@
 xmlSchemaFacetTypeToString(xmlSchemaTypeType type);
 static int
 xmlSchemaValidateSimpleTypeValue(xmlSchemaValidCtxtPtr ctxt, 
+				 xmlSchemaTypePtr type,
 				 const xmlChar *value,
 				 int fireErrors,				 
 				 int applyFacets,
-				 int normalize);
+				 int normalize,
+				 int checkNodes);
+static int
+xmlSchemaValidateElementByDeclaration(xmlSchemaValidCtxtPtr ctxt,
+				      xmlSchemaElementPtr elemDecl); 
+static int
+xmlSchemaValidateElementByWildcard(xmlSchemaValidCtxtPtr ctxt,
+				   xmlSchemaTypePtr type);
+static int
+xmlSchemaHasElemOrCharContent(xmlNodePtr node);
 static int
 xmlSchemaParseImport(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema,
                      xmlNodePtr node);
@@ -1697,6 +1770,29 @@
 }
 
 /**
+ * xmlSchemaNewSchema:
+ * @ctxt:  a schema validation context
+ *
+ * Allocate a new Schema structure.
+ *
+ * Returns the newly allocated structure or NULL in case or error
+ */
+static xmlSchemaAssemblePtr
+xmlSchemaNewAssemble(void)
+{
+    xmlSchemaAssemblePtr ret;
+
+    ret = (xmlSchemaAssemblePtr) xmlMalloc(sizeof(xmlSchemaAssemble));
+    if (ret == NULL) {
+        /* xmlSchemaPErrMemory(ctxt, "allocating assemble info", NULL); */
+        return (NULL);
+    }
+    memset(ret, 0, sizeof(xmlSchemaAssemble));
+    ret->items = NULL;
+    return (ret);
+}
+
+/**
  * xmlSchemaNewFacet:
  *
  * Allocate a new Facet structure.
@@ -1994,11 +2090,14 @@
     if (type->type != XML_SCHEMA_TYPE_BASIC) {
 	if (type->attributeUses != NULL)
 	    xmlSchemaFreeAttributeUseList(type->attributeUses);
-	/* TODO: There must be a way more simple than this. */
-	if ((type->attributeWildcard != NULL) && 
+	if ((type->attributeWildcard != NULL) &&
 	    ((type->type != XML_SCHEMA_TYPE_COMPLEX) ||
-	    ((type->type == XML_SCHEMA_TYPE_COMPLEX) && 
-	    (type->flags & XML_SCHEMAS_TYPE_OWNED_ATTR_WILDCARD)))) { 
+	    (type->flags & XML_SCHEMAS_TYPE_OWNED_ATTR_WILDCARD))) {
+	    /*
+	    * NOTE: The only case where an attribute wildcard
+	    * is not owned, is if a complex type inherits it
+	    * from a base type.
+	    */
 	    xmlSchemaFreeWildcard(type->attributeWildcard);
 	}
     }
@@ -2013,7 +2112,9 @@
 	    xmlFree(link);
 	    link = next;
 	} while (link != NULL);
-    }      
+    }  
+    if (type->contModel != NULL)
+        xmlRegFreeRegexp(type->contModel);
     xmlFree(type);
 }
 
@@ -2075,8 +2176,7 @@
         xmlSchemaFreeAnnot(schema->annot);
     if (schema->doc != NULL && !schema->preserve)
         xmlFreeDoc(schema->doc);
-    xmlDictFree(schema->dict);
-
+    xmlDictFree(schema->dict);    
     xmlFree(schema);
 }
 
@@ -2811,8 +2911,56 @@
 }
 
 /**
+ * xmlSchemaAddAssembledItem:
+ * @ctxt:  a schema parser context
+ * @schema:  the schema being built
+ * @item:  the item
+ *
+ * Add a item to the schema's list of current items.
+ * This is used if the schema was already constructed and
+ * new schemata need to be added to it.
+ * *WARNING* this interface is highly subject to change.
+ *
+ * Returns 0 if suceeds and -1 if an internal error occurs.
+ */
+static int
+xmlSchemaAddAssembledItem(xmlSchemaParserCtxtPtr ctxt,
+			   xmlSchemaTypePtr item)
+{
+    static int growSize = 100;
+    xmlSchemaAssemblePtr ass;
+
+    ass = ctxt->assemble;
+    if (ass->sizeItems < 0) {
+	/* If disabled. */
+	return (0);
+    }
+    if (ass->sizeItems <= 0) {
+	ass->items = xmlMalloc(growSize * sizeof(xmlSchemaTypePtr));
+	if (ass->items == NULL) {
+	    xmlSchemaPErrMemory(ctxt,
+		"allocating new item buffer", NULL);
+	    return (-1);
+	}	
+	ass->sizeItems = growSize;
+    } else if (ass->sizeItems <= ass->nbItems) {
+	ass->sizeItems *= 2;
+	ass->items = (xmlNsPtr *) xmlRealloc(ass->items, 
+	    ass->sizeItems * sizeof(xmlSchemaTypePtr));
+	if (ass->items == NULL) {
+	    xmlSchemaPErrMemory(ctxt,
+		"growing item buffer", NULL);
+	    ass->sizeItems = 0;
+	    return (-1);
+	}	
+    }
+    ((xmlSchemaTypePtr *) ass->items)[ass->nbItems++] = (void *) item;
+    return (0);
+}
+
+/**
  * xmlSchemaAddNotation:
- * @ctxt:  a schema validation context
+ * @ctxt:  a schema parser context
  * @schema:  the schema being built
  * @name:  the item name
  *
@@ -2863,7 +3011,7 @@
 
 /**
  * xmlSchemaAddAttribute:
- * @ctxt:  a schema validation context
+ * @ctxt:  a schema parser context
  * @schema:  the schema being built
  * @name:  the item name
  * @namespace:  the namespace
@@ -2913,12 +3061,14 @@
         xmlFree(ret);
         return (NULL);
     }
+    if (ctxt->assemble != NULL)
+	xmlSchemaAddAssembledItem(ctxt, (xmlSchemaTypePtr) ret); 
     return (ret);
 }
 
 /**
  * xmlSchemaAddAttributeGroup:
- * @ctxt:  a schema validation context
+ * @ctxt:  a schema parser context
  * @schema:  the schema being built
  * @name:  the item name
  *
@@ -2961,12 +3111,14 @@
         xmlFree(ret);
         return (NULL);
     }
+    if (ctxt->assemble != NULL)	
+	xmlSchemaAddAssembledItem(ctxt, (xmlSchemaTypePtr) ret);
     return (ret);
 }
 
 /**
  * xmlSchemaAddElement:
- * @ctxt:  a schema validation context
+ * @ctxt:  a schema parser context
  * @schema:  the schema being built
  * @name:  the type name
  * @namespace:  the type namespace
@@ -3036,6 +3188,8 @@
 	}
         
     }
+    if (ctxt->assemble != NULL)	
+	xmlSchemaAddAssembledItem(ctxt, (xmlSchemaTypePtr) ret);
     return (ret);
 }
 
@@ -3111,7 +3265,8 @@
     ret->maxOccurs = 1;
     ret->attributeUses = NULL;
     ret->attributeWildcard = NULL;
-
+    if (ctxt->assemble != NULL)	
+	xmlSchemaAddAssembledItem(ctxt,ret);
     return (ret);
 }
 
@@ -3160,7 +3315,8 @@
     }
     ret->minOccurs = 1;
     ret->maxOccurs = 1;
-
+    if (ctxt->assemble != NULL)	
+	xmlSchemaAddAssembledItem(ctxt, (xmlSchemaTypePtr) ret);
     return (ret);
 }
 
@@ -3275,9 +3431,8 @@
         xmlSchemaPSimpleTypeErr(ctxt, XML_SCHEMAP_PREFIX_UNDEFINED, 
 	    NULL, NULL, (xmlNodePtr) attr, 
 	    xmlSchemaGetBuiltInType(XML_SCHEMAS_QNAME), NULL, val,
-	    "The prefix '%s' of the QName value "
-	    "'%s' has no corresponding namespace declaration in scope",
-	    prefix, val);
+	    "The QName value '%s' has no corresponding namespace "
+	    "declaration in scope", val, NULL);
     } else {
         *namespace = xmlDictLookup(ctxt->dict, ns->href, -1);
     }
@@ -3360,9 +3515,9 @@
 	xmlSchemaPSimpleTypeErr(ctxt, 
 	    XML_SCHEMAP_S4S_ATTR_INVALID_VALUE,
 	    ownerDes, ownerItem, (xmlNodePtr) attr, 
-	    xmlSchemaGetBuiltInType(XML_SCHEMAS_QNAME), "QName", value, 
-	    "The prefix '%s' of the value '%s' is not declared.\n",
-	    pref, value);
+	    xmlSchemaGetBuiltInType(XML_SCHEMAS_QNAME), "QName", value,
+	    "The QName value '%s' has no corresponding namespace "
+	    "declaration in scope", value, NULL);
 	return (ctxt->err);
     } else {
         *uri = xmlDictLookup(ctxt->dict, ns->href, -1);
@@ -3651,7 +3806,7 @@
                            xmlSchemaPtr schema, xmlNodePtr node);
 
 /**
- * xmlSchemaPValAttrNode:
+ * xmlSchemaPValAttrNodeValue:
  * 
  * @ctxt:  a schema parser context
  * @ownerDes: the designation of the parent element
@@ -3903,19 +4058,7 @@
             }
         }
         child = child->next;
-    }
-    if (IS_SCHEMA(child, "anyAttribute")) {
-	xmlSchemaWildcardPtr wildcard;
-
-        wildcard = xmlSchemaParseAnyAttribute(ctxt, schema, child);
-        if (wildcard != NULL) {
-	    if (type->type == XML_SCHEMA_TYPE_ATTRIBUTEGROUP)
-		((xmlSchemaAttributeGroupPtr) type)->attributeWildcard = wildcard;
-	    else
-		type->attributeWildcard = wildcard;
-        }
-        child = child->next;
-    }
+    }    
     return (child);
 }
 
@@ -4118,8 +4261,7 @@
 	    if (xmlStrEqual(fixed, BAD_CAST "true"))
 		facet->fixed = 1;
 	}
-    }
-    
+    }    
     child = node->children;
 
     if (IS_SCHEMA(child, "annotation")) {
@@ -4416,7 +4558,7 @@
  * parse a XML schema AnyAttrribute declaration
  * *WARNING* this interface is highly subject to change
  *
- * Returns an attribute def structure or NULL
+ * Returns a wildcard or NULL.
  */
 static xmlSchemaWildcardPtr
 xmlSchemaParseAnyAttribute(xmlSchemaParserCtxtPtr ctxt,
@@ -4424,6 +4566,7 @@
 {
     xmlSchemaWildcardPtr ret;
     xmlNodePtr child = NULL;
+    xmlAttrPtr attr;
 
     if ((ctxt == NULL) || (schema == NULL) || (node == NULL))
         return (NULL);
@@ -4433,22 +4576,47 @@
         return (NULL);
     }
     ret->type = XML_SCHEMA_TYPE_ANY_ATTRIBUTE;
-    ret->id = xmlSchemaGetProp(ctxt, node, "id");
+    /*
+    * Check for illegal attributes.
+    */
+    attr = node->properties;
+    while (attr != NULL) {
+	if (attr->ns == NULL) {
+	    if ((!xmlStrEqual(attr->name, BAD_CAST "id")) &&
+	        (!xmlStrEqual(attr->name, BAD_CAST "namespace")) &&
+		(!xmlStrEqual(attr->name, BAD_CAST "processContents"))) {
+		xmlSchemaPIllegalAttrErr(ctxt, 
+		    XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, 
+		    NULL, NULL, attr);		    
+	    }
+	} else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) {
+	    xmlSchemaPIllegalAttrErr(ctxt, 
+		XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, 
+		NULL, NULL, attr);	
+	}
+	attr = attr->next;
+    }
+    /* ret->id = xmlSchemaGetProp(ctxt, node, "id"); */
+    /*
+    * Parse the namespace list.
+    */
     if (xmlSchemaParseWildcardNs(ctxt, schema, ret, node) != 0) {
 	xmlSchemaFreeWildcard(ret);
 	return (NULL);
-    }    
+    }  
+    /*
+    * And now for the children...
+    */
     child = node->children;
     if (IS_SCHEMA(child, "annotation")) {
         ret->annot = xmlSchemaParseAnnotation(ctxt, schema, child);
         child = child->next;
     }
     if (child != NULL) {
-	/* TODO: Change the error code. */
 	xmlSchemaPContentErr(ctxt,
-		XML_SCHEMAP_UNKNOWN_ANYATTRIBUTE_CHILD,
-		NULL, NULL, node, child, 
-		NULL, "(annotation?)");
+	    XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED,
+	    NULL, NULL, node, child, 
+	    NULL, "(annotation?)");
     }
 
     return (ret);
@@ -4799,55 +4967,119 @@
                              xmlSchemaPtr schema, xmlNodePtr node,
 			     int topLevel)
 {
-    const xmlChar *name, *refNs = NULL, *ref = NULL;
+    const xmlChar *name;
     xmlSchemaAttributeGroupPtr ret;
     xmlNodePtr child = NULL;
-    const xmlChar *oldcontainer;
-    char buf[100];
+    const xmlChar *oldcontainer;    
+    xmlAttrPtr attr, nameAttr;
 
     if ((ctxt == NULL) || (schema == NULL) || (node == NULL))
         return (NULL);
+
+    nameAttr = xmlSchemaGetPropNode(node, "name");
+    attr = xmlSchemaGetPropNode(node, "ref");   
+    if ((topLevel) || (attr == NULL)) {
+	/*
+	* Parse as an attribute group definition.
+	* Note that those are allowed at top level only.
+	*/
+	if (nameAttr == NULL) {
+	    xmlSchemaPMissingAttrErr(ctxt,
+		XML_SCHEMAP_S4S_ATTR_MISSING,
+		NULL, NULL, node, "name", NULL);	    
+	    return (NULL);
+	}
+	name = xmlSchemaGetNodeContent(ctxt, (xmlNodePtr) nameAttr);
+	/*
+	* The name is crucial, exit if invalid. 
+	*/
+	if (xmlSchemaPValAttrNode(ctxt,
+	    NULL, NULL, nameAttr, 
+	    xmlSchemaGetBuiltInType(XML_SCHEMAS_NCNAME), &name) != 0) {
+	    return (NULL);
+	}
+	ret = xmlSchemaAddAttributeGroup(ctxt, schema, name, node);
+	if (ret == NULL)
+	    return (NULL);
+	ret->type = XML_SCHEMA_TYPE_ATTRIBUTEGROUP;
+	ret->flags |= XML_SCHEMAS_ATTRGROUP_GLOBAL;
+	ret->node = node;
+    } else {    
+	char buf[50];
+	const xmlChar *refNs = NULL, *ref = NULL, *refPrefix;
+
+	/*
+	* Parse as an attribute group definition reference.
+	*/
+	if (attr == NULL) {
+	    xmlSchemaPMissingAttrErr(ctxt, 
+		XML_SCHEMAP_S4S_ATTR_MISSING, 
+		NULL, NULL, node, "ref", NULL);
+	}	
+	xmlSchemaPValAttrNodeQName(ctxt, schema,
+	    NULL, NULL, attr, &refNs, &refPrefix, &ref);
+	 
+        snprintf(buf, 49, "#aGrRef %d", ctxt->counter++ + 1);
+	name = (const xmlChar *) buf;
+	if (name == NULL) {
+	    xmlSchemaPErrMemory(ctxt, "creating internal name for an "
+		"attribute group definition reference", node);
+            return (NULL);
+        }
+	ret = xmlSchemaAddAttributeGroup(ctxt, schema, name, node);
+	if (ret == NULL)
+	    return (NULL);
+	ret->type = XML_SCHEMA_TYPE_ATTRIBUTEGROUP;
+	ret->ref = ref;
+	ret->refNs = refNs;
+	/* TODO: Is @refPrefix currently used? */
+	ret->refPrefix = refPrefix;
+	ret->node = node;
+    }
+    /*
+    * Check for illegal attributes.
+    */
+    attr = node->properties;
+    while (attr != NULL) {
+	if (attr->ns == NULL) {
+	    if ((((topLevel == 0) && (!xmlStrEqual(attr->name, BAD_CAST "ref"))) ||
+		 (topLevel && (!xmlStrEqual(attr->name, BAD_CAST "name")))) &&
+		(!xmlStrEqual(attr->name, BAD_CAST "id"))) 
+	    {
+		xmlSchemaPIllegalAttrErr(ctxt,
+		    XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED,
+		    NULL, NULL, attr);
+	    }
+	} else if (xmlStrEqual(attr->ns->href, xmlSchemaNs)) {
+	    xmlSchemaPIllegalAttrErr(ctxt,
+		XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED,
+		NULL, NULL, attr);
+	}
+	attr = attr->next;
+    }	
+    /* TODO: Validate "id" ? */  
+    /*
+    * And now for the children...
+    */
     oldcontainer = ctxt->container;
-    name = xmlSchemaGetProp(ctxt, node, "name");
-    if (name == NULL) {
-        ref = xmlGetQNameProp(ctxt, node, "ref", &refNs);
-        if (ref == NULL) {
-            xmlSchemaPErr2(ctxt, node, child,
-		XML_SCHEMAP_ATTRGRP_NONAME_NOREF,
-		"Attribute group or particle: One of the attributes 'name' "
-		"or 'ref' must be present.\n", NULL,
-		NULL);
-            return (NULL);
-        }
-        snprintf(buf, 99, "anonattrgroup %d", ctxt->counter++ + 1);
-        name = (const xmlChar *) buf;
-        if (name == NULL) {
-	    xmlSchemaPErrMemory(ctxt, "creating attribute group", node);
-            return (NULL);
-        }
-    }
-    ret = xmlSchemaAddAttributeGroup(ctxt, schema, name, node);
-    if (ret == NULL) {
-        return (NULL);
-    }
-    ret->ref = ref;
-    ret->refNs = refNs;
-    ret->type = XML_SCHEMA_TYPE_ATTRIBUTEGROUP;
-    if (topLevel) 
-        ret->flags |= XML_SCHEMAS_ATTRGROUP_GLOBAL;
-    ret->node = node;
-    child = node->children;
     ctxt->container = name;
+    child = node->children;    
     if (IS_SCHEMA(child, "annotation")) {
         ret->annot = xmlSchemaParseAnnotation(ctxt, schema, child);
         child = child->next;
     }
-    child = xmlSchemaParseAttrDecls(ctxt, schema, child, (xmlSchemaTypePtr) ret);     
+    if (topLevel) {
+	child = xmlSchemaParseAttrDecls(ctxt, schema, child, (xmlSchemaTypePtr) ret); 
+	if (IS_SCHEMA(child, "anyAttribute")) {
+	    ret->attributeWildcard = xmlSchemaParseAnyAttribute(ctxt, schema, child);
+	    child = child->next;
+	}
+    }
     if (child != NULL) {
-        xmlSchemaPErr2(ctxt, node, child,
-                       XML_SCHEMAP_UNKNOWN_ATTRGRP_CHILD,
-                       "Attribute group '%s' has unexpected content.\n", name,
-                       NULL);
+	xmlSchemaPContentErr(ctxt,
+	    XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, 
+	    NULL, NULL, node, child, NULL, 
+	    "(annotation?)");
     }
     ctxt->container = oldcontainer;
     return (ret);
@@ -5042,7 +5274,7 @@
     * robust.
     */
     if (isRef) {
-	char buf[100];
+	char buf[50];
 	const xmlChar *refNs = NULL, *ref = NULL, *refPrefix;
 
 	/*
@@ -5052,7 +5284,7 @@
 	    (xmlChar **) &xmlSchemaElemDesAttrRef, 
 	    NULL, attr, &refNs, &refPrefix, &ref);			
 	 
-        snprintf(buf, 99, "#eRef %d", ctxt->counter++ + 1);
+        snprintf(buf, 49, "#eRef %d", ctxt->counter++ + 1);
 	name = (const xmlChar *) buf;
 	ret = xmlSchemaAddElement(ctxt, schema, name, NULL, node, 0);
 	if (ret == NULL) {
@@ -6178,6 +6410,259 @@
     ctxt->ctxtType = NULL;
 }
 
+static xmlSchemaImportPtr
+xmlSchemaAddImport(xmlSchemaParserCtxtPtr ctxt, 
+		   xmlHashTablePtr *imports,
+		   const xmlChar *nsName)
+{
+    xmlSchemaImportPtr ret;
+
+    if (*imports == NULL) {
+	*imports = xmlHashCreate(10);
+	if (*imports == NULL) {
+	    xmlSchemaPCustomErr(ctxt, 
+		XML_SCHEMAP_FAILED_BUILD_IMPORT,
+		NULL, NULL, (xmlNodePtr) ctxt->doc,
+		"Internal error: failed to build the import table",
+		NULL);
+	    return (NULL);
+	}
+    }
+    ret = (xmlSchemaImport*) xmlMalloc(sizeof(xmlSchemaImport));
+    if (ret == NULL) {
+	xmlSchemaPErrMemory(NULL, "allocating import struct", NULL);
+	return (NULL);
+    }   
+    memset(ret, 0, sizeof(xmlSchemaImport));
+    if (nsName == NULL)
+	nsName = XML_SCHEMAS_NO_NAMESPACE;
+    xmlHashAddEntry(*imports, nsName, ret);  
+
+    return (ret);
+}
+
+static int
+xmlSchemaAcquireSchemaDoc(xmlSchemaParserCtxtPtr ctxt,
+			       xmlSchemaPtr schema,
+			       xmlNodePtr node,
+			       const xmlChar *nsName,
+			       const xmlChar *location,
+			       xmlDocPtr *doc,
+			       const xmlChar **targetNamespace,
+			       int absolute)
+{
+    xmlParserCtxtPtr parserCtxt;
+    xmlSchemaImportPtr import;
+    const xmlChar *ns;
+    xmlNodePtr root;
+
+    /*
+    * NOTE: This will be used for <import>, <xsi:schemaLocation> and
+    * <xsi:noNamespaceSchemaLocation>.
+    */
+    *doc = NULL;
+    /*
+    * Given that the schemaLocation [attribute] is only a hint, it is open 
+    * to applications to ignore all but the first <import> for a given 
+    * namespace, regardless of the ·actual value· of schemaLocation, but
+    * such a strategy risks missing useful information when new
+    * schemaLocations are offered.
+    *
+    * XSV (ver 2.5-2) does use the first <import> which resolves to a valid schema.
+    * Xerces-J (ver 2.5.1) ignores all but the first given <import> - regardless if
+    * valid or not.
+    * We will follow XSV here. 
+    */
+    if (location == NULL) {
+	/*
+	* Schema Document Location Strategy:
+	*
+	* 3 Based on the namespace name, identify an existing schema document,
+	* either as a resource which is an XML document or a <schema> element 
+	* information item, in some local schema repository; 
+	*
+	* 5 Attempt to resolve the namespace name to locate such a resource. 
+	*
+	* NOTE: Those stategies are not supported, so we will skip.
+	*/
+	return (0);
+    }
+    if (nsName == NULL) 
+	ns = XML_SCHEMAS_NO_NAMESPACE;
+    else
+	ns = nsName;
+    
+    import = xmlHashLookup(schema->schemasImports, ns);
+    if (import != NULL) {	
+	/*
+	* There was a valid resource for the specified namespace already
+	* defined, so skip.
+	* TODO: This might be changed someday to allow import of
+	* components from multiple documents for a single target namespace.
+	*/
+	return (0);
+    } 
+    /*
+    * Schema Document Location Strategy: 
+    *
+    * 2 Based on the location URI, identify an existing schema document, 
+    * either as a resource which is an XML document or a <schema> element 
+    * information item, in some local schema repository;   
+    *
+    * 4 Attempt to resolve the location URI, to locate a resource on the 
+    * web which is or contains or references a <schema> element;
+    * TODO: Hmm, I don't know if the reference stuff in 4. will work.
+    *
+    */
+    if ((absolute == 0) && (node != NULL)) {
+	xmlChar *base, *URI;
+
+	base = xmlNodeGetBase(node->doc, node);
+	if (base == NULL) {
+	    URI = xmlBuildURI(location, node->doc->URL);
+	} else {
+	    URI = xmlBuildURI(location, base);
+	    xmlFree(base);
+	}
+	if (URI != NULL) {
+	    location = xmlDictLookup(ctxt->dict, URI, -1);
+	    xmlFree(URI);
+	}
+    }
+    parserCtxt = xmlNewParserCtxt();
+    if (parserCtxt == NULL) {
+	xmlSchemaPErrMemory(NULL, "xmlSchemaParseImport: "
+	    "allocating a parser context", NULL);
+	return(-1);
+    }		
+    
+    *doc = xmlCtxtReadFile(parserCtxt, (const char *) location, 
+	    NULL, SCHEMAS_PARSE_OPTIONS);
+
+    /*
+    * 2.1 The referent is (a fragment of) a resource which is an 
+    * XML document (see clause 1.1), which in turn corresponds to 
+    * a <schema> element information item in a well-formed information 
+    * set, which in turn corresponds to a valid schema.
+    * TODO: What to do with the "fragment" stuff?
+    *
+    * 2.2 The referent is a <schema> element information item in 
+    * a well-formed information set, which in turn corresponds 
+    * to a valid schema.
+    * NOTE: 2.2 won't apply, since only XML documents will be processed 
+    * here.
+    */       
+    if (*doc == NULL) {	
+	xmlErrorPtr lerr;
+	/*
+	* It is *not* an error for the application schema reference 
+	* strategy to fail.
+	* 
+	* If the doc is NULL and the parser error is an IO error we
+	* will assume that the resource could not be located or accessed.
+	*
+	* TODO: Try to find specific error codes to react only on
+	* localisation failures.
+	*
+	* TODO, FIXME: Check the spec: is a namespace added to the imported
+	* namespaces, even if the schemaLocation did not provide
+	* a resource? I guess so, since omitting the "schemaLocation"
+	* attribute, imports a namespace as well.
+	*/
+	lerr = xmlGetLastError();
+	if ((lerr != NULL) && (lerr->domain == XML_FROM_IO)) {	
+	    xmlFreeParserCtxt(parserCtxt);
+	    return(0);
+	}
+
+	xmlSchemaPCustomErr(ctxt,
+	    XML_SCHEMAP_SRC_IMPORT_2_1,
+	    NULL, NULL, node,
+	    "Failed to parse the resource '%s' for import",
+	    location);
+	xmlFreeParserCtxt(parserCtxt);
+	return(XML_SCHEMAP_SRC_IMPORT_2_1);
+    }
+    xmlFreeParserCtxt(parserCtxt);
+    
+    root = xmlDocGetRootElement(*doc);
+    if (root == NULL) {
+	xmlSchemaPCustomErr(ctxt,
+	    XML_SCHEMAP_SRC_IMPORT_2_1,
+	    NULL, NULL, node,
+	    "The XML document '%s' to be imported has no document "
+	    "element", location);	
+	xmlFreeDoc(*doc);
+	*doc = NULL;
+	return (XML_SCHEMAP_SRC_IMPORT_2_1);
+    }	
+    
+    xmlSchemaCleanupDoc(ctxt, root);	
+    
+    if (!IS_SCHEMA(root, "schema")) {
+	xmlSchemaPCustomErr(ctxt,
+	    XML_SCHEMAP_SRC_IMPORT_2_1,
+	    NULL, NULL, node,
+	    "The XML document '%s' to be imported is not a XML schema document",
+	    location);	
+	xmlFreeDoc(*doc);
+	*doc = NULL;
+	return (XML_SCHEMAP_SRC_IMPORT_2_1);
+    }	
+    *targetNamespace = xmlSchemaGetProp(ctxt, root, "targetNamespace");
+    /*
+    * Schema Representation Constraint: Import Constraints and Semantics
+    */    
+    if (nsName == NULL) {
+	if (*targetNamespace != NULL) {
+	    xmlSchemaPCustomErr(ctxt,
+		XML_SCHEMAP_SRC_IMPORT_3_2,
+		NULL, NULL, node,
+		"The XML schema to be imported is not expected "
+		"to have a target namespace; this differs from "
+		"its target namespace of '%s'", *targetNamespace);
+	    xmlFreeDoc(*doc);
+	    *doc = NULL;
+	    return (XML_SCHEMAP_SRC_IMPORT_3_2);
+	}
+    } else {
+	if (*targetNamespace == NULL) {
+	    xmlSchemaPCustomErr(ctxt,
+		XML_SCHEMAP_SRC_IMPORT_3_1,
+		NULL, NULL, node,
+		"The XML schema to be imported is expected to have a target "
+		"namespace of '%s'", nsName);
+	    xmlFreeDoc(*doc);
+	    *doc = NULL;
+	    return (XML_SCHEMAP_SRC_IMPORT_3_1);
+	} else if (!xmlStrEqual(*targetNamespace, nsName)) {
+	    xmlSchemaPCustomErrExt(ctxt,
+		XML_SCHEMAP_SRC_IMPORT_3_1,
+		NULL, NULL, node,
+		"The XML schema to be imported is expected to have a "
+		"target namespace of '%s'; this differs from "
+		"its target namespace of '%s'", 
+		nsName, *targetNamespace, NULL);
+	    xmlFreeDoc(*doc);
+	    *doc = NULL;
+	    return (XML_SCHEMAP_SRC_IMPORT_3_1);
+	}
+    }
+
+    import = xmlSchemaAddImport(ctxt, &(schema->schemasImports), nsName);
+    if (import == NULL) {
+	xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_FAILED_BUILD_IMPORT,
+	    NULL, NULL, NULL,	    
+	    "Internal error: xmlSchemaAcquireSchemaDoc, "
+	    "failed to build import table", NULL);
+	xmlFreeDoc(*doc);
+	*doc = NULL;
+	return (-1);
+    }
+    import->schemaLocation = location;
+    import->doc = *doc;
+    return (0);
+}
 
 /**
  * xmlSchemaParseImport:
@@ -6194,19 +6679,15 @@
 static int
 xmlSchemaParseImport(xmlSchemaParserCtxtPtr ctxt, xmlSchemaPtr schema,
                      xmlNodePtr node)
-{
-    xmlNodePtr child = NULL;
-    xmlSchemaImportPtr import = NULL;
-    const xmlChar *namespace = NULL, *ns;
+{    
+    xmlNodePtr child;
+    const xmlChar *namespace = NULL;
     const xmlChar *schemaLocation = NULL;
     const xmlChar *targetNamespace, *oldTNS, *url;
     xmlAttrPtr attr;
     xmlDocPtr doc;
     xmlNodePtr root;
-    xmlChar *base = NULL;
-    xmlChar *URI = NULL;
-    int flags;
-    xmlParserCtxtPtr parserCtxt;
+    int flags, ret = 0;
 
 
     if ((ctxt == NULL) || (schema == NULL) || (node == NULL))
@@ -6305,232 +6786,41 @@
 	    return (XML_SCHEMAP_SRC_IMPORT_1_2);
 	}
     }
-
     /*
-    * Given that the schemaLocation [attribute] is only a hint, it is open 
-    * to applications to ignore all but the first <import> for a given 
-    * namespace, regardless of the ·actual value· of schemaLocation, but
-    * such a strategy risks missing useful information when new
-    * schemaLocations are offered.
-    *
-    * XSV (ver 2.5-2) does use the first <import> which resolves to a valid schema.
-    * Xerces-J (ver 2.5.1) ignores all but the first given <import> - regardless if
-    * valid or not.
-    * We will follow XSV here. 
+    * Locate and aquire the schema document.
     */
-    if (schemaLocation == NULL) {
-	/*
-	* Schema Document Location Strategy:
-	*
-	* 3 Based on the namespace name, identify an existing schema document,
-	* either as a resource which is an XML document or a <schema> element 
-	* information item, in some local schema repository; 
-	*
-	* 5 Attempt to resolve the namespace name to locate such a resource. 
-	*
-	* NOTE: Those stategies are not supported, so we will skip.
-	*/
-	return (0);
-    }
-    if (namespace == NULL) 
-	ns = XML_SCHEMAS_NO_NAMESPACE;
-    else
-	ns = namespace;
-    
-    import = xmlHashLookup(schema->schemasImports, ns);
-    if (import != NULL) {	
-	/*
-	* There was a valid resource for the specified namespace already
-	* defined, so skip.
-	* TODO: This might be changed someday to allow import of
-	* components from multiple documents for a single target namespace.
-	*/
-	return (0);
-    } 
-    /*
-    * Schema Document Location Strategy: 
-    *
-    * 2 Based on the location URI, identify an existing schema document, 
-    * either as a resource which is an XML document or a <schema> element 
-    * information item, in some local schema repository;   
-    *
-    * 4 Attempt to resolve the location URI, to locate a resource on the 
-    * web which is or contains or references a <schema> element;
-    * TODO: Hmm, I don't know if the reference stuff in 4. will work.
-    *
-    */
-    	
-    base = xmlNodeGetBase(node->doc, node);
-    if (base == NULL) {
-	URI = xmlBuildURI(schemaLocation, node->doc->URL);
-    } else {
-	URI = xmlBuildURI(schemaLocation, base);
-	xmlFree(base);
-    }
-    if (URI != NULL) {
-	schemaLocation = xmlDictLookup(ctxt->dict, URI, -1);
-	xmlFree(URI);
-    }
-                 	
-    parserCtxt = xmlNewParserCtxt();
-    if (parserCtxt == NULL) {
-	xmlSchemaPErrMemory(NULL, "xmlSchemaParseImport: "
-	    "allocating a parser context", NULL);
-	return(-1);
-    }		
-    
-    doc = xmlCtxtReadFile(parserCtxt, (const char *) schemaLocation, 
-	    NULL, SCHEMAS_PARSE_OPTIONS);
-
-    /*
-    * 2.1 The referent is (a fragment of) a resource which is an 
-    * XML document (see clause 1.1), which in turn corresponds to 
-    * a <schema> element information item in a well-formed information 
-    * set, which in turn corresponds to a valid schema.
-    * TODO: What to do with the "fragment" stuff?
-    *
-    * 2.2 The referent is a <schema> element information item in 
-    * a well-formed information set, which in turn corresponds 
-    * to a valid schema.
-    * NOTE: 2.2 won't apply, since only XML documents will be processed 
-    * here.
-    */       
-    if (doc == NULL) {	
-	xmlErrorPtr lerr;
-	/*
-	* It is *not* an error for the application schema reference 
-	* strategy to fail.
-	* 
-	* If the doc is NULL and the parser error is an IO error we
-	* will assume that the resource could not be located or accessed.
-	*
-	* TODO: Try to find specific error codes to react only on
-	* localisation failures.
-	*
-	* TODO, FIXME: Check the spec: is a namespace added to the imported
-	* namespaces, even if the schemaLocation did not provide
-	* a resource? I guess so, since omitting the "schemaLocation"
-	* attribute, imports a namespace as well.
-	*/
-	lerr = xmlGetLastError();
-	if ((lerr != NULL) && (lerr->domain == XML_FROM_IO)) {	
-	    xmlFreeParserCtxt(parserCtxt);
-	    return(0);
-	}
-
-	xmlSchemaPCustomErr(ctxt,
-	    XML_SCHEMAP_SRC_IMPORT_2_1,
-	    NULL, NULL, node,
-	    "Failed to parse the resource '%s' for import",
-	    schemaLocation);
-	xmlFreeParserCtxt(parserCtxt);
-	return(XML_SCHEMAP_SRC_IMPORT_2_1);
-    }
-    xmlFreeParserCtxt(parserCtxt);
-    
-    root = xmlDocGetRootElement(doc);
-    if (root == NULL) {
-	xmlSchemaPCustomErr(ctxt,
-	    XML_SCHEMAP_SRC_IMPORT_2_1,
-	    NULL, NULL, node,
-	    "The XML document '%s' to be imported has no document "
-	    "element", schemaLocation);	
-	xmlFreeDoc(doc);	
-	return (XML_SCHEMAP_SRC_IMPORT_2_1);
-    }	
-    
-    xmlSchemaCleanupDoc(ctxt, root);	
-    
-    if (!IS_SCHEMA(root, "schema")) {
-	xmlSchemaPCustomErr(ctxt,
-	    XML_SCHEMAP_SRC_IMPORT_2_1,
-	    NULL, NULL, node,
-	    "The XML document '%s' to be imported is not a XML schema document",
-	    schemaLocation);	
-	xmlFreeDoc(doc);
-	return (XML_SCHEMAP_SRC_IMPORT_2_1);
-    }	
-    targetNamespace = xmlSchemaGetProp(ctxt, root, "targetNamespace");
-    /*
-    * Schema Representation Constraint: Import Constraints and Semantics
-    */    
-    if (namespace == NULL) {
-	if (targetNamespace != NULL) {
-	    xmlSchemaPCustomErr(ctxt,
-		XML_SCHEMAP_SRC_IMPORT_3_2,
-		NULL, NULL, node,
-		"No 'namespace' attribute was " 
-		"specified, thus the XML schema to be imported "
-		"must have no target namespace", NULL);
+    ret = xmlSchemaAcquireSchemaDoc(ctxt, schema, node, namespace, 
+	schemaLocation, &doc, &targetNamespace, 0);
+    if (ret != 0) {
+	if (doc != NULL)
 	    xmlFreeDoc(doc);
-	    return (XML_SCHEMAP_SRC_IMPORT_3_2);
-	}
-    } else {
-	if (targetNamespace == NULL) {
-	    xmlSchemaPCustomErr(ctxt,
-		XML_SCHEMAP_SRC_IMPORT_3_1,
-		NULL, NULL, node,
-		"The attribute 'namespace' requires the XML schema to be "
-		"imported to have a target namespace of '%s'", namespace);
-	    xmlFreeDoc(doc);
-	    return (XML_SCHEMAP_SRC_IMPORT_3_1);
-	} else if (!xmlStrEqual(targetNamespace, namespace)) {
-	    xmlSchemaPCustomErrExt(ctxt,
-		XML_SCHEMAP_SRC_IMPORT_3_1,
-		NULL, NULL, node,
-		"The value '%s' of the attribute 'namespace' is not "
-		"identical to the target namespace '%s' of the "
-		"XML schema to be imported", 
-		namespace, targetNamespace, NULL);
-	    xmlFreeDoc(doc);
-	    return (XML_SCHEMAP_SRC_IMPORT_3_1);
-	}
+	return (ret);
+    } else if (doc != NULL) {       
+	/*
+	* Save and reset the context & schema.
+	*/
+	url = ctxt->URL;  
+	/* TODO: Is using the doc->URL here correct? */
+	ctxt->URL = doc->URL;
+	flags = schema->flags;
+	oldTNS = schema->targetNamespace;
+	/*
+	* Parse the schema.
+	*/
+	root = xmlDocGetRootElement(doc);
+	xmlSchemaClearSchemaDefaults(schema);
+	xmlSchemaParseSchemaDefaults(ctxt, schema, root);
+	schema->targetNamespace = targetNamespace;
+	xmlSchemaParseSchemaTopLevel(ctxt, schema, root->children);
+	/*
+	* Restore the context & schema.
+	*/
+	schema->flags = flags;
+	schema->targetNamespace = oldTNS;
+	ctxt->URL = url;
     }
-    /*
-    * Finally, import the schema.
-    */
-    if (schema->schemasImports == NULL) {
-	schema->schemasImports = xmlHashCreate(10);
-	if (schema->schemasImports == NULL) {
-	    xmlSchemaPErr2(ctxt, node, child,
-		XML_SCHEMAP_FAILED_BUILD_IMPORT,
-		"Internal error: failed to build import table.\n",
-		NULL, NULL);
-	    return (-1);
-	}
-    }
-    import = (xmlSchemaImport*) xmlMalloc(sizeof(xmlSchemaImport));
-    if (import == NULL) {
-	xmlSchemaPErrMemory(NULL, "allocating imported schema", NULL);
-	xmlFreeDoc(doc);
-	return (-1);
-    }    
-    memset(import, 0, sizeof(xmlSchemaImport));
-    import->schemaLocation = schemaLocation;
-    import->doc = doc;
-    xmlHashAddEntry(schema->schemasImports, ns, import);    
-    /*
-    * Save and reset the context & schema.
-    */
-    url = ctxt->URL;  
-    /* TODO: Check this. */
-    ctxt->URL = schemaLocation;
-    flags = schema->flags;
-    oldTNS = schema->targetNamespace;
-
-    xmlSchemaClearSchemaDefaults(schema);
-    xmlSchemaParseSchemaDefaults(ctxt, schema, root);
-    schema->targetNamespace = targetNamespace;
-    xmlSchemaParseSchemaTopLevel(ctxt, schema, root->children);
-
-    /*
-    * Restore the context & schema.
-    */
-    schema->flags = flags;
-    schema->targetNamespace = oldTNS;
-    ctxt->URL = url;                       
     
-    return (1);
+    return (0);
 }
 
 /**
@@ -7155,8 +7445,13 @@
 	    } while (facet != NULL);
 	}
     }    
-    if (ctxt->ctxtType->type == XML_SCHEMA_TYPE_COMPLEX)
-	child = xmlSchemaParseAttrDecls(ctxt, schema, child, type);    
+    if (ctxt->ctxtType->type == XML_SCHEMA_TYPE_COMPLEX) {
+	child = xmlSchemaParseAttrDecls(ctxt, schema, child, type);
+	if (IS_SCHEMA(child, "anyAttribute")) {
+	    ctxt->ctxtType->attributeWildcard = xmlSchemaParseAnyAttribute(ctxt, schema, child);
+	    child = child->next;
+	}
+    }
     if (child != NULL) {
 	/* TODO: Think about the error code. */
 	if (ctxt->parentItem->type == XML_SCHEMA_TYPE_COMPLEX_CONTENT) {	    
@@ -7250,7 +7545,15 @@
     }
     if (subtype != NULL)
         type->subtypes = subtype;
-    child = xmlSchemaParseAttrDecls(ctxt, schema, child, type);
+    if ((ctxt->ctxtType != NULL) &&
+	(ctxt->ctxtType->type == XML_SCHEMA_TYPE_COMPLEX)) {
+	child = xmlSchemaParseAttrDecls(ctxt, schema, child, type);
+	if (IS_SCHEMA(child, "anyAttribute")) {	    
+	    ctxt->ctxtType->attributeWildcard = 
+		xmlSchemaParseAnyAttribute(ctxt, schema, child);
+	    child = child->next;
+	}
+    }
     if (child != NULL) {
         xmlSchemaPErr2(ctxt, node, child,
 	    XML_SCHEMAP_UNKNOWN_EXTENSION_CHILD,
@@ -7418,6 +7721,11 @@
 
     type->node = node;
     type->type = XML_SCHEMA_TYPE_COMPLEX;
+    /* Set as default for attribute wildcards. 
+    * This will be only changed if a complex type
+    * inherits an attribute wildcard from a base type.
+    */
+    type->flags |= XML_SCHEMAS_TYPE_OWNED_ATTR_WILDCARD;
     if (topLevel) 
         type->flags |= XML_SCHEMAS_TYPE_GLOBAL;
     type->id = xmlSchemaGetProp(ctxt, node, "id");
@@ -7460,6 +7768,10 @@
         if (subtype != NULL)
             type->subtypes = subtype;
         child = xmlSchemaParseAttrDecls(ctxt, schema, child, type);
+	if (IS_SCHEMA(child, "anyAttribute")) {	    
+	    type->attributeWildcard = xmlSchemaParseAnyAttribute(ctxt, schema, child);
+	    child = child->next;
+	}
     }
     if (child != NULL) {
         xmlSchemaPErr2(ctxt, node, child,
@@ -7493,15 +7805,26 @@
     int nberrors;
     xmlAttrPtr attr;
 
+    /*
+    * This one is called by xmlSchemaParse only and is used if
+    * the schema to be parsed was specified via the API; i.e. not
+    * automatically by the validated instance document.
+    */
+
     if ((ctxt == NULL) || (node == NULL))
         return (NULL);
     
     nberrors = ctxt->nberrors;
     ctxt->nberrors = 0;
     if (IS_SCHEMA(node, "schema")) {
+	xmlSchemaImportPtr import;
+
         schema = xmlSchemaNewSchema(ctxt);
         if (schema == NULL)
             return (NULL);
+	/*
+	* Disable build of list of items.
+	*/
 	attr = xmlSchemaGetPropNode(node, "targetNamespace"); 		
 	if (attr != NULL) {
 	    xmlSchemaPValAttrNode(ctxt, NULL, NULL, attr, 
@@ -7513,6 +7836,31 @@
 	} else {
 	    schema->targetNamespace = NULL;
 	}
+	/*
+	* Add the current ns name and location to the import table;
+	* this is needed to have a consistent mechanism, regardless
+	* if all schemata are constructed dynamically fired by the
+	* instance or if the schema to be used was specified via
+	* the API.
+	*/
+	import = xmlSchemaAddImport(ctxt, &(schema->schemasImports),
+	    schema->targetNamespace);
+	if (import == NULL) {
+	    xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_FAILED_BUILD_IMPORT,
+		NULL, NULL, (xmlNodePtr) ctxt->doc,
+		"Internal error: xmlSchemaParseSchema, "
+		"failed to add an import entry", NULL);
+	    xmlSchemaFree(schema);
+	    schema = NULL;
+	    return (NULL);
+	}
+	import->schemaLocation = ctxt->URL;
+	/*
+	* NOTE: We won't set the doc here, otherwise it will be freed
+	* if the import struct is freed.
+	* import->doc = ctxt->doc;
+	*/
+
 	/* TODO: Check id. */
         schema->id = xmlSchemaGetProp(ctxt, node, "id");
 	xmlSchemaPValAttr(ctxt, NULL, NULL, node, "version", 
@@ -7563,6 +7911,61 @@
  * 									*
  ************************************************************************/
 
+#if 0 /* Will be enabled if it is clear what options are needed. */
+/**
+ * xmlSchemaParserCtxtSetOptions:
+ * @ctxt:	a schema parser context
+ * @options: a combination of xmlSchemaParserOption
+ *
+ * Sets the options to be used during the parse.
+ *
+ * Returns 0 in case of success, -1 in case of an
+ * API error.
+ */
+static int
+xmlSchemaParserCtxtSetOptions(xmlSchemaParserCtxtPtr ctxt,
+			      int options)
+					
+{
+    int i;
+
+    if (ctxt == NULL)
+	return (-1);
+    /*
+    * WARNING: Change the start value if adding to the
+    * xmlSchemaParseOption.
+    */
+    for (i = 1; i < (int) sizeof(int) * 8; i++) {
+        if (options & 1<<i) {
+	    return (-1);   
+        }	
+    }
+    ctxt->options = options;
+    return (0);      
+}
+
+/**
+ * xmlSchemaValidCtxtGetOptions:
+ * @ctxt: a schema parser context 
+ *
+ * Returns the option combination of the parser context.
+ */
+static int
+xmlSchemaParserCtxtGetOptions(xmlSchemaParserCtxtPtr ctxt)
+					
+{    
+    if (ctxt == NULL)
+	return (-1);
+    else 
+	return (ctxt->options);    
+}
+
+ void *curItems;  /* used for dynamic addition of schemata */
+    int nbCurItems; /* used for dynamic addition of schemata */
+    int sizeCurItems; /* used for dynamic addition of schemata */
+
+#endif
+
 /**
  * xmlSchemaNewParserCtxt:
  * @URL:  the location of the schema
@@ -7594,6 +7997,38 @@
 }
 
 /**
+ * xmlSchemaNewParserCtxtUseDict:
+ * @URL:  the location of the schema
+ * @dict: the dictionary to be used
+ *
+ * Create an XML Schemas parse context for that file/resource expected
+ * to contain an XML Schemas file.
+ *
+ * Returns the parser context or NULL in case of error
+ */
+static xmlSchemaParserCtxtPtr
+xmlSchemaNewParserCtxtUseDict(const char *URL, xmlDictPtr dict)
+{
+    xmlSchemaParserCtxtPtr ret;
+
+    if (URL == NULL)
+        return (NULL);
+
+    ret = (xmlSchemaParserCtxtPtr) xmlMalloc(sizeof(xmlSchemaParserCtxt));
+    if (ret == NULL) {
+        xmlSchemaPErrMemory(NULL, "allocating schema parser context",
+                            NULL);
+        return (NULL);
+    }
+    memset(ret, 0, sizeof(xmlSchemaParserCtxt));
+    ret->dict = dict;
+    ret->URL = xmlDictLookup(dict, (const xmlChar *) URL, -1);
+    ret->includes = 0;
+    return (ret);
+}
+
+
+/**
  * xmlSchemaNewMemParserCtxt:
  * @buffer:  a pointer to a char array containing the schemas
  * @size:  the size of the array
@@ -7669,6 +8104,10 @@
         return;
     if (ctxt->doc != NULL && !ctxt->preserve)
         xmlFreeDoc(ctxt->doc);
+    if (ctxt->assemble != NULL) {
+	xmlFree(ctxt->assemble->items);
+	xmlFree(ctxt->assemble);
+    }
     xmlDictFree(ctxt->dict);
     xmlFree(ctxt);
 }
@@ -7804,122 +8243,114 @@
             break;
 	}
         case XML_SCHEMA_TYPE_ELEMENT:{
-                xmlSchemaElementPtr elem = (xmlSchemaElementPtr) type;		
-		
-                /* TODO : handle the namespace too */
-                xmlAutomataStatePtr oldstate = ctxt->state;
+		xmlAutomataStatePtr oldstate;
+                xmlSchemaElementPtr particle, elemDecl;
 
-                if (elem->maxOccurs >= UNBOUNDED) {
-                    if (elem->minOccurs > 1) {
+		/*
+		* IMPORTANT: This puts element declarations
+		* (and never element decl. references) into the
+		* automaton. This is crucial and should not be changed, 
+		* since validating functions rely now on it.
+		*/
+		particle = (xmlSchemaElementPtr) type;
+		if (particle->ref != NULL) {
+		    if (particle->refDecl == NULL) {
+			/*
+			* Skip content model creation if the reference
+			* did not resolve to a declaration.
+			*/
+			break;
+		    } else {
+			/*
+			* Referenced global element declaration.
+			*/
+			elemDecl = particle->refDecl;
+		    }
+		} else {
+		    /*
+		    * Anonymous element declaration.
+		    */
+		    elemDecl = particle;
+		}
+		
+                oldstate = ctxt->state;
+
+                if (particle->maxOccurs >= UNBOUNDED) {
+                    if (particle->minOccurs > 1) {
                         xmlAutomataStatePtr tmp;
                         int counter;
 
                         ctxt->state = xmlAutomataNewEpsilon(ctxt->am,
-                                                            oldstate,
-                                                            NULL);
+			    oldstate, NULL);
                         oldstate = ctxt->state;
-
                         counter = xmlAutomataNewCounter(ctxt->am,
-                                                        elem->minOccurs -
-                                                        1, UNBOUNDED);
-
-                        if (elem->refDecl != NULL) {
-                            xmlSchemaBuildAContentModel((xmlSchemaTypePtr)
-                                                        elem->refDecl,
-                                                        ctxt,
-                                                        elem->refDecl->
-                                                        name);
-                        } else {
-                            ctxt->state =
-                                xmlAutomataNewTransition2(ctxt->am,
-                                                         ctxt->state, NULL,
-                                                         elem->name, 
-							 elem->targetNamespace,
-							 type);
-                        }
+			    particle->minOccurs - 1, UNBOUNDED);                      
+                        ctxt->state =                            
+			    xmlAutomataNewTransition2(ctxt->am,
+				ctxt->state, NULL, 
+				elemDecl->name, 
+				elemDecl->targetNamespace,
+				(xmlSchemaTypePtr) elemDecl);
                         tmp = ctxt->state;
                         xmlAutomataNewCountedTrans(ctxt->am, tmp, oldstate,
-                                                   counter);
+			    counter);
                         ctxt->state =
                             xmlAutomataNewCounterTrans(ctxt->am, tmp, NULL,
-                                                       counter);
+				counter);
 
-                    } else {
-                        if (elem->refDecl != NULL) {
-                            xmlSchemaBuildAContentModel((xmlSchemaTypePtr)
-                                                        elem->refDecl,
-                                                        ctxt,
-                                                        elem->refDecl->
-                                                        name);
-                        } else {
-                            ctxt->state =
-                                xmlAutomataNewTransition2(ctxt->am,
-                                                         ctxt->state, NULL,
-                                                         elem->name, 
-							 elem->targetNamespace,
-							 type);
-                        }
+                    } else {                        
+			ctxt->state =
+			    xmlAutomataNewTransition2(ctxt->am,
+			    ctxt->state, NULL,
+			    elemDecl->name, 
+			    elemDecl->targetNamespace,
+			    (xmlSchemaTypePtr) elemDecl);
                         xmlAutomataNewEpsilon(ctxt->am, ctxt->state,
                                               oldstate);
-                        if (elem->minOccurs == 0) {
+                        if (particle->minOccurs == 0) {
                             /* basically an elem* */
                             xmlAutomataNewEpsilon(ctxt->am, oldstate,
                                                   ctxt->state);
                         }
                     }
-                } else if ((elem->maxOccurs > 1) || (elem->minOccurs > 1)) {
+                } else if ((particle->maxOccurs > 1) || (particle->minOccurs > 1)) {
                     xmlAutomataStatePtr tmp;
                     int counter;
 
                     ctxt->state = xmlAutomataNewEpsilon(ctxt->am,
                                                         oldstate, NULL);
                     oldstate = ctxt->state;
-
                     counter = xmlAutomataNewCounter(ctxt->am,
-                                                    elem->minOccurs - 1,
-                                                    elem->maxOccurs - 1);
-
-                    if (elem->refDecl != NULL) {
-                        xmlSchemaBuildAContentModel((xmlSchemaTypePtr)
-                                                    elem->refDecl, ctxt,
-                                                    elem->refDecl->name);
-                    } else {
-                        ctxt->state = xmlAutomataNewTransition2(ctxt->am,
-                                                               ctxt->state,
-                                                               NULL,
-                                                               elem->name,
-							       elem->targetNamespace,
-                                                               type);
-                    }
+			particle->minOccurs - 1,
+			particle->maxOccurs - 1);
+                    ctxt->state = xmlAutomataNewTransition2(ctxt->am,
+			ctxt->state,
+			NULL,
+			elemDecl->name,
+			elemDecl->targetNamespace,
+			(xmlSchemaTypePtr) elemDecl);
                     tmp = ctxt->state;
                     xmlAutomataNewCountedTrans(ctxt->am, tmp, oldstate,
-                                               counter);
+			counter);
                     ctxt->state = xmlAutomataNewCounterTrans(ctxt->am, tmp,
-                                                             NULL,
-                                                             counter);
-                    if (elem->minOccurs == 0) {
+			NULL, counter);
+                    if (particle->minOccurs == 0) {
                         /* basically an elem? */
                         xmlAutomataNewEpsilon(ctxt->am, oldstate,
-                                              ctxt->state);
+			    ctxt->state);
                     }
 
-                } else {
-                    if (elem->refDecl != NULL) {
-                        xmlSchemaBuildAContentModel((xmlSchemaTypePtr)
-                                                    elem->refDecl, ctxt,
-                                                    elem->refDecl->name);
-                    } else {
-                        ctxt->state = xmlAutomataNewTransition2(ctxt->am,
-                                                               ctxt->state,
-                                                               NULL,
-                                                               elem->name,
-							       elem->targetNamespace,
-                                                               type);
-                    }
-                    if (elem->minOccurs == 0) {
+                } else {                    
+		    ctxt->state = xmlAutomataNewTransition2(ctxt->am,
+			ctxt->state,
+			NULL,
+			elemDecl->name,
+			elemDecl->targetNamespace,
+			(xmlSchemaTypePtr) elemDecl);
+                    if (particle->minOccurs == 0) {
                         /* basically an elem? */
                         xmlAutomataNewEpsilon(ctxt->am, oldstate,
-                                              ctxt->state);
+			    ctxt->state);
                     }
                 }
                 break;
@@ -8132,7 +8563,12 @@
         case XML_SCHEMA_TYPE_EXTENSION:
             if (type->baseType != NULL) {
                 xmlSchemaTypePtr subtypes;
-
+		
+		/*
+		* TODO: Circular definitions will be checked at the
+		* constraint level. So remove this when the complex type
+		* constraints are implemented.
+		*/
 		if (type->recurse) { 
 		    /* TODO: Change the error code. */
 		    xmlSchemaPCustomErr(ctxt,
@@ -8214,30 +8650,24 @@
 
 /**
  * xmlSchemaBuildContentModel:
- * @elem:  the element
+ * @type:  the type definition (or reference)
  * @ctxt:  the schema parser context
  * @name:  the element name
  *
- * Builds the content model of the element.
+ * Builds the content model of the complex type.
  */
 static void
-xmlSchemaBuildContentModel(xmlSchemaElementPtr elem,
+xmlSchemaBuildContentModel(xmlSchemaTypePtr type,
                            xmlSchemaParserCtxtPtr ctxt,
                            const xmlChar * name)
 {
     xmlAutomataStatePtr start;
 
-    if (elem->contModel != NULL)
-        return;
-    if (elem->subtypes == NULL) {
-        elem->contentType = XML_SCHEMA_CONTENT_ANY;
-        return;
-    }
-    if (elem->subtypes->type != XML_SCHEMA_TYPE_COMPLEX)
-        return;
-    if ((elem->subtypes->contentType == XML_SCHEMA_CONTENT_BASIC) ||
-        (elem->subtypes->contentType == XML_SCHEMA_CONTENT_SIMPLE))
-        return;
+    if ((type->type != XML_SCHEMA_TYPE_COMPLEX) || (type->ref != NULL) ||
+	(type->contentType == XML_SCHEMA_CONTENT_BASIC) ||
+	(type->contentType == XML_SCHEMA_CONTENT_SIMPLE) ||
+	(type->contModel != NULL))
+	return;
 
 #ifdef DEBUG_CONTENT
     xmlGenericError(xmlGenericErrorContext,
@@ -8247,28 +8677,29 @@
     ctxt->am = xmlNewAutomata();
     if (ctxt->am == NULL) {
         xmlGenericError(xmlGenericErrorContext,
-                        "Cannot create automata for elem %s\n", name);
+                        "Cannot create automata for complex tpye %s\n", name);
         return;
     }
     start = ctxt->state = xmlAutomataGetInitState(ctxt->am);
-    xmlSchemaBuildAContentModel(elem->subtypes, ctxt, name);
+    xmlSchemaBuildAContentModel(type, ctxt, name);
     xmlAutomataSetFinalState(ctxt->am, ctxt->state);
-    elem->contModel = xmlAutomataCompile(ctxt->am);
-    if (elem->contModel == NULL) {
-        xmlSchemaPCustomErr(ctxt, XML_SCHEMAP_INTERNAL, 
-	    NULL, (xmlSchemaTypePtr) elem, NULL,	    
+    type->contModel = xmlAutomataCompile(ctxt->am);
+    if (type->contModel == NULL) {
+        xmlSchemaPCustomErr(ctxt, 
+	    XML_SCHEMAP_INTERNAL, 
+	    NULL, type, type->node,	    
 	    "Failed to compile the content model", NULL);
-    } else if (xmlRegexpIsDeterminist(elem->contModel) != 1) {
+    } else if (xmlRegexpIsDeterminist(type->contModel) != 1) {
         xmlSchemaPCustomErr(ctxt, 
 	    XML_SCHEMAP_NOT_DETERMINISTIC,
 	    /* XML_SCHEMAS_ERR_NOTDETERMINIST, */
-	    NULL, (xmlSchemaTypePtr) elem, NULL,
+	    NULL, type, type->node,
 	    "The content model is not determinist", NULL);
     } else {
 #ifdef DEBUG_CONTENT_REGEXP
         xmlGenericError(xmlGenericErrorContext,
                         "Content model of %s:\n", name);
-        xmlRegexpPrint(stderr, elem->contModel);
+        xmlRegexpPrint(stderr, type->contModel);
 #endif
     }
     ctxt->state = NULL;
@@ -9248,7 +9679,32 @@
 	if (attrs->type == XML_SCHEMA_TYPE_ATTRIBUTEGROUP) {
 	    xmlSchemaAttributeGroupPtr group;
 
-	    group = (xmlSchemaAttributeGroupPtr) attrs;	  
+	    group = (xmlSchemaAttributeGroupPtr) attrs;
+	    /*
+	    * Handle attribute group references.
+	    */
+	    if (group->ref != NULL) {
+		if (group->refItem == NULL) {
+		    /*
+		    * TODO: Should we raise a warning here?
+		    */
+		    /*
+		    * The referenced attribute group definition could not
+		    * be resolved beforehand, so skip.
+		    */
+		    attrs = attrs->next;
+		    continue;
+		} else
+		    group = group->refItem;
+	    }	    
+	    /*
+	    * For every attribute group definition, an intersected wildcard 
+	    * will be created (assumed that a wildcard exists on the 
+	    * particular attr. gr. def. or on any contained attr. gr. def 
+	    * at all).
+	    * The flag XML_SCHEMAS_ATTRGROUP_WILDCARD_BUILDED ensures
+	    * that the intersection will be performed only once.
+	    */
 	    if ((group->flags & XML_SCHEMAS_ATTRGROUP_WILDCARD_BUILDED) == 0) {
 		if (group->attributes != NULL) {
 		    if (xmlSchemaBuildCompleteAttributeWildcard(ctxt, 
@@ -9271,6 +9727,7 @@
 		    /*
 		    * Although the complete wildcard might not correspond to any
 		    * node in the schema, we will save this context node.
+		    * TODO: Hmm, is this sane?
 		    */
 		    (*completeWild)->node = group->attributeWildcard->node;  
 		    
@@ -9392,8 +9849,11 @@
     if ((type->subtypes != NULL) && 
 	((type->subtypes->type == XML_SCHEMA_TYPE_COMPLEX_CONTENT) || 
 	 (type->subtypes->type == XML_SCHEMA_TYPE_SIMPLE_CONTENT))) {
+	/* 
+	* type --> (<simpleContent>|<complexContent>) 
+	*        --> (<restriction>|<extension>) --> attributes
+	*/ 
 	attrs = type->subtypes->subtypes->attributes;
-	type->attributeWildcard = type->subtypes->subtypes->attributeWildcard;
     } else {
 	/* Short hand form of the complexType. */
 	attrs = type->attributes;
@@ -9404,29 +9864,16 @@
     err = xmlSchemaBuildCompleteAttributeWildcard(ctxt, 
 	attrs, &type->attributeWildcard);    
     /*
-    * TODO: This "onwed_attr_wildcard" is quite sensless: we should
-    * create the wildcard right from the start on the complexType,
-    * rather than on the <restriction>/<extension>.
-    *
-    * This here simply checks if <complexType>-><restriction>|<extension>
-    * does exist and its wildcard is used or not.
+    * NOTE: During the parse time, the wildcard is created on the complexType
+    * directly, if encountered in a <restriction> or <extension> element.
     */
-    if (type->attributeWildcard != NULL) {
-	if ((type->subtypes == NULL) ||
-	    ((type->subtypes->type != XML_SCHEMA_TYPE_COMPLEX_CONTENT) &&
-	     (type->subtypes->type != XML_SCHEMA_TYPE_SIMPLE_CONTENT)) ||
-	    (type->subtypes->subtypes == NULL) ||
-	    (type->attributeWildcard != type->subtypes->subtypes->attributeWildcard)) {
-	    type->flags |= XML_SCHEMAS_TYPE_OWNED_ATTR_WILDCARD;
-	}
-    }
-    /*
-    * Note that an error for the above call to 
-    * xmlSchemaBuildCompleteAttributeWildcard is processed here, since we
-    * needed to set XML_SCHEMAS_TYPE_OWNED_ATTR_WILDCARD beforehand.
-    */
-    if (err == -1)
+    if (err == -1) {
+	xmlSchemaPErr(ctxt, type->node, XML_SCHEMAP_INTERNAL,
+	    "Internal error: xmlSchemaBuildAttributeValidation: "
+	    "failed to build an intersected attribute wildcard.\n",
+	    NULL, NULL);
 	return (-1);
+    }
 
     if ((type->flags & XML_SCHEMAS_TYPE_DERIVATION_METHOD_EXTENSION) && 
 	((baseIsAnyType) ||
@@ -9444,6 +9891,12 @@
 	    /*
 	    * Just inherit the wildcard.
 	    */
+	    /*
+	    * NOTE: This is the only case where an attribute 
+            * wildcard is shared.
+            */
+	    if (type->flags & XML_SCHEMAS_TYPE_OWNED_ATTR_WILDCARD)
+		type->flags ^= XML_SCHEMAS_TYPE_OWNED_ATTR_WILDCARD;
 	    type->attributeWildcard = baseType->attributeWildcard;
 	}
     }
@@ -10681,8 +11134,8 @@
     * 1 It is schema-valid with respect to that definition as defined 
     * by Datatype Valid in [XML Schemas: Datatypes].
     */
-    ctxt->type = type;
-    ret = xmlSchemaValidateSimpleTypeValue(ctxt, value, fireErrors, 1, 1);
+    ret = xmlSchemaValidateSimpleTypeValue(ctxt, type, value, 
+	fireErrors, 1, 1, 1);
     return (ret);
     /*
     * 2.1 If The definition is ENTITY or is validly derived from ENTITY given 
@@ -10748,17 +11201,20 @@
 		"creation of a new validation context failed.\n",
 		NULL, NULL);
 	    return (-1);	
-	}
+	}	
+	if (elemDecl->flags & XML_SCHEMAS_ELEM_FIXED)
+	    attr = xmlSchemaGetPropNode(elemDecl->node, "fixed");
+	else
+	    attr = xmlSchemaGetPropNode(elemDecl->node, "default");
 	/*
-	* TODO: This won't work. 
+	* TODO: This won't work yet. 
 	*/
-	if (typeDef->type == XML_SCHEMA_TYPE_SIMPLE)
-	    ret = xmlSchemaCheckCVCSimpleType(vctxt, elemDecl->value, typeDef, 0);	
-	if (ret > 0) {
-	    if (elemDecl->flags & XML_SCHEMAS_ELEM_FIXED)
-		attr = xmlSchemaGetPropNode(elemDecl->node, "fixed");
-	    else
-		attr = xmlSchemaGetPropNode(elemDecl->node, "default");
+	if (typeDef->type == XML_SCHEMA_TYPE_SIMPLE) {
+	    vctxt->node = elemDecl->node;
+	    vctxt->cur = attr->children;
+	    ret = xmlSchemaCheckCVCSimpleType(vctxt, elemDecl->value, typeDef, 0);
+	}
+	if (ret > 0) {	    
 	    if (ctxt != NULL) {
 		xmlSchemaPSimpleTypeErr(ctxt, 
 		    XML_SCHEMAP_COS_VALID_DEFAULT_2_1, 
@@ -10808,8 +11264,9 @@
 		    NULL, NULL);
 		return (-1);	
 	    }
-	    vctxt->type = elemDecl->subtypes;	    
-	    ret = xmlSchemaValidateSimpleTypeValue(vctxt, elemDecl->value, 0, 1, 1);	    
+
+	    ret = xmlSchemaValidateSimpleTypeValue(vctxt, elemDecl->subtypes, 
+		elemDecl->value, 0, 1, 1);	    
 	    if (ret > 0) {
 		if (elemDecl->flags & XML_SCHEMAS_ELEM_FIXED)
 		    attr = xmlSchemaGetPropNode(elemDecl->node, "fixed");
@@ -11045,19 +11502,19 @@
  * Fixes the content model of the type.
  */
 static void
-xmlSchemaTypeFixup(xmlSchemaTypePtr typeDecl,
+xmlSchemaTypeFixup(xmlSchemaTypePtr item,
                    xmlSchemaParserCtxtPtr ctxt, const xmlChar * name)
 {
     xmlSchemaTypePtr ctxtType;
 
-    if (typeDecl == NULL)
+    if (item == NULL)
         return;
     /*
     * Do not allow the following types to be typefixed, prior to
     * the corresponding simple/complex types.
     */
     if (ctxt->ctxtType == NULL) {
-	switch (typeDecl->type) {
+	switch (item->type) {
 	    case XML_SCHEMA_TYPE_SIMPLE_CONTENT:
 	    case XML_SCHEMA_TYPE_COMPLEX_CONTENT:
 	    case XML_SCHEMA_TYPE_UNION:
@@ -11069,18 +11526,18 @@
 	}
     }
     if (name == NULL)
-        name = typeDecl->name;
-    if (typeDecl->contentType == XML_SCHEMA_CONTENT_UNKNOWN) {
-        switch (typeDecl->type) {
+        name = item->name;
+    if (item->contentType == XML_SCHEMA_CONTENT_UNKNOWN) {
+        switch (item->type) {
             case XML_SCHEMA_TYPE_SIMPLE_CONTENT:{		    
-		    if (typeDecl->subtypes != NULL) {
-			if (typeDecl->subtypes->contentType ==
+		    if (item->subtypes != NULL) {
+			if (item->subtypes->contentType ==
 			    XML_SCHEMA_CONTENT_UNKNOWN) {
-			    xmlSchemaTypeFixup(typeDecl->subtypes, ctxt,
+			    xmlSchemaTypeFixup(item->subtypes, ctxt,
 				NULL);
 			}
-                        typeDecl->contentType =
-                            typeDecl->subtypes->contentType;
+                        item->contentType =
+                            item->subtypes->contentType;
 		    }
                     break;
                 }
@@ -11089,18 +11546,18 @@
 
 		    ctxt->ctxtType->flags |= 
 			XML_SCHEMAS_TYPE_DERIVATION_METHOD_RESTRICTION;
-		    if (typeDecl->baseType != NULL)
-			base = typeDecl->baseType;
-                    else if (typeDecl->base != NULL) {
+		    if (item->baseType != NULL)
+			base = item->baseType;
+                    else if (item->base != NULL) {
                         base =
-                            xmlSchemaGetType(ctxt->schema, typeDecl->base,
-                                             typeDecl->baseNs);
+                            xmlSchemaGetType(ctxt->schema, item->base,
+                                             item->baseNs);
                         if (base == NULL) {
 			    xmlSchemaPResCompAttrErr(ctxt, 
 				XML_SCHEMAP_SRC_RESOLVE, 
 				NULL, NULL, 
-				(xmlNodePtr) xmlSchemaGetPropNode(typeDecl->node, "base"),
-				"base", typeDecl->base, typeDecl->baseNs,
+				(xmlNodePtr) xmlSchemaGetPropNode(item->node, "base"),
+				"base", item->base, item->baseNs,
 				XML_SCHEMA_TYPE_BASIC, "type definition");			    
                         } else if (base->contentType == 
 			    XML_SCHEMA_CONTENT_UNKNOWN) {
@@ -11115,24 +11572,24 @@
 			/*
 			* Content type.
 			*/
-			if (typeDecl->subtypes == NULL)
+			if (item->subtypes == NULL)
 			    /* 1.1.1 */
-			    typeDecl->contentType = XML_SCHEMA_CONTENT_EMPTY;
-			else if ((typeDecl->subtypes->subtypes == NULL) &&
-			    ((typeDecl->subtypes->type ==
+			    item->contentType = XML_SCHEMA_CONTENT_EMPTY;
+			else if ((item->subtypes->subtypes == NULL) &&
+			    ((item->subtypes->type ==
 			    XML_SCHEMA_TYPE_ALL)
-			    || (typeDecl->subtypes->type ==
+			    || (item->subtypes->type ==
 			    XML_SCHEMA_TYPE_SEQUENCE)))
 			    /* 1.1.2 */
-			    typeDecl->contentType = XML_SCHEMA_CONTENT_EMPTY;
-			else if ((typeDecl->subtypes->type ==
+			    item->contentType = XML_SCHEMA_CONTENT_EMPTY;
+			else if ((item->subtypes->type ==
 			    XML_SCHEMA_TYPE_CHOICE)
-			    && (typeDecl->subtypes->subtypes == NULL))
+			    && (item->subtypes->subtypes == NULL))
 			    /* 1.1.3 */
-			    typeDecl->contentType = XML_SCHEMA_CONTENT_EMPTY;
+			    item->contentType = XML_SCHEMA_CONTENT_EMPTY;
 			else {
 			    /* 1.2 and 2.X are applied at the other layer */
-			    typeDecl->contentType =
+			    item->contentType =
 				XML_SCHEMA_CONTENT_ELEMENTS;
 			}
 		    } else {	
@@ -11152,29 +11609,29 @@
 		    */
 		    ctxt->ctxtType->flags |= 
 			XML_SCHEMAS_TYPE_DERIVATION_METHOD_EXTENSION;
-		    if (typeDecl->recurse) {
+		    if (item->recurse) {
 			/* TODO: The word "recursive" should be changed to "circular" here. */
 			xmlSchemaPCustomErr(ctxt,
 			    XML_SCHEMAP_UNKNOWN_BASE_TYPE,
-			    NULL, typeDecl, typeDecl->node,	
+			    NULL, item, item->node,	
 			    "This item is circular", NULL);
                         return;
 		    }
-		    if (typeDecl->base != NULL) {                        
+		    if (item->base != NULL) {                        
                         base =
-                            xmlSchemaGetType(ctxt->schema, typeDecl->base,
-                                             typeDecl->baseNs);
+                            xmlSchemaGetType(ctxt->schema, item->base,
+                                             item->baseNs);
                         if (base == NULL) {
 			    xmlSchemaPResCompAttrErr(ctxt, 
 				XML_SCHEMAP_SRC_RESOLVE, 
-				NULL, typeDecl, typeDecl->node,
-				"base", typeDecl->base, typeDecl->baseNs,
+				NULL, item, item->node,
+				"base", item->base, item->baseNs,
 				XML_SCHEMA_TYPE_BASIC, "type definition");				   
                         } else if (base->contentType == 
 			    XML_SCHEMA_CONTENT_UNKNOWN) {
-			    typeDecl->recurse = 1;
+			    item->recurse = 1;
 			    xmlSchemaTypeFixup(base, ctxt, NULL);
-			    typeDecl->recurse = 0;
+			    item->recurse = 0;
                         }
 			/*
 			* The type definition ·resolved· to by the ·actual 
@@ -11186,41 +11643,41 @@
 			* the content model by xmlSchemaBuildAContentModel.
 			* Try to get rid of it.
 			*/
-			typeDecl->baseType = base;			
+			item->baseType = base;			
                     }
-		    if ((typeDecl->subtypes != NULL) &&
-			(typeDecl->subtypes->contentType == XML_SCHEMA_CONTENT_UNKNOWN))
-                        xmlSchemaTypeFixup(typeDecl->subtypes, ctxt, NULL);	    
+		    if ((item->subtypes != NULL) &&
+			(item->subtypes->contentType == XML_SCHEMA_CONTENT_UNKNOWN))
+                        xmlSchemaTypeFixup(item->subtypes, ctxt, NULL);	    
 		    
 		    explicitContentType = XML_SCHEMA_CONTENT_ELEMENTS;
-		    if (typeDecl->subtypes == NULL)
+		    if (item->subtypes == NULL)
 			/* 1.1.1 */
 			explicitContentType = XML_SCHEMA_CONTENT_EMPTY;
-		    else if ((typeDecl->subtypes->subtypes == NULL) &&
-			((typeDecl->subtypes->type ==
+		    else if ((item->subtypes->subtypes == NULL) &&
+			((item->subtypes->type ==
 			XML_SCHEMA_TYPE_ALL)
-			|| (typeDecl->subtypes->type ==
+			|| (item->subtypes->type ==
 			XML_SCHEMA_TYPE_SEQUENCE)))
 			/* 1.1.2 */
 			explicitContentType = XML_SCHEMA_CONTENT_EMPTY;
-		    else if ((typeDecl->subtypes->type ==
+		    else if ((item->subtypes->type ==
 			XML_SCHEMA_TYPE_CHOICE)
-			&& (typeDecl->subtypes->subtypes == NULL))
+			&& (item->subtypes->subtypes == NULL))
 			/* 1.1.3 */
 			explicitContentType = XML_SCHEMA_CONTENT_EMPTY;
 		    if (base != NULL) {
 			/* It will be reported later, if the base is missing. */			    
 			if (explicitContentType == XML_SCHEMA_CONTENT_EMPTY) {
 			    /* 2.1 */
-			    typeDecl->contentType = base->contentType;
+			    item->contentType = base->contentType;
 			} else if (base->contentType ==
 			    XML_SCHEMA_CONTENT_EMPTY) {
 			    /* 2.2 imbitable ! */
-			    typeDecl->contentType =
+			    item->contentType =
 				XML_SCHEMA_CONTENT_ELEMENTS;
 			} else {
 			    /* 2.3 imbitable pareil ! */
-			    typeDecl->contentType =
+			    item->contentType =
 				XML_SCHEMA_CONTENT_ELEMENTS;
 			}
 		    }		                
@@ -11228,11 +11685,17 @@
                 }
             case XML_SCHEMA_TYPE_COMPLEX:{
 		    ctxtType = ctxt->ctxtType;
-		    ctxt->ctxtType = typeDecl;
-		    if ((typeDecl->subtypes == NULL) || 
-			((typeDecl->subtypes->type != 
+		    ctxt->ctxtType = item;
+		    /*
+		    * Start with an empty content-type type.
+		    */
+		    if (item->subtypes == NULL)
+			item->contentType = XML_SCHEMA_CONTENT_EMPTY;
+
+		    if ((item->subtypes == NULL) || 
+			((item->subtypes->type != 
 			XML_SCHEMA_TYPE_SIMPLE_CONTENT) && 
-			(typeDecl->subtypes->type != 
+			(item->subtypes->type != 
 			XML_SCHEMA_TYPE_COMPLEX_CONTENT))) {
 			/* 
 			* This case is understood as shorthand for complex 
@@ -11240,60 +11703,62 @@
 			* the details of the mappings should be modified as 
 			* necessary.
 			*/			
-			typeDecl->baseType = xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYTYPE);
-			typeDecl->flags |= 
+			item->baseType = xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYTYPE);
+			item->flags |= 
 			    XML_SCHEMAS_TYPE_DERIVATION_METHOD_RESTRICTION;
+			/*
+			* Assume that we inherit the content-type type from 'anyType'.
+			*/
+			item->contentType = item->baseType->contentType;
+		    } 			
+		    /*
+		    * Fixup the sub components.
+		    */
+		    if ((item->subtypes != NULL) &&
+			(item->subtypes->contentType ==
+			XML_SCHEMA_CONTENT_UNKNOWN)) {			    
+			xmlSchemaTypeFixup(item->subtypes, ctxt, NULL);
 		    }
-                    if (typeDecl->subtypes == NULL) {
-			typeDecl->contentType = XML_SCHEMA_CONTENT_EMPTY;
-                        if (typeDecl->flags & XML_SCHEMAS_TYPE_MIXED)
-                            typeDecl->contentType =
-                                XML_SCHEMA_CONTENT_MIXED;			
-                    } else {
-			if ((typeDecl->subtypes != NULL) &&
-			    (typeDecl->subtypes->contentType ==
-			    XML_SCHEMA_CONTENT_UNKNOWN)) {			    
-			    xmlSchemaTypeFixup(typeDecl->subtypes, ctxt,
-				NULL);			    
-			}
-                        if (typeDecl->flags & XML_SCHEMAS_TYPE_MIXED) {
-                            typeDecl->contentType =
-                                XML_SCHEMA_CONTENT_MIXED;
-                        } else {			    
-                            if (typeDecl->subtypes != NULL) {
-                                typeDecl->contentType =
-                                    typeDecl->subtypes->contentType;
-			    }
-                        }			
-                    }
-		    xmlSchemaBuildAttributeValidation(ctxt, typeDecl);
+		    if (item->flags & XML_SCHEMAS_TYPE_MIXED) {
+			item->contentType = XML_SCHEMA_CONTENT_MIXED;			
+		    } else if (item->subtypes != NULL) {
+			/*
+			* Use the content-type type of the model groups
+			* defined, if 'mixed' is not set. If 'mixed' is set
+			* it will expand the content-type by allowing character
+			* content to appear.
+			*/
+			item->contentType =
+			    item->subtypes->contentType;
+		    }
+		    xmlSchemaBuildAttributeValidation(ctxt, item);
 		    ctxt->ctxtType = ctxtType;
                     break;
                 }
             case XML_SCHEMA_TYPE_COMPLEX_CONTENT:{
-                    if (typeDecl->subtypes == NULL) {
-                        typeDecl->contentType = XML_SCHEMA_CONTENT_EMPTY;
-                        if (typeDecl->flags & XML_SCHEMAS_TYPE_MIXED)
-                            typeDecl->contentType =
+                    if (item->subtypes == NULL) {
+                        item->contentType = XML_SCHEMA_CONTENT_EMPTY;
+                        if (item->flags & XML_SCHEMAS_TYPE_MIXED)
+                            item->contentType =
                                 XML_SCHEMA_CONTENT_MIXED;
                     } else {
-                        if (typeDecl->flags & XML_SCHEMAS_TYPE_MIXED) {
-                            typeDecl->contentType =
+                        if (item->flags & XML_SCHEMAS_TYPE_MIXED) {
+                            item->contentType =
                                 XML_SCHEMA_CONTENT_MIXED;
                         } else {
-                            xmlSchemaTypeFixup(typeDecl->subtypes, ctxt,
+                            xmlSchemaTypeFixup(item->subtypes, ctxt,
                                                NULL);
-                            if (typeDecl->subtypes != NULL)
-                                typeDecl->contentType =
-                                    typeDecl->subtypes->contentType;
+                            if (item->subtypes != NULL)
+                                item->contentType =
+                                    item->subtypes->contentType;
                         }
 			/* 
 			 * Removed due to implementation of the build of attribute uses. 
 			 */
 			/*
-			if (typeDecl->attributes == NULL)
-			    typeDecl->attributes =
-			        typeDecl->subtypes->attributes;
+			if (item->attributes == NULL)
+			    item->attributes =
+			        item->subtypes->attributes;
 			*/
                     }
                     break;
@@ -11304,35 +11769,35 @@
 		*
 		*/
 		ctxtType = ctxt->ctxtType;		
-		typeDecl->contentType = XML_SCHEMA_CONTENT_SIMPLE;
-		if (typeDecl->subtypes->contentType == 
+		item->contentType = XML_SCHEMA_CONTENT_SIMPLE;
+		if (item->subtypes->contentType == 
 		    XML_SCHEMA_CONTENT_UNKNOWN) {
-		    ctxt->ctxtType = typeDecl;
-		    xmlSchemaTypeFixup(typeDecl->subtypes, ctxt, NULL);
+		    ctxt->ctxtType = item;
+		    xmlSchemaTypeFixup(item->subtypes, ctxt, NULL);
 		}
 		/* Fixup base type */		
-		if ((typeDecl->baseType != NULL) && 
-		    (typeDecl->baseType->contentType ==
+		if ((item->baseType != NULL) && 
+		    (item->baseType->contentType ==
 		    XML_SCHEMA_CONTENT_UNKNOWN)) {
 		    /* OPTIMIZE: Actually this one will never by hit, since
 		    * the base type is already type-fixed in <restriction>.
 		    */
-		    ctxt->ctxtType = typeDecl;
-		    xmlSchemaTypeFixup(typeDecl->baseType, ctxt, NULL);
+		    ctxt->ctxtType = item;
+		    xmlSchemaTypeFixup(item->baseType, ctxt, NULL);
 		}
 		/* Base type: 
 		* 2 If the <list> or <union> alternative is chosen, 
 		* then the ·simple ur-type definition·.
 		*/
-		if (typeDecl->subtypes->type ==
+		if (item->subtypes->type ==
 		    XML_SCHEMA_TYPE_LIST) {
-		    typeDecl->baseType = xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYSIMPLETYPE);
-		    typeDecl->flags |= XML_SCHEMAS_TYPE_VARIETY_LIST;		    
-		} else if (typeDecl->subtypes->type ==
+		    item->baseType = xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYSIMPLETYPE);
+		    item->flags |= XML_SCHEMAS_TYPE_VARIETY_LIST;		    
+		} else if (item->subtypes->type ==
 		    XML_SCHEMA_TYPE_UNION) {
-		    typeDecl->baseType = xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYSIMPLETYPE);
-		    typeDecl->flags |= XML_SCHEMAS_TYPE_VARIETY_UNION;
-		} else if (typeDecl->subtypes->type ==
+		    item->baseType = xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYSIMPLETYPE);
+		    item->flags |= XML_SCHEMAS_TYPE_VARIETY_UNION;
+		} else if (item->subtypes->type ==
 		    XML_SCHEMA_TYPE_RESTRICTION) {
 		    xmlSchemaFacetLinkPtr facet, cur, last = NULL;
 		    		    	    		   
@@ -11341,16 +11806,16 @@
 		    * If the <restriction> alternative is chosen, then the 
 		    * {variety} of the {base type definition}.
 		    */	
-		    if (typeDecl->baseType != NULL) {
-			if (typeDecl->baseType->flags & 
+		    if (item->baseType != NULL) {
+			if (item->baseType->flags & 
 			    XML_SCHEMAS_TYPE_VARIETY_ATOMIC)
-			    typeDecl->flags |= XML_SCHEMAS_TYPE_VARIETY_ATOMIC;
-			else if (typeDecl->baseType->flags & 
+			    item->flags |= XML_SCHEMAS_TYPE_VARIETY_ATOMIC;
+			else if (item->baseType->flags & 
 			    XML_SCHEMAS_TYPE_VARIETY_LIST)
-			    typeDecl->flags |= XML_SCHEMAS_TYPE_VARIETY_LIST;
-			else if (typeDecl->baseType->flags & 
+			    item->flags |= XML_SCHEMAS_TYPE_VARIETY_LIST;
+			else if (item->baseType->flags & 
 			    XML_SCHEMAS_TYPE_VARIETY_UNION)
-			    typeDecl->flags |= XML_SCHEMAS_TYPE_VARIETY_UNION;		    		    		   
+			    item->flags |= XML_SCHEMAS_TYPE_VARIETY_UNION;		    		    		   
 			/*
 			* Schema Component Constraint: Simple Type Restriction 
 			* (Facets)
@@ -11365,12 +11830,12 @@
 			* facets, for which multiple occurrences with distinct values 
 			* are allowed.
 			*/
-			if (typeDecl->baseType->facetSet != NULL) {
-			    last = typeDecl->facetSet;
+			if (item->baseType->facetSet != NULL) {
+			    last = item->facetSet;
 			    if (last != NULL)
 				while (last->next != NULL)
 				    last = last->next;
-				cur = typeDecl->baseType->facetSet;
+				cur = item->baseType->facetSet;
 				for (; cur != NULL; cur = cur->next) {
 				    /* 
 				    * Base patterns won't be add here:
@@ -11383,12 +11848,12 @@
 					XML_SCHEMA_FACET_PATTERN) 
 					continue;
 				    facet = NULL;
-				    if ((typeDecl->facetSet != NULL) &&
+				    if ((item->facetSet != NULL) &&
 					(cur->facet->type != 
 					XML_SCHEMA_FACET_PATTERN) &&
 					(cur->facet->type != 
 					XML_SCHEMA_FACET_ENUMERATION)) {				
-					facet = typeDecl->facetSet;
+					facet = item->facetSet;
 					do {
 					    if (cur->facet->type == 
 						facet->facet->type) 
@@ -11407,7 +11872,7 @@
 					facet->facet = cur->facet;
 					facet->next = NULL;
 					if (last == NULL)
-					    typeDecl->facetSet = facet;		    
+					    item->facetSet = facet;		    
 					else 
 					    last->next = facet;
 					last = facet;				
@@ -11419,13 +11884,13 @@
 		/*
 		* Check constraints.
 		*/
-		xmlSchemaCheckSRCSimpleType(ctxt, typeDecl);
+		xmlSchemaCheckSRCSimpleType(ctxt, item);
 		ctxt->ctxtType = ctxtType;
 		break;
             case XML_SCHEMA_TYPE_SEQUENCE:            
             case XML_SCHEMA_TYPE_ALL:
             case XML_SCHEMA_TYPE_CHOICE:
-                typeDecl->contentType = XML_SCHEMA_CONTENT_ELEMENTS;
+                item->contentType = XML_SCHEMA_CONTENT_ELEMENTS;
                 break;
 	    case XML_SCHEMA_TYPE_GROUP:
 		/*
@@ -11433,12 +11898,12 @@
 		*/
 		break;
             case XML_SCHEMA_TYPE_LIST: 
-		xmlSchemaParseListRefFixup(typeDecl, ctxt);
-		typeDecl->contentType = XML_SCHEMA_CONTENT_SIMPLE;
+		xmlSchemaParseListRefFixup(item, ctxt);
+		item->contentType = XML_SCHEMA_CONTENT_SIMPLE;
 		break;
             case XML_SCHEMA_TYPE_UNION:		
-		xmlSchemaParseUnionRefCheck(typeDecl, ctxt);
-		typeDecl->contentType = XML_SCHEMA_CONTENT_SIMPLE;
+		xmlSchemaParseUnionRefCheck(item, ctxt);
+		item->contentType = XML_SCHEMA_CONTENT_SIMPLE;
 		break;
             case XML_SCHEMA_TYPE_BASIC:
             case XML_SCHEMA_TYPE_ANY:
@@ -11461,22 +11926,22 @@
             case XML_SCHEMA_FACET_LENGTH:
             case XML_SCHEMA_FACET_MAXLENGTH:
             case XML_SCHEMA_FACET_MINLENGTH:
-                typeDecl->contentType = XML_SCHEMA_CONTENT_SIMPLE;
-		if (typeDecl->subtypes != NULL)
-		    xmlSchemaTypeFixup(typeDecl->subtypes, ctxt, NULL);
+                item->contentType = XML_SCHEMA_CONTENT_SIMPLE;
+		if (item->subtypes != NULL)
+		    xmlSchemaTypeFixup(item->subtypes, ctxt, NULL);
                 break;
         }
     }
 #ifdef DEBUG_TYPE
-    if (typeDecl->node != NULL) {
+    if (item->node != NULL) {
         xmlGenericError(xmlGenericErrorContext,
                         "Type of %s : %s:%d :", name,
-                        typeDecl->node->doc->URL,
-                        xmlGetLineNo(typeDecl->node));
+                        item->node->doc->URL,
+                        xmlGetLineNo(item->node));
     } else {
         xmlGenericError(xmlGenericErrorContext, "Type of %s :", name);
     }
-    switch (typeDecl->contentType) {
+    switch (item->contentType) {
         case XML_SCHEMA_CONTENT_SIMPLE:
             xmlGenericError(xmlGenericErrorContext, "simple\n");
             break;
@@ -11586,8 +12051,17 @@
 			NULL, NULL);
                     return (-1);	
 		}
-		vctxt->type = base;		
-		ret = xmlSchemaValidateSimpleTypeValue(vctxt, facet->value, 0, 1, 1);
+		vctxt->node = facet->node;
+		vctxt->cur = NULL;
+		/*
+		* NOTE: This call does not check the content nodes, 
+		* since they are not available:
+		* facet->node is just the node holding the facet 
+		* definition, *not* the attribute holding the *value* 
+		* of the facet.
+		*/
+		ret = xmlSchemaValidateSimpleTypeValue(vctxt, base, 
+		    facet->value, 0, 1, 1, 0);
 		facet->val = vctxt->value;
 		vctxt->value = NULL;		
                 if (ret > 0) {
@@ -12007,14 +12481,18 @@
 
 	type = xmlSchemaGetType(ctxt->schema, attrDecl->typeName,
 	    attrDecl->typeNs);
-	if (type == NULL) {
+	if ((type == NULL) || 
+	    ((type->type != XML_SCHEMA_TYPE_SIMPLE) &&
+	     (type->type != XML_SCHEMA_TYPE_BASIC)) ||
+	    ((type->type == XML_SCHEMA_TYPE_BASIC) &&
+	     (type->builtInType == XML_SCHEMAS_ANYTYPE))) {
 	    xmlSchemaPResCompAttrErr(ctxt,
 		XML_SCHEMAP_SRC_RESOLVE,
 		NULL, (xmlSchemaTypePtr) attrDecl, attrDecl->node,
 		"type", attrDecl->typeName, attrDecl->typeNs, 
-		XML_SCHEMA_TYPE_BASIC, "type definition");
-	}
-        attrDecl->subtypes = type;
+		XML_SCHEMA_TYPE_SIMPLE, NULL);
+	} else
+	    attrDecl->subtypes = type;
     } else if (attrDecl->ref != NULL) {
         xmlSchemaAttributePtr ref;
 
@@ -12059,6 +12537,11 @@
     int nberrors;
     int preserve = 0;
 
+    /*
+    * This one is used if the schema to be parsed was specified via 
+    * the API; i.e. not automatically by the validated instance document.
+    */
+
     xmlSchemaInitTypes();
 
     if (ctxt == NULL)
@@ -12160,7 +12643,7 @@
     * Then fixup all model group definitions.
     */    
     xmlHashScan(ret->groupDecl, (xmlHashScanner) xmlSchemaGroupDefFixup, ctxt);
-
+    
     /*
      * Then fixup all types properties
      */    
@@ -12178,11 +12661,10 @@
     xmlHashScan(ret->groupDecl, (xmlHashScanner) 
 	xmlSchemaCheckGroupDefCircular, ctxt);
 
-
     /*
-     * Then build the content model for all elements
+     * Then build the content model for all complex types
      */
-    xmlHashScan(ret->elemDecl,
+    xmlHashScan(ret->typeDecl,
                 (xmlHashScanner) xmlSchemaBuildContentModel, ctxt);
 
     /*
@@ -12409,6 +12891,7 @@
 				int fireErrors)
 {
     int ret = 0;
+    xmlNodePtr node;
     xmlSchemaTypePtr  biType; /* The build-in type. */
     xmlSchemaTypePtr tmpType;
     xmlSchemaFacetLinkPtr facetLink;
@@ -12421,6 +12904,7 @@
     printf("  fireErrors: %d\n", fireErrors);
 #endif
         
+    node = ctxt->node;
     /*
     * NOTE: Do not jump away, if the facetSet of the given type is
     * empty: until now, "pattern" facets of the *base types* need to
@@ -12430,7 +12914,7 @@
     while ((biType != NULL) && (biType->type != XML_SCHEMA_TYPE_BASIC))
 	biType = biType->baseType;
     if (biType == NULL) {
-	xmlSchemaVErr(ctxt, ctxt->cur, XML_SCHEMAV_INTERNAL,		    
+	xmlSchemaVErr(ctxt, node, XML_SCHEMAV_INTERNAL,		    
 	    "Internal error: xmlSchemaValidateFacetsInternal, "
 	    "the base type axis of the given type '%s' does not resolve to "
 	    "a built-in type.\n",
@@ -12467,13 +12951,13 @@
 			ctxt->value);
 	    }
 	    if (ret < 0) {
-		xmlSchemaVErr(ctxt, ctxt->cur, XML_SCHEMAV_INTERNAL,
+		xmlSchemaVErr(ctxt, node, XML_SCHEMAV_INTERNAL,
 		    "Internal error: xmlSchemaValidateFacetsInternal, "
 		    "validating facet of type '%s'.\n",
 		    type->name, NULL);
 		break;
 	    } else if ((ret > 0) && (fireErrors)) {
-		xmlSchemaVFacetErr(ctxt, ret, ctxt->cur, value, len,
+		xmlSchemaVFacetErr(ctxt, ret, node, value, len,
 		    type, facet, NULL, NULL, NULL, NULL);
 	    }
 
@@ -12497,10 +12981,10 @@
 	    if (retFacet > 0) {
 		ret = XML_SCHEMAV_CVC_ENUMERATION_VALID;
 		if (fireErrors)
-		    xmlSchemaVFacetErr(ctxt, ret, ctxt->cur,
+		    xmlSchemaVFacetErr(ctxt, ret, node,
 			value, 0, type, NULL, NULL, NULL, NULL, NULL);
 	    } else if (retFacet < 0) {
-		xmlSchemaVErr(ctxt, ctxt->cur, XML_SCHEMAV_INTERNAL,
+		xmlSchemaVErr(ctxt, node, XML_SCHEMAV_INTERNAL,
 		    "Internal error: xmlSchemaValidateFacetsInternal, "
 		    "validating facet of type '%s'.\n",
 		    BAD_CAST "enumeration", NULL);
@@ -12519,14 +13003,21 @@
 	do {
 	    retFacet = 0;
 	    for (facetLink = tmpType->facetSet; facetLink != NULL; 
-	    facetLink = facetLink->next) {
+		facetLink = facetLink->next) {
 		if (facetLink->facet->type != XML_SCHEMA_FACET_PATTERN)
 		    continue;
 		retFacet = xmlSchemaValidateFacet(biType, facetLink->facet, 
 		    value, ctxt->value);
-		if (retFacet <= 0)
+		if (retFacet == 0) 
 		    break;
-		else
+		else if (retFacet < 0) {
+		    xmlSchemaVErr(ctxt, node, XML_SCHEMAV_INTERNAL,
+			"Internal error: xmlSchemaValidateFacetsInternal, "
+			"validating 'pattern' facet '%s' of type '%s'.\n",
+			facetLink->facet->value, tmpType->name);
+		    ret = -1;
+		    break;
+		} else
 		    /* Save the last non-validating facet. */
 		    facet = facetLink->facet;
 	    }
@@ -12534,16 +13025,10 @@
 		break;		    
 	    tmpType = tmpType->baseType;
 	} while ((tmpType != NULL) && (tmpType->type != XML_SCHEMA_TYPE_BASIC));
-	if (retFacet < 0) {
-	    xmlSchemaVErr(ctxt, ctxt->cur, XML_SCHEMAV_INTERNAL,
-		"Internal error: xmlSchemaValidateSimpleTypeValue, "
-		"validating 'pattern' facets of type '%s'.\n",
-		tmpType->name, NULL);
-	    ret = -1;
-	} else if (retFacet > 0) {
+	if (retFacet > 0) {
 	    ret = XML_SCHEMAV_CVC_PATTERN_VALID;
 	    if (fireErrors) {
-		xmlSchemaVFacetErr(ctxt, ret, ctxt->cur, value, 0, type, facet, 
+		xmlSchemaVFacetErr(ctxt, ret, node, value, 0, type, facet, 
 		    NULL, NULL, NULL, NULL);
 	    }
 	}
@@ -12565,15 +13050,11 @@
  * 									*
  ************************************************************************/
 
-static int xmlSchemaValidateContent(xmlSchemaValidCtxtPtr ctxt,
-                                    xmlNodePtr node);
 static int xmlSchemaValidateAttributes(xmlSchemaValidCtxtPtr ctxt,
                                        xmlNodePtr elem,
                                        xmlSchemaTypePtr type);
-static int xmlSchemaValidateType(xmlSchemaValidCtxtPtr ctxt,
-                                 xmlNodePtr elem,
-                                 xmlSchemaElementPtr elemDecl,
-                                 xmlSchemaTypePtr type);
+static int xmlSchemaValidateElementByType(xmlSchemaValidCtxtPtr ctxt,                                
+					  xmlSchemaTypePtr type);
 
 
 /**
@@ -12664,6 +13145,330 @@
 }
 #endif
 
+static void
+xmlSchemaPostSchemaAssembleFixup(xmlSchemaParserCtxtPtr ctxt)
+{
+    int i, nbItems;
+    xmlSchemaTypePtr item, *items;
+
+
+    /*
+    * During the Assemble of the schema ctxt->curItems has
+    * been filled with the relevant new items. Fix those up.
+    */
+    nbItems = ctxt->assemble->nbItems;
+    items = (xmlSchemaTypePtr *) ctxt->assemble->items;
+    
+    for (i = 0; i < nbItems; i++) {
+	item = items[i];
+	switch (item->type) {
+	    case XML_SCHEMA_TYPE_ATTRIBUTE:
+		xmlSchemaAttrFixup((xmlSchemaAttributePtr) item, ctxt, NULL);
+		break;
+	    case XML_SCHEMA_TYPE_ELEMENT:
+		xmlSchemaRefFixupCallback((xmlSchemaElementPtr) item, ctxt, 
+		    NULL, NULL, NULL);
+		break;
+	    case XML_SCHEMA_TYPE_ATTRIBUTEGROUP:
+		xmlSchemaAttrGrpFixup((xmlSchemaAttributeGroupPtr) item, 
+		    ctxt, NULL);
+		break;
+	    case XML_SCHEMA_TYPE_GROUP:
+		xmlSchemaGroupDefFixup(item, ctxt, NULL);            
+	    default:
+		break;
+	}
+    }
+    /*
+    * Circularity checks.
+    */
+    for (i = 0; i < nbItems; i++) {
+	item = items[i];
+	switch (item->type) {	    
+	    case XML_SCHEMA_TYPE_GROUP:
+		xmlSchemaCheckGroupDefCircular(item, ctxt, NULL);
+		break;
+	    case XML_SCHEMA_TYPE_ATTRIBUTEGROUP:
+		xmlSchemaCheckAttributeGroupCircular(
+		    (xmlSchemaAttributeGroupPtr) item, ctxt, NULL);
+		break;
+	    default:
+		break;
+	}
+    }
+    /*
+    * Fixup for all other item. 
+    * TODO: Hmm, not sure if starting from complex/simple types,
+    * all subsequent items will be reached.
+    */
+    for (i = 0; i < nbItems; i++) {
+	item = items[i];
+	switch (item->type) {	    
+            case XML_SCHEMA_TYPE_SIMPLE:
+	    case XML_SCHEMA_TYPE_COMPLEX:
+		xmlSchemaTypeFixup(item, ctxt, NULL);
+		break;
+	    default:
+		break;
+	}
+    }
+    /*
+    * Check facet values. Note that facets are
+    * hold by complex and simple type components only.
+    */
+    for (i = 0; i < nbItems; i++) {
+	item = items[i];
+	switch (item->type) {	 
+	    case XML_SCHEMA_TYPE_SIMPLE:
+	    case XML_SCHEMA_TYPE_COMPLEX:
+		xmlSchemaCheckDefaults(item, ctxt, NULL);
+		break;
+	    default:
+		break;
+	}
+    }
+    /*
+    * Build the content model for complex types.
+    */
+    for (i = 0; i < nbItems; i++) {
+	item = items[i];
+	switch (item->type) {	    
+	    case XML_SCHEMA_TYPE_COMPLEX:
+		xmlSchemaBuildContentModel(item, ctxt, NULL);
+		break;
+	    default:
+		break;
+	}
+    }        
+}
+
+/**
+ * xmlSchemaAssembleByLocation:
+ * @pctxt:  a schema parser context
+ * @vctxt:  a schema validation context
+ * @schema: the existing schema
+ * @node: the node that fired the assembling
+ * @nsName: the namespace name of the new schema
+ * @location: the location of the schema
+ *
+ * Expands an existing schema by an additional schema.
+ *
+ * Returns 0 if the new schema is correct, a positive error code
+ * number otherwise and -1 in case of an internal or API error.
+ */
+static int
+xmlSchemaAssembleByLocation(xmlSchemaParserCtxtPtr pctxt, 
+			  xmlSchemaValidCtxtPtr vctxt,			    
+			  xmlSchemaPtr schema,
+			  xmlNodePtr node,
+			  const xmlChar *nsName,
+			  const xmlChar *location)
+{
+    const xmlChar *targetNs, *oldtns; 
+    xmlDocPtr doc, olddoc;
+    int oldflags, ret = 0, reuseCtxt;
+    xmlNodePtr docElem;
+    /*
+    * This should be used:
+    * 1. on <import>(s)
+    * 2. if requested by the validated instance 
+    * 3. if requested via the API
+    */
+    if ((pctxt == NULL) && (vctxt == NULL))
+	return (-1);
+    /*
+    * Create a temporary parser context.
+    * TODO: what to set exaclty for the URL argument here? 
+    */
+    if (pctxt == NULL) {
+	reuseCtxt = 0;
+	pctxt = xmlSchemaNewParserCtxtUseDict((const char *) location, schema->dict);
+	if (pctxt == NULL) {
+	    xmlSchemaVErrMemory(vctxt, 
+		"xmlSchemaAssembleByLocation, allocating new parser "
+		"content for dynamic construction of schemata", NULL);
+	    return (-1);		
+	}
+	pctxt->error = vctxt->error;
+	pctxt->warning = vctxt->warning;
+    } else
+	reuseCtxt = 1;        
+    /*
+    * Acquire the schema document.
+    */
+    ret = xmlSchemaAcquireSchemaDoc(pctxt, schema, node,
+	nsName, location, &doc, &targetNs, 0);
+    if (ret != 0) {
+	if (doc != NULL)
+	    xmlFreeDoc(doc);
+    } else if (doc != NULL) {
+	docElem = xmlDocGetRootElement(doc);
+	/*
+	* Save and reset the context & schema.
+	*/
+	oldflags = schema->flags;
+	oldtns = schema->targetNamespace;
+	olddoc = schema->doc;
+	
+	xmlSchemaClearSchemaDefaults(schema);
+	schema->targetNamespace = targetNs;
+	/* schema->nbCurItems = 0; */
+	pctxt->schema = schema;
+	if (pctxt->assemble == NULL) {
+	    pctxt->assemble = xmlSchemaNewAssemble();
+	     xmlSchemaVErrMemory(vctxt, 
+		"Memory error: xmlSchemaAssembleByLocation, "
+		"allocating assemble info", NULL);
+	    return (-1);
+	}
+	pctxt->ctxtType = NULL;
+	pctxt->parentItem = NULL;
+	
+	xmlSchemaParseSchemaDefaults(pctxt, pctxt->schema, docElem);		
+	xmlSchemaParseSchemaTopLevel(pctxt, pctxt->schema, docElem->children);
+	xmlSchemaPostSchemaAssembleFixup(pctxt);
+	/*
+	* Free the list of assembled components.
+	*/
+	xmlFree(pctxt->assemble->items);
+	/*
+	* Restore the context & schema.
+	*/
+	schema->flags = oldflags;
+	schema->targetNamespace = oldtns;
+	schema->doc = olddoc;
+	ret = pctxt->err;
+    }     
+    if (reuseCtxt == 0) {
+	pctxt->dict = NULL;	
+	xmlSchemaFreeParserCtxt(pctxt);
+    }
+    return (ret);
+}
+
+/**
+ * xmlSchemaAssembleByXSIAttr:
+ * @vctxt:  a schema validation context
+ * @xsiAttr: an xsi attribute
+ * @noNamespace: whether a schema with no target namespace is exptected
+ *
+ * Expands an existing schema by an additional schema using
+ * the xsi:schemaLocation or xsi:noNamespaceSchemaLocation attribute
+ * of an instance. If xsi:noNamespaceSchemaLocation is used, @noNamespace
+ * must be set to 1.
+ *
+ * Returns 0 if the new schema is correct, a positive error code
+ * number otherwise and -1 in case of an internal or API error.
+ */
+static int
+xmlSchemaAssembleByXSIAttr(xmlSchemaValidCtxtPtr vctxt,
+			 xmlAttrPtr xsiAttr,
+			 int noNamespace)
+{
+    xmlChar *value;
+    const xmlChar *cur, *end;
+    const xmlChar *nsname = NULL, *location;
+    int count = 0;
+    int ret = 0;
+    
+    if (xsiAttr == NULL) {
+	xmlSchemaVCustomErr(vctxt, XML_SCHEMAV_INTERNAL, 
+	    NULL, NULL,
+	    "Internal error: xmlSchemaAssembleByXSIAttr, "
+	    "bad arguments", NULL);
+	return (-1);
+    }
+    /*
+    * Parse the value; we will assume an even number of values
+    * to be given (this is how Xerces and XSV work).
+    */
+    value = xmlNodeGetContent((xmlNodePtr) xsiAttr);	    
+    cur = value;
+    do {	
+	if (noNamespace != 1) {
+	    /*
+	    * Get the namespace name.
+	    */
+	    while (IS_BLANK_CH(*cur))
+		cur++;
+	    end = cur;
+	    while ((*end != 0) && (!(IS_BLANK_CH(*end))))
+		end++;
+	    if (end == cur)
+		break;
+	    count++;
+	    nsname = xmlDictLookup(vctxt->schema->dict, cur, end - cur);		
+	    cur = end;
+	}
+	/*
+	* Get the URI.
+	*/
+	while (IS_BLANK_CH(*cur))
+	    cur++;
+	end = cur;
+	while ((*end != 0) && (!(IS_BLANK_CH(*end))))
+	    end++;
+	if (end == cur)
+	    break;
+	count++;
+	location = xmlDictLookup(vctxt->schema->dict, cur, end - cur);
+	cur = end;		
+	ret = xmlSchemaAssembleByLocation(NULL, vctxt, vctxt->schema, 
+	    xsiAttr->parent, nsname, location);
+	if (ret == -1) {
+	    xmlSchemaVCustomErr(vctxt, 
+		XML_SCHEMAV_INTERNAL,
+		(xmlNodePtr) xsiAttr, NULL,
+		"Internal error: xmlSchemaAssembleByXSIAttr, "
+		"assembling schemata", NULL);
+	    if (value != NULL)
+		xmlFree(value);
+	    return (-1);
+	}
+    } while (*cur != 0);
+    if (value != NULL)
+	xmlFree(value);
+    return (ret);
+}
+
+/**
+ * xmlSchemaAssembleByXSIElem:
+ * @vctxt:  a schema validation context
+ * @elem: an element node possibly holding xsi attributes
+ * @noNamespace: whether a schema with no target namespace is exptected
+ *
+ * Assembles an existing schema by an additional schema using
+ * the xsi:schemaLocation or xsi:noNamespaceSchemaLocation attributes
+ * of the given @elem.
+ *
+ * Returns 0 if the new schema is correct, a positive error code
+ * number otherwise and -1 in case of an internal or API error.
+ */
+static int
+xmlSchemaAssembleByXSIElem(xmlSchemaValidCtxtPtr vctxt,  
+			 xmlNodePtr elem)
+{    
+    int ret = 0, retNs = 0;
+    xmlAttrPtr attr;
+
+    attr = xmlHasNsProp(elem, BAD_CAST "schemaLocation", xmlSchemaInstanceNs);
+    if (attr != NULL) {
+	retNs = xmlSchemaAssembleByXSIAttr(vctxt, attr, 0);
+	if (retNs == -1)
+	    return (-1);
+    }
+    attr = xmlHasNsProp(elem, BAD_CAST "noNamespaceSchemaLocation", xmlSchemaInstanceNs);
+    if (attr != NULL) {
+	ret = xmlSchemaAssembleByXSIAttr(vctxt, attr, 1);
+	if (ret == -1)
+	    return (-1);
+    }
+    if (retNs != 0)
+	return (retNs);
+    else
+	return (ret);
+}
+
 /**
  * xmlSchemaValidateCallback:
  * @ctxt:  a schema validation context
@@ -12686,12 +13491,66 @@
                     "xmlSchemaValidateCallback: %s, %s, %s\n",
                     name, type->name, node->name);
 #endif
+    /*
+    * @type->type will be XML_SCHEMA_TYPE_ANY or XML_SCHEMA_TYPE_ELEMENT.
+    */
     ctxt->type = type;
-    ctxt->node = node;
-    xmlSchemaValidateContent(ctxt, node);    
+    ctxt->node = node;    
+    ctxt->cur = node->children;
+    /*
+    * Assemble new schemata using xsi.
+    */
+    if (ctxt->options & XML_SCHEMA_VAL_XSI_ASSEMBLE) {
+	int ret;
+	
+	ret = xmlSchemaAssembleByXSIElem(ctxt, ctxt->node);
+	if (ret == -1) {
+	    xmlSchemaVCustomErr(ctxt, 
+		XML_SCHEMAV_INTERNAL,
+		ctxt->node, NULL, 	
+		"Internal error: xmlSchemaValidateElement, "
+		"assembling schema by xsi", NULL);
+	    return;
+	}
+	/*
+	* NOTE: We won't react on schema parser errors here.
+	* TODO: But a warning would be nice.
+	*/
+    }    
+    switch (type->type) {
+	case XML_SCHEMA_TYPE_ELEMENT: {
+	    /*
+	    * NOTE: The build of the content model 
+	    * (xmlSchemaBuildAContentModel) ensures that the element 
+	    * declaration (and not a reference to it) will be given.
+	    */
+	    if (((xmlSchemaElementPtr) ctxt->type)->ref != NULL) {
+		/*
+		* This is paranoid coding ;-)... it should not
+		* happen here any more.
+		*/
+		xmlSchemaVCustomErr(ctxt, 
+		    XML_SCHEMAV_INTERNAL, 
+		    node, NULL,						
+		    "Internal error: xmlSchemaValidateCallback, "
+		    "element declaration 'reference' encountered, "
+		    "but an element declaration was expected", 
+		    NULL);
+		return;
+	    }
+	    xmlSchemaValidateElementByDeclaration(ctxt, 
+		(xmlSchemaElementPtr) type);
+	    break;
+	}
+        case XML_SCHEMA_TYPE_ANY:
+	    xmlSchemaValidateElementByWildcard(ctxt, type);
+            break;
+	default: 
+	    break;
+    }
     ctxt->type = oldtype;
     ctxt->node = oldnode;
-}
+}  
 
 /**
  * xmlSchemaValidateSimpleTypeValue:
@@ -12700,6 +13559,7 @@
  * @fireErrors: shall errors be reported?
  * @applyFacets: shall facets be applied?
  * @normalize: shall the value be normalized?
+ * @checkNodes: shall the content nodes be checked?
  *
  * Validates a value by the given type (user derived or built-in).
  *
@@ -12708,17 +13568,20 @@
  */
 static int
 xmlSchemaValidateSimpleTypeValue(xmlSchemaValidCtxtPtr ctxt, 
-				 const xmlChar *value,
+				 xmlSchemaTypePtr type,
+				 const xmlChar *value,				 
 				 int fireErrors,				 
 				 int applyFacets,
-				 int normalize)
+				 int normalize,
+				 int checkNodes)
 {
-    xmlSchemaTypePtr type;
+    xmlNodePtr node;
     int ret = 0;  
     xmlChar *normValue = NULL;
     int wtsp;       
  
-    type = ctxt->type;
+    node = ctxt->node;
+    /* Save the current whitespace normalization type. */
     wtsp = ctxt->valueWS;
     /*
     * Normalize the value.
@@ -12737,6 +13600,67 @@
 		value = (const xmlChar *) normValue;
 	}		
     }    
+    /*
+    * The nodes of a content must be checked only once,
+    * this is not working since list types will fire this
+    * multiple times.
+    */
+    if ((checkNodes == 1) && (ctxt->cur != NULL)) {
+	xmlNodePtr cur = ctxt->cur;
+
+	do {
+	    switch (cur->type) {
+	    case XML_TEXT_NODE:
+	    case XML_CDATA_SECTION_NODE:
+	    case XML_PI_NODE:
+	    case XML_COMMENT_NODE:
+	    case XML_XINCLUDE_START:
+	    case XML_XINCLUDE_END:
+		break;
+	    case XML_ENTITY_REF_NODE:
+	    case XML_ENTITY_NODE:
+		/* TODO: Scour the entities for illegal nodes. */
+		TODO break;
+	    case XML_ELEMENT_NODE: {
+	    /* NOTE: Changed to an internal error, since the 
+	    * existence of an element node will be already checked in
+	    * xmlSchemaValidateElementBySimpleType and in
+	    * xmlSchemaValidateElementByComplexType.
+		*/
+		xmlSchemaVCustomErr(ctxt, 
+		    XML_SCHEMAV_INTERNAL,
+		    /* XML_SCHEMAS_ERR_INVALIDELEM, */
+		    node, type,
+		    "Element '%s' found in simple type content", 
+		    cur->name);
+		return (XML_SCHEMAV_INTERNAL);
+				   }
+	    case XML_ATTRIBUTE_NODE:
+	    case XML_DOCUMENT_NODE:
+	    case XML_DOCUMENT_TYPE_NODE:
+	    case XML_DOCUMENT_FRAG_NODE:
+	    case XML_NOTATION_NODE:
+	    case XML_HTML_DOCUMENT_NODE:
+	    case XML_DTD_NODE:
+	    case XML_ELEMENT_DECL:
+	    case XML_ATTRIBUTE_DECL:
+	    case XML_ENTITY_DECL:
+	    case XML_NAMESPACE_DECL:
+#ifdef LIBXML_DOCB_ENABLED
+	    case XML_DOCB_DOCUMENT_NODE: 
+#endif		    		    		    
+		xmlSchemaVCustomErr(ctxt, 
+		    XML_SCHEMAV_INTERNAL,
+		    /* XML_SCHEMAS_ERR_INVALIDELEM, */
+		    node, NULL,
+		    "Node of unexpected type found in simple type content",
+		    NULL);
+		return (XML_SCHEMAV_INTERNAL);
+	    }
+	    cur = cur->next;
+	} while (cur != NULL);
+    }
+
     if (type->type == XML_SCHEMA_TYPE_COMPLEX) {
 	xmlSchemaTypePtr base, anyType;
 
@@ -12749,11 +13673,9 @@
 	    (base != anyType)) {
 	    base = base->baseType;
 	}
-	ctxt->type = base;
-	ret = xmlSchemaValidateSimpleTypeValue(ctxt, value, 1, 0, 1);
-	ctxt->type = type;
+	ret = xmlSchemaValidateSimpleTypeValue(ctxt, base, value, 1, 0, 1, 0);
 	if (ret < 0) {
-	    xmlSchemaVErr(ctxt, ctxt->cur, XML_SCHEMAV_INTERNAL,
+	    xmlSchemaVErr(ctxt, node, XML_SCHEMAV_INTERNAL,
 		"Internal error: xmlSchemaValidateSimpleTypeValue, "
 		"validating complex type '%s'\n",
 		type->name, NULL);
@@ -12771,90 +13693,35 @@
 	    ret = xmlSchemaValidateFacetsInternal(ctxt, type, 
 		value, 0, fireErrors);
 	    if (ret < 0) {
-		xmlSchemaVErr(ctxt, ctxt->cur, XML_SCHEMAV_INTERNAL,
+		xmlSchemaVErr(ctxt, node, XML_SCHEMAV_INTERNAL,
 		    "Internal error: xmlSchemaValidateSimpleTypeValue, "
 		    "validating facets of complex type '%s'\n",
 		    type->name, NULL);
 	    } else if (ret > 0) {
 		ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_1;
-		/*
-		 Disabled, since the facet validation already reports errors.
 		if (fireErrors) 
 		    xmlSchemaVSimpleTypeErr(ctxt, ret, ctxt->cur, value, type);
-		*/
 	    }	
 	}	
     } else if (type->type == XML_SCHEMA_TYPE_BASIC) {
-	xmlNodePtr child;
 
 	if (ctxt->value != NULL) {
 	    xmlSchemaFreeValue(ctxt->value);
 	    ctxt->value = NULL;
 	}
-	child = ctxt->node;
-	while (child != NULL) {
-	    switch (child->type) {
-		case XML_TEXT_NODE:
-		case XML_CDATA_SECTION_NODE:
-		case XML_PI_NODE:
-		case XML_COMMENT_NODE:
-		case XML_XINCLUDE_START:
-		case XML_XINCLUDE_END:
-		    break;
-		case XML_ENTITY_REF_NODE:
-		case XML_ENTITY_NODE:
-		    /* TODO: Scour the entities for illegal nodes. */
-		    TODO break;
-		case XML_ELEMENT_NODE: {
-		    /* NOTE: Changed to an internal error, since the 
-		    * existence of an element node will be already checked in
-		    * xmlSchemaValidateSimpleTypeElement and in
-		    * xmlSchemaValidateComplexType.
-		    */
-		    xmlSchemaVCustomErr(ctxt, 
-			XML_SCHEMAV_INTERNAL,
-			/* XML_SCHEMAS_ERR_INVALIDELEM, */
-			ctxt->cur, type,
-			"Element found in content", NULL);
-		    return (XML_SCHEMAV_INTERNAL);
-				       }
-		case XML_ATTRIBUTE_NODE:
-		case XML_DOCUMENT_NODE:
-		case XML_DOCUMENT_TYPE_NODE:
-		case XML_DOCUMENT_FRAG_NODE:
-		case XML_NOTATION_NODE:
-		case XML_HTML_DOCUMENT_NODE:
-		case XML_DTD_NODE:
-		case XML_ELEMENT_DECL:
-		case XML_ATTRIBUTE_DECL:
-		case XML_ENTITY_DECL:
-		case XML_NAMESPACE_DECL:
-#ifdef LIBXML_DOCB_ENABLED
-		case XML_DOCB_DOCUMENT_NODE: 
-#endif		
-		{		    		    
-		    xmlSchemaVCustomErr(ctxt, 
-			XML_SCHEMAV_INTERNAL,
-			/* XML_SCHEMAS_ERR_INVALIDELEM, */
-			ctxt->cur, NULL,
-			"Node of unexpected type found in content", 
-			NULL);
-		    return (XML_SCHEMAV_INTERNAL);
-		}
-	    }
-	    child = child->next;
-	    
-	}	
-	ret = xmlSchemaValPredefTypeNodeNoNorm(type, value, &(ctxt->value), ctxt->cur);
+	/*
+	* STREAM-READ-CHILDREN.
+	*/	    		
+	ret = xmlSchemaValPredefTypeNodeNoNorm(type, value, &(ctxt->value), node);
 	if (ret > 0) {	    
 	    if (type->flags & XML_SCHEMAS_TYPE_VARIETY_LIST) 
 		ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_2;
 	    else
 		ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_1;	    
 	    if (fireErrors)
-		xmlSchemaVSimpleTypeErr(ctxt, ret, ctxt->cur, value, type);
+		xmlSchemaVSimpleTypeErr(ctxt, ret, node, value, type);
 	} else if (ret < 0) {
-	    xmlSchemaVErr(ctxt, ctxt->cur, XML_SCHEMAV_INTERNAL,
+	    xmlSchemaVErr(ctxt, node, XML_SCHEMAV_INTERNAL,
 		"Internal error: xmlSchemaValidateSimpleTypeValue, "
 		"validating built-in type '%s'\n", type->name, NULL);
 	}
@@ -12862,18 +13729,16 @@
 	/* 1.2.1 if {variety} is ·atomic· then the string must ·match· 
 	* a literal in the ·lexical space· of {base type definition} 
 	*/	
-	ctxt->type = type->baseType;
-	ret = xmlSchemaValidateSimpleTypeValue(ctxt, value, 0, 0, 0);
-	ctxt->type = type;
+	ret = xmlSchemaValidateSimpleTypeValue(ctxt, type->baseType, value, 0, 0, 0, 0);
 	if (ret < 0) {
-	    xmlSchemaVErr(ctxt, ctxt->cur, XML_SCHEMAV_INTERNAL,
+	    xmlSchemaVErr(ctxt, node, XML_SCHEMAV_INTERNAL,
 		"Internal error: xmlSchemaValidateSimpleTypeValue, "
 		"validating atomic simple type '%s'\n",
 		type->name, NULL);
 	} else if (ret > 0) {	    
 	    ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_1;
 	    if (fireErrors)
-		xmlSchemaVSimpleTypeErr(ctxt, ret, ctxt->cur, value, type);	
+		xmlSchemaVSimpleTypeErr(ctxt, ret, node, value, type);	
 	} else if ((applyFacets) && (type->facetSet != NULL)) {
 	    /* 
 	    * Check facets.
@@ -12881,7 +13746,7 @@
 	    ret = xmlSchemaValidateFacetsInternal(ctxt, type, 
 		value, 0, fireErrors);
 	    if (ret < 0) {
-		xmlSchemaVErr(ctxt, ctxt->cur, XML_SCHEMAV_INTERNAL,
+		xmlSchemaVErr(ctxt, node, XML_SCHEMAV_INTERNAL,
 		    "Internal error: xmlSchemaValidateSimpleTypeValue, "
 		    "validating facets of atomic simple type '%s'\n",
 		    type->name, NULL);
@@ -12918,12 +13783,10 @@
 		break;
 	    tmp = xmlStrndup(cur, end - cur);
 	    len++;
-	    ctxt->type = tmpType;
-	    ret = xmlSchemaValidateSimpleTypeValue(ctxt, tmp, 0, 1, 0);
-	    ctxt->type = type;
+	    ret = xmlSchemaValidateSimpleTypeValue(ctxt, tmpType, tmp, 0, 1, 0, 0);
 	    xmlFree(tmp);
 	    if (ret < 0) {
-		xmlSchemaVErr(ctxt, ctxt->cur, XML_SCHEMAV_INTERNAL,
+		xmlSchemaVErr(ctxt, node, XML_SCHEMAV_INTERNAL,
 		    "Internal error: xmlSchemaValidateSimpleTypeValue, "
 		    "validating an item of list simple type '%s'\n",
 		    type->name, NULL);	
@@ -12931,7 +13794,7 @@
 	    } else if (ret > 0) {
 		ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_2;
 		if (fireErrors)
-		    xmlSchemaVSimpleTypeErr(ctxt, ret, ctxt->cur, value, type);
+		    xmlSchemaVSimpleTypeErr(ctxt, ret, node, value, type);
 		break;
 	    }	
 	    cur = end;
@@ -12940,7 +13803,7 @@
 	* Check facets.
 	*/
 	if (ret < 0) {
-	    xmlSchemaVErr(ctxt, ctxt->cur, XML_SCHEMAV_INTERNAL,
+	    xmlSchemaVErr(ctxt, node, XML_SCHEMAV_INTERNAL,
 		"Internal error: xmlSchemaValidateSimpleTypeValue, "
 		"validating list simple type '%s'\n",
 		type->name, NULL);
@@ -12948,7 +13811,7 @@
 	    ret = xmlSchemaValidateFacetsInternal(ctxt, type, 
 		value, len, fireErrors);
 	    if (ret < 0) {
-		xmlSchemaVErr(ctxt, ctxt->cur, XML_SCHEMAV_INTERNAL,
+		xmlSchemaVErr(ctxt, node, XML_SCHEMAV_INTERNAL,
 		    "Internal error: xmlSchemaValidateSimpleTypeValue, "
 		    "validating facets of list simple type '%s'\n",
 		    type->name, NULL);
@@ -12988,7 +13851,7 @@
 #endif
 	memberLink = xmlSchemaGetUnionSimpleTypeMemberTypes(type);
 	if (memberLink == NULL) {
-	    xmlSchemaVErr(ctxt, ctxt->cur, XML_SCHEMAV_INTERNAL,
+	    xmlSchemaVErr(ctxt, node, XML_SCHEMAV_INTERNAL,
 		"Internal error: xmlSchemaValidateSimpleTypeValue, "
 		"union simple type '%s' has no member types\n",
 		type->name, NULL);
@@ -12996,22 +13859,21 @@
 	} 
 	if (ret == 0) {
 	    while (memberLink != NULL) {
-		ctxt->type = memberLink->type;
-		ret = xmlSchemaValidateSimpleTypeValue(ctxt, value, 0, 1, 1);
+		ret = xmlSchemaValidateSimpleTypeValue(ctxt, memberLink->type, 
+		    value, 0, 1, 1, 0);
 		if ((ret <= 0) || (ret == 0))
 		    break;	    
 		memberLink = memberLink->next;
 	    }     
-	    ctxt->type = type;
 	    if (ret < 0) {
-		xmlSchemaVErr(ctxt, ctxt->cur, XML_SCHEMAV_INTERNAL,
+		xmlSchemaVErr(ctxt, node, XML_SCHEMAV_INTERNAL,
 		    "Internal error: xmlSchemaValidateSimpleTypeValue, "
 		    "validating members of union simple type '%s'\n",
 		    type->name, NULL);
 	    } else if (ret > 0) {
 		ret = XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_3;
 		if (fireErrors)
-		    xmlSchemaVSimpleTypeErr(ctxt, ret, ctxt->cur, value, type);
+		    xmlSchemaVSimpleTypeErr(ctxt, ret, node, value, type);
 	    }
 	}
 	/*
@@ -13025,7 +13887,7 @@
 	    * against which the ·union· is successfully validated. 
 	    */		    
 	    if (normValue != NULL) {
-		xmlSchemaVErr(ctxt, ctxt->cur, XML_SCHEMAV_INTERNAL,
+		xmlSchemaVErr(ctxt, node, XML_SCHEMAV_INTERNAL,
 		    "Internal error: xmlSchemaValidateSimpleTypeValue, "
 		    "the value was already normalized for the union simple "
 		    "type '%s'.\n", type->name, NULL);
@@ -13043,7 +13905,7 @@
 	    ret = xmlSchemaValidateFacetsInternal(ctxt, type, 
 		value, 0, fireErrors);
 	    if (ret < 0) {
-		xmlSchemaVErr(ctxt, ctxt->cur, XML_SCHEMAV_INTERNAL,
+		xmlSchemaVErr(ctxt, node, XML_SCHEMAV_INTERNAL,
 		    "Internal error: xmlSchemaValidateSimpleTypeValue, "
 		    "validating facets of union simple type '%s'\n",
 		    type->name, NULL);
@@ -13056,7 +13918,6 @@
 	    }	
 	}
     }           
-    ctxt->type = type;
     ctxt->valueWS = wtsp;
     if (normValue != NULL)
 	xmlFree(normValue);
@@ -13074,38 +13935,42 @@
  * number otherwise and -1 in case of an internal or API error.
  */
 static int
-xmlSchemaValidateSimpleTypeElement(xmlSchemaValidCtxtPtr ctxt, xmlNodePtr node)
+xmlSchemaValidateElementBySimpleType(xmlSchemaValidCtxtPtr ctxt, 
+				     xmlSchemaTypePtr type)
 {
-    xmlNodePtr child;
-    xmlSchemaTypePtr type;
+    xmlSchemaTypePtr oldtype;
+    xmlNodePtr node;
     xmlAttrPtr attr;
-    int ret = 0;
-    xmlChar *value;
     xmlNodePtr cur;
-    
-
-    child = ctxt->node;
-    type = ctxt->type;
-
+    int ret = 0, retval = 0;
+        
     if ((ctxt == NULL) || (type == NULL)) {
-        xmlSchemaVErr(ctxt, node, XML_SCHEMAV_INTERNAL,
-		      "Internal error: xmlSchemaValidateSimpleTypeElement %s\n",
-		      node->name, NULL);
-        return (-1);
+        xmlSchemaVCustomErr(ctxt, XML_SCHEMAV_INTERNAL, NULL, NULL,
+	    "Internal error: xmlSchemaValidateElementBySimpleType, "
+	    "bad arguments", NULL);
+        return (-1);    
     }
 
+    oldtype = ctxt->type;
+    node = ctxt->node;
     /* 
     * cvc-type: 3.1.2 The element information item must have no element 
     * information item [children].
     */   
-    cur = child;
+    /*
+    * STREAM: Child nodes are processed.
+    */
+    cur = node->children;
     while (cur != NULL) {
+	/*
+	* TODO: Entities, will they produce elements as well?
+	*/
 	if (cur->type == XML_ELEMENT_NODE) {
 	    xmlSchemaVCustomErr(ctxt,
 		XML_SCHEMAV_CVC_TYPE_3_1_2,
 		node, type,		
 		"No element content allowed", NULL);
-	    return (XML_SCHEMAV_CVC_TYPE_3_1_2);
+	    ret = XML_SCHEMAV_CVC_TYPE_3_1_2;
 	}
 	cur = cur->next;
     }
@@ -13116,7 +13981,10 @@
     * The attributes of must be empty, excepting those whose namespace name 
     * is identical to http://www.w3.org/2001/XMLSchema-instance and whose local 
     * name is one of type, nil, schemaLocation or noNamespaceSchemaLocation.
-    */        
+    */   
+    /*
+    * STREAM: Attribute nodes are processed.
+    */
     attr = node->properties;
     while (attr != NULL) {
         if ((attr->ns == NULL) ||
@@ -13127,172 +13995,370 @@
              (!xmlStrEqual
               (attr->name, BAD_CAST "noNamespaceSchemaLocation")))) {
 	    xmlSchemaVIllegalAttrErr(ctxt, 
-		XML_SCHEMAV_CVC_TYPE_3_1_1, attr);						
-            return (ctxt->err);
+		XML_SCHEMAV_CVC_TYPE_3_1_1, attr);
+	    ret = XML_SCHEMAV_CVC_TYPE_3_1_1;
         }
 	attr = attr->next;
     }
+    /*
+    * This will skip validation if the type is 'anySimpleType'.
+    */
     if ((type->type != XML_SCHEMA_TYPE_BASIC) ||
 	(type->builtInType != XML_SCHEMAS_ANYSIMPLETYPE)) {
-	value = xmlNodeGetContent(child);
-	ret = xmlSchemaValidateSimpleTypeValue(ctxt, value, 1, 1, 1);
+	xmlChar *value;	
+
+	value = xmlNodeGetContent(node);
+	/*
+	* NOTE: This call will not check the content nodes, since
+	* this should be checked here already.
+	*/
+	retval = xmlSchemaValidateSimpleTypeValue(ctxt, type, value, 
+	    1, 1, 1, 0);
 	if (value != NULL)
 	    xmlFree(value);
-	ctxt->type = type;
+	if (retval != 0)
+	    ret = retval;
     }
+    ctxt->type = oldtype;
     return (ret);
 }
 
 /**
- * xmlSchemaValidateElementType:
+ * xmlSchemaValQNameAcquire:
+ * @value: the lexical represantation of the QName value
+ * @node: the node to search for the corresponding namespace declaration
+ * @nsName: the resulting namespace name if found
+ *
+ * Checks that a value conforms to the lexical space of the type QName;
+ * if valid, the corresponding namespace name is searched and retured 
+ * as a copy in @nsName. The local name is returned in @localName as
+ * a copy.
+ *
+ * Returns 0 if valid, 1 if not valid by type, 2 if no corresponding 
+ * namespace declaration was found in scope; -1 in case of an internal or 
+ * API error.
+ */
+static int
+xmlSchemaValQNameAcquire(const xmlChar *value, xmlNodePtr node,
+			xmlChar **nsName, xmlChar **localName)
+{
+    int ret;
+    xmlChar *local = NULL;
+
+    if ((nsName == NULL) || (localName == NULL) || (node == NULL))
+	return (-1);  
+    *nsName = NULL;   
+    *localName = NULL;
+    ret = xmlValidateQName(value, 1);
+    if (ret == 0) {
+	xmlChar *prefix;
+	
+	local = xmlSplitQName2(value, &prefix);
+	if (prefix != NULL) {
+	    xmlNsPtr ns;
+	    
+	    ns = xmlSearchNs(node->doc, node, prefix);
+	    if (ns == NULL)
+		ret = 2;
+	    else {
+		*nsName = xmlStrdup(ns->href);
+		*localName = xmlStrdup(local);
+	    }
+	}
+	if (local != NULL)
+	    xmlFree(local);
+	if (prefix != NULL)
+	    xmlFree(prefix);
+    } else
+	return (1);
+    return (ret);
+}
+
+/**
+ * xmlSchemaValidateElementByDeclaration:
  * @ctxt:  a schema validation context
  * @node:  the top node.
  *
  * Validate the content of an element type.
- * Validation Rule: Element Locally Valid (Complex Type)
+ * Validation Rule: Element Locally Valid (Element)
  *
  * Returns 0 if the element is schemas valid, a positive error code
  *     number otherwise and -1 in case of internal or API error.
  */
 static int
-xmlSchemaValidateElementType(xmlSchemaValidCtxtPtr ctxt, xmlNodePtr node)
+xmlSchemaValidateElementByDeclaration(xmlSchemaValidCtxtPtr ctxt,
+				      xmlSchemaElementPtr elemDecl)
 {
-    xmlNodePtr child;
-    xmlRegExecCtxtPtr oldregexp;        /* cont model of the parent */
-    xmlSchemaElementPtr decl;
+    xmlNodePtr elem;
     int ret;
-    xmlSchemaAttrStatePtr attrs = NULL, attrTop = NULL;
+    xmlSchemaTypePtr type = NULL;
+    xmlAttrPtr attr;
+    xmlChar *attrValue; 
+    int nilled = 0;
 
-    /* This one is called by xmlSchemaValidateContent only. */
     /* 
-     * TODO: Look into "xmlSchemaValidateElement" for missing parts, which should
-     * go in here as well.
-     */
+    * This one is called by xmlSchemaValidateElementByWildcardInternal, 
+    * xmlSchemaValidateElementByAnyType and xmlSchemaValidateElement.
+    *
+    * @ctxt->type will be the element's declaration.
+    */
 
-    /* TODO: Is this one called always with an element declaration as the 
-     * context's type?
-     */
-
-    oldregexp = ctxt->regexp;
-
-    child = ctxt->node;
-    decl = (xmlSchemaElementPtr) ctxt->type;
-
-    if ((ctxt == NULL) || (decl == NULL)) {
-        xmlSchemaVErr(ctxt, node, XML_SCHEMAV_INTERNAL,
-		      "Internal error: xmlSchemaValidateElementType\n",
-		      node->name, NULL);
+    if (ctxt == NULL) {
+        xmlSchemaVErr(ctxt, NULL, XML_SCHEMAV_INTERNAL,
+	    "Internal error: xmlSchemaValidateElementByDeclaration, "
+	    "bad arguments.\n",
+	    NULL, NULL);
         return (-1);
     }
+
+    elem = ctxt->node;   
+
+    /*
+    * cvc-elt (3.3.4) : 1
+    */
+    if (elemDecl == NULL) {
+	xmlSchemaVCustomErr(ctxt,
+	    XML_SCHEMAV_CVC_ELT_1, 
+	    elem, NULL,
+	    "No matching declaration available", NULL);
+        return (ctxt->err);
+    }
+    /*
+    * cvc-elt (3.3.4) : 2
+    */
+    if (elemDecl->flags & XML_SCHEMAS_ELEM_ABSTRACT) {
+	xmlSchemaVCustomErr(ctxt,
+	    XML_SCHEMAV_CVC_ELT_2,
+	    elem, NULL, 
+	    "The element declaration is abstract", NULL);
+        return (ctxt->err);
+    }
+     
+    /*
+    * cvc-elt (3.3.4) : 3
+    * Handle 'xsi:nil'.
+    */
+    attr = xmlHasNsProp(elem, BAD_CAST "nil", xmlSchemaInstanceNs);
+    if (attr != NULL) {	
+	attrValue = xmlNodeGetContent((xmlNodePtr) attr);	
+	ctxt->node = (xmlNodePtr) attr;
+	ctxt->cur = attr->children;	
+	ret = xmlSchemaValidateSimpleTypeValue(ctxt, 
+	    xmlSchemaGetBuiltInType(XML_SCHEMAS_BOOLEAN),
+	    BAD_CAST attrValue, 1, 1, 1, 1);
+	ctxt->node = elem;
+	ctxt->type = (xmlSchemaTypePtr) elemDecl;
+	if (ret < 0) {
+	    xmlSchemaVCustomErr(ctxt,
+		XML_SCHEMAV_INTERNAL, 
+		(xmlNodePtr) attr, NULL,
+		"Internal error: xmlSchemaValidateElementByDeclaration, "
+		"validating the attribute 'xsi:nil'", NULL);
+	    if (attrValue != NULL)
+		xmlFree(attrValue);
+	    return (-1);
+	} 
+	if ((elemDecl->flags & XML_SCHEMAS_ELEM_NILLABLE) == 0) {
+	    /* 
+	    * cvc-elt (3.3.4) : 3.1 
+	    */
+	    xmlSchemaVCustomErr(ctxt, 
+		XML_SCHEMAV_CVC_ELT_3_1, 
+		elem, NULL,
+		"The element is not 'nillable'", NULL);	
+	} else {		    
+	    if (xmlStrEqual(BAD_CAST attrValue, BAD_CAST "true") ||
+		xmlStrEqual(BAD_CAST attrValue, BAD_CAST "1")) {
+		nilled = 1;
+		ret = 0;
+		/* 
+		* cvc-elt (3.3.4) : 3.2.1 
+		*/
+		if (xmlSchemaHasElemOrCharContent(elem) == 1) {
+		    xmlSchemaVCustomErr(ctxt, 
+			XML_SCHEMAV_CVC_ELT_3_2_1, 
+			/* XML_SCHEMAS_ERR_NOTEMPTY, */
+			elem, NULL,
+			"The 'nilled' element must have no character or element "
+			"content", NULL);
+		    ret = XML_SCHEMAV_CVC_ELT_3_2_1;
+		}
+		/* 
+		* cvc-elt (3.3.4) : 3.2.2 
+		*/
+		if ((elemDecl->flags & XML_SCHEMAS_ELEM_FIXED) &&
+		    (elemDecl->value != NULL)) {
+		    xmlSchemaVCustomErr(ctxt, XML_SCHEMAV_CVC_ELT_3_2_2, 
+			/* XML_SCHEMAS_ERR_HAVEDEFAULT, */
+			elem, NULL,
+			"There is a fixed value constraint defined for "
+			"the 'nilled' element", NULL);		    
+		    ret = XML_SCHEMAV_CVC_ELT_3_2_2;
+		}
+		
+	    }
+	}
+	if (attrValue != NULL)
+	    xmlFree(attrValue);
+    }
+    
+    /* 
+    * cvc-elt (3.3.4) : 4 
+    * Handle 'xsi:type'.
+    */
+    attr = xmlHasNsProp(elem, BAD_CAST "type",  xmlSchemaInstanceNs);
+    if (attr != NULL) {	
+	xmlChar *nsName = NULL, *local = NULL;
+
+	/*
+	* TODO: We should report a *warning* that the type was overriden
+	* by the instance.
+	*/
+
+	/* 
+	* cvc-elt (3.3.4) : 4.1 
+	*/
+	attrValue = xmlNodeGetContent((xmlNodePtr) attr);
+	ret = xmlSchemaValQNameAcquire(attrValue, attr->parent,	
+	    &nsName, &local);
+	if (ret < 0) {
+	    xmlSchemaVCustomErr(ctxt,
+		XML_SCHEMAV_INTERNAL, 
+		(xmlNodePtr) attr, NULL,
+		"Internal error: xmlSchemaValidateElementByDeclaration, "
+		"validating the attribute 'xsi:type'", NULL);;
+	    FREE_AND_NULL(attrValue)
+	    FREE_AND_NULL(nsName)
+	    FREE_AND_NULL(local)
+	    return (-1);
+	} else if (ret == 1) {
+	    xmlSchemaVSimpleTypeErr(ctxt,
+		XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_1,
+		(xmlNodePtr) attr, attrValue, 
+		xmlSchemaGetBuiltInType(XML_SCHEMAS_QNAME));
+	} else if (ret == 2) {
+	    xmlSchemaVCustomErr(ctxt,
+		XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_1,
+		(xmlNodePtr) attr, 
+		xmlSchemaGetBuiltInType(XML_SCHEMAS_QNAME),
+		"The QName value '%s' has no "
+		"corresponding namespace declaration in scope", 
+		attrValue);	    	    
+	} else {
+	    /*
+	    * cvc-elt (3.3.4) : 4.2 
+	    */
+	    type = xmlSchemaGetType(ctxt->schema, local, nsName);
+	    if (type == NULL) {	  
+		xmlChar *strA = NULL;
+
+		xmlSchemaVCustomErr(ctxt,
+		    XML_SCHEMAV_CVC_ELT_4_2,
+	    	    (xmlNodePtr) attr, 
+		    xmlSchemaGetBuiltInType(XML_SCHEMAS_QNAME),
+		    "The value %s does not resolve to a type "
+		    "definition", 
+		    xmlSchemaFormatNsUriLocal(&strA, nsName, local));
+		FREE_AND_NULL(strA);    
+	    } else {
+		TODO
+		/*
+		* TODO: cvc-elt (3.3.4) : 4.3 (Type Derivation OK)
+		*/		
+	    }
+	}
+	FREE_AND_NULL(attrValue)
+	FREE_AND_NULL(nsName)
+	FREE_AND_NULL(local)
+    } else {
+	type = elemDecl->subtypes;
+	/* TODO: Change the handling of missing types according to
+	* the spec.
+	*/
+	if (type == NULL) {
+	    xmlSchemaVCustomErr(ctxt,
+		XML_SCHEMAV_INTERNAL,
+		/* XML_SCHEMAS_ERR_NOTYPE */
+		elem, NULL,
+		"The element declaration has no type assigned", NULL);        
+	    return (-1);
+	}
+    }
+      
     /*
     * TODO: Since this should be already checked by the content model automaton,
     * and we want to get rid of the XML_SCHEMAS_ERR... types, the error code
     * has been changed to XML_SCHEMAV_INTERNAL.
     */
+    /*
     if (child == NULL) {
         if (decl->minOccurs > 0) {
             xmlSchemaVErr(ctxt, node, XML_SCHEMAV_INTERNAL,
-		/* XML_SCHEMAS_ERR_MISSING, */
+		 XML_SCHEMAS_ERR_MISSING, 
 		"Element %s: missing child %s\n",
 		node->name, decl->name);
         }
         return (ctxt->err);
-    }    
-
+    } 
+    */
     /*
      * Verify the element matches
      * TODO, FIXME: Can this still happen here? Isn't this already checked
-     * by the content model automaton?
-     */    
+     * by the content model automaton?         
     if (!xmlStrEqual(child->name, decl->name)) {
         xmlSchemaVErr3(ctxt, node, XML_SCHEMAV_INTERNAL,
-	    /* XML_SCHEMAS_ERR_WRONGELEM, */
+	     XML_SCHEMAS_ERR_WRONGELEM, 
 	    "Element %s: missing child %s found %s\n",
 	    node->name, decl->name, child->name);
         return (ctxt->err);
     }
+    */
     /*
-     * Verify the attributes
-     */
-    /*
-    * TODO: This "attrTop" thing is not needed any more.
-    */    
-    attrs = ctxt->attr;    
-    attrTop = ctxt->attrTop;    
-    xmlSchemaRegisterAttributes(ctxt, child->properties);     
-    xmlSchemaValidateAttributes(ctxt, child, decl->subtypes);
-    if (ctxt->attr != NULL)
-	xmlSchemaFreeAttributeStates(ctxt->attr);
-    ctxt->attr = attrs;    
-    ctxt->attrTop = attrTop;
-
-    /*
-     * Verify the element content recursively
-     */   
-    oldregexp = ctxt->regexp;
-    /*
-    * FIXME TODO: This one creates a regexp even if no content
-    * model was defined. Somehow ->contModel is always not NULL
-    * for complex types, even if they are empty.
-    */    
-    if (decl->contModel != NULL) {	
-        ctxt->regexp = xmlRegNewExecCtxt(decl->contModel,
-                                         (xmlRegExecCallbacks)
-                                         xmlSchemaValidateCallback, ctxt);
-#ifdef DEBUG_AUTOMATA
-        xmlGenericError(xmlGenericErrorContext, "====> %s\n", node->name);
-#endif
-    }
-    xmlSchemaValidateType(ctxt, child, decl, decl->subtypes);
-
-    if (decl->contModel != NULL) {
-        ret = xmlRegExecPushString(ctxt->regexp, NULL, NULL);
-#ifdef DEBUG_AUTOMATA
-        xmlGenericError(xmlGenericErrorContext,
-                        "====> %s : %d\n", node->name, ret);
-#endif
-        if (ret == 0) {
-            xmlSchemaVCustomErr(ctxt, XML_SCHEMAV_ELEMENT_CONTENT,
-		node, decl->subtypes, "The element content is not valid", NULL);
-        } else if (ret < 0) {
-	    xmlSchemaVCustomErr(ctxt, XML_SCHEMAV_ELEMENT_CONTENT,
-		node, decl->subtypes, "The element content is not valid", NULL);
-#ifdef DEBUG_CONTENT
-        } else {
-            xmlGenericError(xmlGenericErrorContext,
-                            "Element %s content check succeeded\n",
-                            node->name);
-
-#endif
-        }
-        xmlRegFreeExecCtxt(ctxt->regexp);
-    }
-    ctxt->regexp = oldregexp;
-    ctxt->node = child;
-    ctxt->type = (xmlSchemaTypePtr) decl;
+    * URGENT TODO: Look up what to do if the type is not available.
+    */
+    if (type != NULL)
+	xmlSchemaValidateElementByType(ctxt, type);
+    
+    ctxt->node = elem;
+    ctxt->type = (xmlSchemaTypePtr) elemDecl;
     return (ctxt->err);
 }
 
 /**
- * xmlSchemaValidateAnyInternal:
+ * xmlSchemaValidateElementByWildcardInternal:
  * @ctxt:  a schema validation context
  * @node:  the top node.
  *
- * Represents the recursive portion of xmlSchemaValidateAny. Not
- * intended to be used by other functions.
+ * Represents the recursive portion of xmlSchemaValidateElementByWildcard. 
+ * Not intended to be used by other functions.
  *
  * Returns 0 if the element is valid, a positive error code
  * number otherwise and -1 in case of an internal error.
  */
 static int
-xmlSchemaValidateAnyInternal(xmlSchemaValidCtxtPtr ctxt, 
-			     xmlSchemaWildcardPtr wild, 
-			     xmlNodePtr node)
+xmlSchemaValidateElementByWildcardInternal(xmlSchemaValidCtxtPtr ctxt,
+					   xmlSchemaWildcardPtr wild, 
+					   xmlNodePtr node)
 {        
     const xmlChar *uri;
     int ret = 0;
     xmlNodePtr child;
-    
+
+    if (ctxt->options & XML_SCHEMA_VAL_XSI_ASSEMBLE) {	
+	ret = xmlSchemaAssembleByXSIElem(ctxt, ctxt->node);
+	if (ret == -1) {
+	    xmlSchemaVCustomErr(ctxt, 
+		XML_SCHEMAV_INTERNAL,
+		ctxt->node, NULL, 	
+		"Internal error: xmlSchemaValidateElement, "
+		"assembling schema by xsi", NULL);
+	    return (-1);
+	}
+	/*
+	* NOTE: We won't react on schema parser errors here.
+	* TODO: But a warning would be nice.
+	*/
+    }    
     if (wild->processContents != XML_SCHEMAS_ANY_SKIP) {
 	xmlSchemaElementPtr decl = NULL;
 
@@ -13303,8 +14369,7 @@
 	    decl = xmlHashLookup3(ctxt->schema->elemDecl, node->name, NULL, NULL);
 	if (decl != NULL) {		    
 	    ctxt->node = node;	
-	    ctxt->type = (xmlSchemaTypePtr) decl;
-	    ret = xmlSchemaValidateElementType(ctxt, node->parent);
+	    ret = xmlSchemaValidateElementByDeclaration(ctxt, decl);
 	    if (ret < 0) {		
 		xmlSchemaVErr(ctxt, node, XML_SCHEMAV_INTERNAL,
 		    "Internal error: xmlSchemaValidateAnyInternal, "
@@ -13315,7 +14380,7 @@
 	} else if (wild->processContents == XML_SCHEMAS_ANY_STRICT) {
 	    /* TODO: Change to proper error code. */
 	    xmlSchemaVWildcardErr(ctxt, XML_SCHEMAV_CVC_ELT_1,
-		node, wild, "Global declaration is absent");
+		node, wild, "No matching global declaration available");
 	    return (ctxt->err);
 	}
     }
@@ -13331,10 +14396,11 @@
 		    /* TODO: error code. */
 		    xmlSchemaVWildcardErr(ctxt, XML_SCHEMAV_ELEMENT_CONTENT,
 			child, wild, 
-			"The namespace of the element is not allowed.");
+			"The namespace of the element is not allowed");
 		    return (ctxt->err);  
 		}
-		ret = xmlSchemaValidateAnyInternal(ctxt, wild, child);
+		ret = xmlSchemaValidateElementByWildcardInternal(ctxt, 
+		    wild, child);
 		if (ret != 0)
 		    return (ret);		
 	    }
@@ -13345,17 +14411,26 @@
 }
 
 /**
- * xmlSchemaValidateAny:
+ * xmlSchemaValidateElementContByWildcard:
  * @ctxt:  a schema validation context
  *
  * Returns 0 if the element is valid, a positive error code
  * number otherwise and -1 in case of an internal or API error.
  */
 static int
-xmlSchemaValidateAny(xmlSchemaValidCtxtPtr ctxt)
+xmlSchemaValidateElementByWildcard(xmlSchemaValidCtxtPtr ctxt, 
+				   xmlSchemaTypePtr type)
 {       
-    return(xmlSchemaValidateAnyInternal(ctxt, 
-	    ctxt->type->attributeWildcard, ctxt->cur));    
+    if ((type == NULL) || (type->type != XML_SCHEMA_TYPE_ANY) ||
+	(ctxt->node == NULL)) {
+	xmlSchemaVCustomErr(ctxt,
+	    XML_SCHEMAV_INTERNAL, ctxt->node, NULL,
+	    "Internal error: xmlSchemaValidateElementByWildcard, "
+	    "bad arguments", NULL);
+	return (-1);
+    }
+    return(xmlSchemaValidateElementByWildcardInternal(ctxt, 
+	    type->attributeWildcard, ctxt->node));
 }
 
 /**
@@ -13372,35 +14447,45 @@
  * otherwise and -1 in case of an internal or API error.
  */
 static int
-xmlSchemaValidateAnyTypeContent(xmlSchemaValidCtxtPtr ctxt, xmlNodePtr node)
+xmlSchemaValidateElementByAnyType(xmlSchemaValidCtxtPtr ctxt, 
+				  xmlSchemaTypePtr type)
 {
-    xmlNodePtr top = node;
-    xmlSchemaTypePtr decl;
+    xmlSchemaTypePtr oldtype;
+    xmlNodePtr top, cur;
+    xmlSchemaElementPtr decl;
     int skipContent, ret;
-    
-    if (node->children == NULL) 
+
+    if ((type == NULL) || (ctxt->node == NULL))
+	return (-1);
+
+    if (ctxt->node->children == NULL) 
 	return (0);
-    node = node->children;
-    while (node != NULL) {
+
+    oldtype = ctxt->type;
+    top = ctxt->node;        
+    /*
+    * STREAM: Child nodes are processed.
+    */
+    cur = ctxt->node->children;
+    while (cur != NULL) {
 	skipContent = 0;
-	if (node->type == XML_ELEMENT_NODE) {    
+	if (cur->type == XML_ELEMENT_NODE) {
 	    /*
 	    * The process contents of the wildcard is "lax", thus
 	    * we need to validate the element if a declaration
 	    * exists.
 	    */		
-	    if (node->ns != NULL)
+	    if (cur->ns != NULL)
 		decl = xmlHashLookup3(ctxt->schema->elemDecl,
-		node->name, node->ns->href, NULL);
+		    cur->name, cur->ns->href, NULL);
 	    else 
-		decl = xmlHashLookup3(ctxt->schema->elemDecl, node->name, NULL, NULL);
-	    
+		decl = xmlHashLookup3(ctxt->schema->elemDecl, cur->name, NULL, NULL);	    
 	    if (decl != NULL) {		    
-		ctxt->node = node;	
-		ctxt->type = (xmlSchemaTypePtr) decl;
-		ret = xmlSchemaValidateElementType(ctxt, node->parent);
+		ctxt->node = cur;
+		ret = xmlSchemaValidateElementByDeclaration(ctxt, decl);
+		ctxt->node = top;
 		if (ret < 0) {		
-		    xmlSchemaVErr(ctxt, node, XML_SCHEMAV_INTERNAL,
+		    xmlSchemaVErr(ctxt, cur, XML_SCHEMAV_INTERNAL,
 			"Internal error: xmlSchemaValidateAnyTypeContent, "
 			"validating an element in the context of a wildcard.",
 			NULL, NULL);
@@ -13413,32 +14498,33 @@
 	/*
 	* Browse the full subtree, deep first.
 	*/
-        if ((skipContent == 0) && (node->children != NULL)) {
+        if ((skipContent == 0) && (cur->children != NULL)) {
 	    /* deep first */
-	    node = node->children;
-	} else if ((node != top) && (node->next != NULL)) {
+	    cur = cur->children;
+	} else if ((cur != top) && (cur->next != NULL)) {
 	    /* then siblings */
-	    node = node->next;
-	} else if (node != top) {
+	    cur = cur->next;
+	} else if (cur != top) {
 	    /* go up to parents->next if needed */
-	    while (node != top) {
-	        if (node->parent != NULL)
-		    node = node->parent;
-		if ((node != top) && (node->next != NULL)) {
-		    node = node->next;
+	    while (cur != top) {
+	        if (cur->parent != NULL)
+		    cur = cur->parent;
+		if ((cur != top) && (cur->next != NULL)) {
+		    cur = cur->next;
 		    break;
 		}
-		if (node->parent == NULL) {
-		    node = NULL;
+		if (cur->parent == NULL) {
+		    cur = NULL;
 		    break;
 		}
 	    }
 	    /* exit condition */
-	    if (node == top) 
-	        node = NULL;
+	    if (cur == top) 
+	        cur = NULL;
 	} else
 	    break;
     }
+    ctxt->type = oldtype;
     return (0);
 }
 
@@ -13500,17 +14586,50 @@
  * the report of any additional information by the user.
  */
 static int
-xmlSchemaValidateComplexType(xmlSchemaValidCtxtPtr ctxt, xmlNodePtr node)
+xmlSchemaValidateElementByComplexType(xmlSchemaValidCtxtPtr ctxt, 
+				      xmlSchemaTypePtr type)
 {
-    xmlNodePtr child;
-    xmlSchemaTypePtr type;
+    xmlSchemaTypePtr oldtype;    
+    xmlNodePtr elem, child;
     int ret = 0;
     const xmlChar *nsUri;    
+    xmlSchemaAttrStatePtr attrs = NULL, attrTop = NULL;
 
-    child = ctxt->node;
-    type = ctxt->type;
-    ctxt->cur = node;
+    if ((ctxt == NULL) || (type->type != XML_SCHEMA_TYPE_COMPLEX))
+	return (-1);
 
+    oldtype = ctxt->type;
+    ctxt->type = type;
+    elem = ctxt->node;
+
+
+    /*
+    * Verify the attributes
+    */
+    /*
+    * TODO: This "attrTop" thing is not needed any more.
+    */    
+    attrs = ctxt->attr;    
+    attrTop = ctxt->attrTop;   
+    /*
+    * STREAM: Attribute nodes are processed.
+    */
+    xmlSchemaRegisterAttributes(ctxt, elem->properties);     
+    xmlSchemaValidateAttributes(ctxt, elem, type);
+    if (ctxt->attr != NULL)
+	xmlSchemaFreeAttributeStates(ctxt->attr);
+    ctxt->attr = attrs;    
+    ctxt->attrTop = attrTop;
+
+    /*
+    * FIXME TODO: This one creates a regexp even if no content
+    * model was defined. Somehow ->contModel is always not NULL
+    * for complex types, even if they are empty.
+    */    
+    /*
+    * FIXME TODO URGENT: Move the content model to the
+    * type definition.
+    */      
     switch (type->contentType) {
 	case XML_SCHEMA_CONTENT_EMPTY: {
 	    /*
@@ -13520,17 +14639,52 @@
 	    /*
 	    * TODO: Is the entity stuff correct?
 	    */
-	    if (xmlSchemaHasElemOrCharContent(node) == 1) {	    	    
+	    if (xmlSchemaHasElemOrCharContent(elem) == 1) {	    	    
 		xmlSchemaVComplexTypeErr(ctxt, 
 		    XML_SCHEMAV_CVC_COMPLEX_TYPE_2_1,
-		    node, type, 
+		    elem, type, 
 		    "Character or element content is not allowed, "
 		    "because the content type is empty");
             }	 
             break;
 	}
+	case XML_SCHEMA_CONTENT_MIXED:
+	    if ((type->subtypes == NULL) && 
+		(type->baseType == xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYTYPE))) {
+		/*
+		* The type has 'anyType' as its base and no content model
+		* is defined -> use 'anyType' as the type to validate
+		* against.
+		*/
+		ret = xmlSchemaValidateElementByAnyType(ctxt, type->baseType);
+		/* TODO: Handle -1. */
+		break;
+	    }
+	    /* No break on purpose. */
         case XML_SCHEMA_CONTENT_ELEMENTS:
-        case XML_SCHEMA_CONTENT_MIXED:              
+        {
+	    xmlRegExecCtxtPtr oldregexp = NULL;
+
+	    
+	    /*
+	    * Content model check initialization.
+	    */
+	    if (type->contModel != NULL) {					
+		oldregexp = ctxt->regexp;
+		ctxt->regexp = xmlRegNewExecCtxt(type->contModel,
+		    (xmlRegExecCallbacks)
+		    xmlSchemaValidateCallback, ctxt);
+#ifdef DEBUG_AUTOMATA
+		xmlGenericError(xmlGenericErrorContext, "====> %s\n", elem->name);
+#endif
+	    }
+	    /* xmlSchemaValidateElementByType(ctxt, elemDecl->subtypes); */
+	    
+	    
+	    /*
+	    * STREAM: Children are processed.
+	    */
+	    child = elem->children;
 	    while (child != NULL) {		
 		if (child->type == XML_ELEMENT_NODE) {
 		    if (child->ns != NULL)
@@ -13538,7 +14692,11 @@
 		    else
 			nsUri = NULL;
 		    ret = xmlRegExecPushString2(ctxt->regexp,
-			child->name, nsUri, child);	
+			child->name, nsUri, child);
+		    /*
+		    * URGENT TODO: Could we anchor an error report
+		    * here to notify of invalid elements?
+		    */
 #ifdef DEBUG_AUTOMATA		    
 		    if (ret < 0)
 			xmlGenericError(xmlGenericErrorContext,
@@ -13564,13 +14722,40 @@
 		    */			
 		    xmlSchemaVComplexTypeErr(ctxt, 
 			XML_SCHEMAV_CVC_COMPLEX_TYPE_2_3,
-			node, type, 
+			elem, type, 
 			"Character content is not allowed, "
 			"because the content type is element-only");		    
 		    break;
 		}
 		child = child->next;		    
-	    }            	    
+	    }    
+	    /*
+	    * Content model check finalization.
+	    */
+       	    if (type->contModel != NULL) {
+		ret = xmlRegExecPushString(ctxt->regexp, NULL, NULL);
+#ifdef DEBUG_AUTOMATA
+		xmlGenericError(xmlGenericErrorContext,
+		    "====> %s : %d\n", elem->name, ret);
+#endif
+		if (ret == 0) {
+		    xmlSchemaVCustomErr(ctxt, XML_SCHEMAV_ELEMENT_CONTENT,
+			elem, type, "The element content is not valid", NULL);
+		} else if (ret < 0) {
+		    xmlSchemaVCustomErr(ctxt, XML_SCHEMAV_ELEMENT_CONTENT,
+			elem, type, "The element content is not valid", NULL);
+#ifdef DEBUG_CONTENT
+		} else {
+		    xmlGenericError(xmlGenericErrorContext,
+			"Element %s content check succeeded\n",
+			elem->name);
+		    
+#endif
+		}
+		xmlRegFreeExecCtxt(ctxt->regexp);
+		ctxt->regexp = oldregexp;
+	    }
+	}
             break;
 	case XML_SCHEMA_CONTENT_SIMPLE:
         case XML_SCHEMA_CONTENT_BASIC:{
@@ -13586,29 +14771,50 @@
 	    * of the element information item is ·valid· with respect 
 	    * to that simple type definition as defined by String 
 	    * Valid (§3.14.4).
-	    */	    
-	    child = node->children;
+	    */	  
+	    /*
+	    * STREAM: Children are processed.
+	    */
+	    child = elem->children;
 	    while (child != NULL) {
+		/*
+		* TODO: Could the entity stuff produce elements
+		* as well?
+		*/
                 if (child->type == XML_ELEMENT_NODE) {
 		    xmlSchemaVComplexTypeErr(ctxt,
 			XML_SCHEMAV_CVC_COMPLEX_TYPE_2_2,
-			node, type, 
+			elem, type, 
 			"Element content is not allowed, because "
 			"the content type is a simple type");
 		    ret = XML_SCHEMAV_CVC_COMPLEX_TYPE_2_2;
 		    break;
 		}
 		child = child->next;		    
-	    }	    
+	    }	
+	    ctxt->node = elem;
+	    ctxt->cur = elem->children;
 	    if (ret == 0) {
 		/*
 		* Validate the character content against a simple type.
 		*/
-		if (ctxt->node == NULL)
+		/*
+		* STREAM: Children are processed.
+		*/
+		if (elem->children == NULL)
 		    value = NULL;
 		else
-		    value = xmlNodeGetContent(node); 
-		ret = xmlSchemaValidateSimpleTypeValue(ctxt, value, 1, 1, 1);
+		    value = xmlNodeGetContent(elem); 
+		/*
+		* URGENT TODO: Should facets for the simple type validation be 
+		* disabled, if the derivation of facets for complex types 
+		* is implemented?
+		*/
+		/*
+		* NOTE: This call won't check the correct types of the
+		* content nodes, since this should be done here.
+		*/
+		ret = xmlSchemaValidateSimpleTypeValue(ctxt, type, value, 1, 1, 1, 0);
 		if (ret > 0) {	
 		    /*
 		    * NOTE: Although an error will be reported by 
@@ -13618,15 +14824,18 @@
 		    */
 		    xmlSchemaVComplexTypeErr(ctxt, 
 			XML_SCHEMAV_CVC_COMPLEX_TYPE_2_2,
-			node, type,  
+			elem, type,  
 			"The character content is not valid");
 		    ret = XML_SCHEMAV_CVC_COMPLEX_TYPE_2_2;
 		} else if (ret < 0) {
-		    xmlSchemaVErr(ctxt, node, XML_SCHEMAV_INTERNAL,
+		    xmlSchemaVErr(ctxt, elem, XML_SCHEMAV_INTERNAL,
 			"Internal error: xmlSchemaValidateComplexType, "
 			"Element '%s': Error while validating character "
 			"content against complex type '%s'.\n",
-			node->name, type->name);
+			elem->name, type->name);
+		    if (value != NULL)
+			xmlFree(value); 
+		    ctxt->type = oldtype;
 		    return (-1);
 		}
 	    }	    
@@ -13635,31 +14844,34 @@
 		* Apply facets of the complexType. Be sure to pass the 
 		* built-in type to xmlSchemaValidateFacetsInternal.
 		*/	    
-		/* TODO: I don't know yet if the facets of the simple type
+		/* URGENT TODO: I don't know yet if the facets of the simple type
 		* are used, or if the facets, defined by this complex type,
 		* are to be used only. This here applies both facet sets.
 		*/	    
 
-		ret = xmlSchemaValidateFacetsInternal(ctxt, type, 
-		    value, 0, 1);
+		ret = xmlSchemaValidateFacetsInternal(ctxt, 
+		    type, value, 0, 1);
 		if (ret > 0) {
 		    xmlSchemaVComplexTypeErr(ctxt, 
 			XML_SCHEMAV_CVC_COMPLEX_TYPE_2_2,
-			node, type, 
+			elem, type, 
 			"The character content is not valid");
 		    ret = XML_SCHEMAV_CVC_COMPLEX_TYPE_2_2;
 		} else if (ret < 0) {
-		    xmlSchemaVErr(ctxt, ctxt->cur, XML_SCHEMAV_INTERNAL,
+		    xmlSchemaVErr(ctxt, elem, XML_SCHEMAV_INTERNAL,
 			"Internal error: xmlSchemaValidateComplexType, "
 			"Element '%s': Error while validating character "
 			"content against complex type '%s'; failed to "
 			"apply facets.\n",
 			type->name, NULL);
+		    if (value != NULL)
+			xmlFree(value); 
+		    ctxt->type = oldtype;
+		    return (-1);
 		}
 	    }
 	    if (value != NULL)
 		xmlFree(value);    
-	    /* TODO: facets */
 	    break;
 	}
         default:
@@ -13667,139 +14879,12 @@
                                  "unimplemented content type %d\n",
                                  type->contentType);
     }
-    ctxt->cur = node;
+    ctxt->type = oldtype;
     return (ctxt->err);
 }
 
 /**
- * xmlSchemaValidateContent:
- * @ctxt:  a schema validation context
- * @elem:  an element
- * @type:  the type declaration
- *
- * Validate the content of an element against the type.
- *
- * Returns 0 if the element is schemas valid, a positive error code
- *     number otherwise and -1 in case of internal or API error.
- */
-static int
-xmlSchemaValidateContent(xmlSchemaValidCtxtPtr ctxt, xmlNodePtr node)
-{
-    xmlSchemaTypePtr type;
-
-    type = ctxt->type;
-    ctxt->cur = node;
-
-    switch (type->type) {
-        case XML_SCHEMA_TYPE_ANY:
-	    xmlSchemaValidateAny(ctxt);
-	    ctxt->type = type;
-            break;
-        case XML_SCHEMA_TYPE_COMPLEX:
-            xmlSchemaValidateComplexType(ctxt, node);
-            break;
-        case XML_SCHEMA_TYPE_ELEMENT:{
-                xmlSchemaElementPtr decl = (xmlSchemaElementPtr) type;
-
-                /*
-                 * Handle element reference here
-                 */
-		/*
-		* TODO: This should be removed, since checks for 
-		* consistence should not be done during validation.
-		*/
-                if (decl->ref != NULL) {
-                    if (decl->refDecl == NULL) {
-                        xmlSchemaVErr(ctxt, node, XML_SCHEMAV_INTERNAL,
-				      "Internal error: element reference %s "
-				      "not resolved\n", decl->ref, NULL);
-                        return (-1);
-                    }
-                    ctxt->type = (xmlSchemaTypePtr) decl->refDecl;
-                    decl = decl->refDecl;
-                }
-		/* TODO: Should "xmlSchemaValidateElement" be called instead? */
-                xmlSchemaValidateElementType(ctxt, node);
-                ctxt->type = type;
-                break;
-            }
-        case XML_SCHEMA_TYPE_BASIC:
-	    if (type->builtInType == XML_SCHEMAS_ANYTYPE)
-		xmlSchemaValidateAnyTypeContent(ctxt, node);
-	    else
-		xmlSchemaValidateSimpleTypeElement(ctxt, node);
-	    break;
-	case XML_SCHEMA_TYPE_SIMPLE:
-            xmlSchemaValidateSimpleTypeElement(ctxt, node);
-            break;
-        case XML_SCHEMA_TYPE_FACET:
-            TODO break;        
-        case XML_SCHEMA_TYPE_SEQUENCE:
-            TODO break;
-        case XML_SCHEMA_TYPE_CHOICE:
-            TODO break;
-        case XML_SCHEMA_TYPE_ALL:
-            TODO break;
-        case XML_SCHEMA_TYPE_SIMPLE_CONTENT:
-            TODO break;
-        case XML_SCHEMA_TYPE_COMPLEX_CONTENT:
-            TODO break;
-        case XML_SCHEMA_TYPE_UR:
-            TODO break;
-        case XML_SCHEMA_TYPE_RESTRICTION:
-            /*xmlSchemaValidateRestrictionType(ctxt, node); */
-            TODO break;
-        case XML_SCHEMA_TYPE_EXTENSION:
-            TODO break;
-        case XML_SCHEMA_TYPE_ATTRIBUTE:
-            TODO break;
-        case XML_SCHEMA_TYPE_GROUP:
-            TODO break;
-        case XML_SCHEMA_TYPE_NOTATION:
-            TODO break;
-        case XML_SCHEMA_TYPE_LIST:
-            TODO break;
-        case XML_SCHEMA_TYPE_UNION:
-            TODO break;
-        case XML_SCHEMA_FACET_MININCLUSIVE:
-            TODO break;
-        case XML_SCHEMA_FACET_MINEXCLUSIVE:
-            TODO break;
-        case XML_SCHEMA_FACET_MAXINCLUSIVE:
-            TODO break;
-        case XML_SCHEMA_FACET_MAXEXCLUSIVE:
-            TODO break;
-        case XML_SCHEMA_FACET_TOTALDIGITS:
-            TODO break;
-        case XML_SCHEMA_FACET_FRACTIONDIGITS:
-            TODO break;
-        case XML_SCHEMA_FACET_PATTERN:
-            TODO break;
-        case XML_SCHEMA_FACET_ENUMERATION:
-            TODO break;
-        case XML_SCHEMA_FACET_WHITESPACE:
-            TODO break;
-        case XML_SCHEMA_FACET_LENGTH:
-            TODO break;
-        case XML_SCHEMA_FACET_MAXLENGTH:
-            TODO break;
-        case XML_SCHEMA_FACET_MINLENGTH:
-            TODO break;
-        case XML_SCHEMA_TYPE_ATTRIBUTEGROUP:
-            TODO break;
-        case XML_SCHEMA_TYPE_ANY_ATTRIBUTE:
-            TODO break;
-    }
-
-    if (ctxt->node == NULL)
-        return (ctxt->err);
-    ctxt->node = ctxt->node->next;
-    ctxt->type = type->next;
-    return (ctxt->err);
-}
-
-/**
- * xmlSchemaValidateType:
+ * xmlSchemaValidateElementByType:
  * @ctxt:  a schema validation context
  * @elem:  an element
  * @type:  the list of type declarations
@@ -13810,72 +14895,44 @@
  *     number otherwise and -1 in case of internal or API error.
  */
 static int
-xmlSchemaValidateType(xmlSchemaValidCtxtPtr ctxt, xmlNodePtr elem,
-                      xmlSchemaElementPtr elemDecl, xmlSchemaTypePtr type)
+xmlSchemaValidateElementByType(xmlSchemaValidCtxtPtr ctxt,
+			       xmlSchemaTypePtr type)
 {
-    xmlChar *nil;
+    int ret;
 
-    if ((elem == NULL) || (type == NULL) || (elemDecl == NULL))
-        return (0);
-
-    /* This one is called by "xmlSchemaValidateElementType" and
-     * "xmlSchemaValidateElement".
-     */
-
+    /* 
+    * This one is called by "xmlSchemaValidateElementByDeclaration".
+    * It will forward to the proper validation 
+    * procedures for the given type.
+    */
+    if ((type == NULL) || (ctxt == NULL))
+        return (-1);
+    
     /*
-     * 3.3.4 : 2
-     */
-    if (elemDecl->flags & XML_SCHEMAS_ELEM_ABSTRACT) {
-	xmlSchemaVCustomErr(ctxt,
-	    XML_SCHEMAV_CVC_ELT_2,
-	    elem, NULL, 
-	    "The element declaration is abstract", NULL);
-        return (ctxt->err);
-    }
-    /*
-     * 3.3.4: 3
-     */
-    nil = xmlGetNsProp(elem, BAD_CAST "nil", xmlSchemaInstanceNs);
-    if (elemDecl->flags & XML_SCHEMAS_ELEM_NILLABLE) {
-        /* 3.3.4: 3.2 */
-        if (xmlStrEqual(nil, BAD_CAST "true")) {
-	    if (xmlSchemaHasElemOrCharContent(elem) == 1) {
-                xmlSchemaVCustomErr(ctxt, 
-		    XML_SCHEMAV_CVC_ELT_3_2_1, 
-		    /* XML_SCHEMAS_ERR_NOTEMPTY, */
-		    elem, NULL,		    
-		    "The 'nilled' element must have no character or element "
-		    "content", NULL);
-                return (ctxt->err);
-            }
-            if ((elemDecl->flags & XML_SCHEMAS_ELEM_FIXED) &&
-                (elemDecl->value != NULL)) {
-                xmlSchemaVCustomErr(ctxt, XML_SCHEMAV_CVC_ELT_3_2_2, 
-		    /* XML_SCHEMAS_ERR_HAVEDEFAULT, */
-		    elem, NULL,
-		    "There is a fixed value constraint defined for "
-		    "the 'nilled' element", NULL);		    
-                return (ctxt->err);
-            }
-        }
-    } else {
-        /* 3.3.4: 3.1 */
-        if (nil != NULL) {
-	    xmlSchemaVCustomErr(ctxt, XML_SCHEMAV_CVC_ELT_3_1, 
-		/* XML_SCHEMAS_ERR_NOTNILLABLE, */
-		elem, NULL,
-		"The element is not 'nillable'", NULL);			  
-            xmlFree(nil);
-            return (ctxt->err);
-        }
-    }
-
-    /* TODO 3.3.4: 4 if the element carries xs:type */
-
-    ctxt->type = elemDecl->subtypes;
-    ctxt->node = elem->children;
-    xmlSchemaValidateContent(ctxt, elem);   
-    return (ctxt->err);
+    * @elemDecl->subtypes will be of type XML_SCHEMA_TYPE_COMPLEX,
+    * XML_SCHEMA_TYPE_SIMPLE or XML_SCHEMA_TYPE_BASIC.
+    */
+    switch (type->type) {
+	case XML_SCHEMA_TYPE_COMPLEX:
+            ret = xmlSchemaValidateElementByComplexType(ctxt, type);
+            break;
+	case XML_SCHEMA_TYPE_SIMPLE:
+            ret = xmlSchemaValidateElementBySimpleType(ctxt, type);
+            break;
+	case XML_SCHEMA_TYPE_BASIC:
+	    if (type->builtInType == XML_SCHEMAS_ANYTYPE)
+		ret = xmlSchemaValidateElementByAnyType(ctxt, type);
+	    else
+		ret = xmlSchemaValidateElementBySimpleType(ctxt, type);
+	    break;
+	default:
+	    ret = -1;
+	    break;
+    }	
+    if (ret == -1)
+	return (-1);
+    else
+	return (ctxt->err);
 }
 
 
@@ -13906,10 +14963,11 @@
     xmlAttrPtr attr; /* An attribute on the element. */
     xmlChar *value;
     const xmlChar *nsURI;
-    xmlSchemaAttributeLinkPtr attrUse;
+    xmlSchemaAttributeLinkPtr attrUse = NULL;
     xmlSchemaAttributePtr attrDecl;
     int found;
     xmlSchemaAttrStatePtr curState, reqAttrStates = NULL, reqAttrStatesTop = NULL;
+    xmlNodePtr oldnode;
 #ifdef DEBUG_ATTR_VALIDATION
     int redundant = 0;
 #endif
@@ -13923,7 +14981,10 @@
     */
     if (type == xmlSchemaGetBuiltInType(XML_SCHEMAS_ANYTYPE))
 	return (0);
-    attrUse = type->attributeUses;
+
+    oldnode = ctxt->node;
+    if (type != NULL)
+	attrUse = type->attributeUses;
     while (attrUse != NULL) {
         found = 0;    
 	attrDecl = attrUse->attr;
@@ -13990,8 +15051,7 @@
 	    printf("found\n");
 #endif
             found = 1;
-            ctxt->cur = (xmlNodePtr) attr;
-	    ctxt->node = attr->children;
+            
 
             if (attrDecl->subtypes == NULL) {
 		curState->state = XML_SCHEMAS_ATTR_TYPE_NOT_RESOLVED;
@@ -14002,9 +15062,13 @@
                 continue;
             }
             value = xmlNodeListGetString(elem->doc, attr->children, 1);
-	    ctxt->type = attrDecl->subtypes;	    
-            ret = xmlSchemaValidateSimpleTypeValue(ctxt, value, 1, 1, 1);
-	    ctxt->type = type;
+	    ctxt->node = (xmlNodePtr) attr;
+	    ctxt->cur = attr->children;
+	    /*
+	    * NOTE: This call also checks the content nodes for correct type.
+	    */
+            ret = xmlSchemaValidateSimpleTypeValue(ctxt, attrDecl->subtypes, 
+		value, 1, 1, 1, 1);
             if (ret != 0) 
 		curState->state = XML_SCHEMAS_ATTR_INVALID_VALUE;   				
             else
@@ -14026,6 +15090,7 @@
 	    tmp = (xmlSchemaAttrStatePtr) xmlMalloc(sizeof(xmlSchemaAttrState));
 	    if (tmp == NULL) {
 		xmlSchemaVErrMemory(ctxt, "registering required attributes", NULL);
+		ctxt->node = oldnode;
 		return (-1);
             }            
 	    tmp->attr = NULL;
@@ -14058,7 +15123,7 @@
     /*
     * Process wildcards.
     */
-    if (type->attributeWildcard != NULL) {	
+    if ((type != NULL) && (type->attributeWildcard != NULL)) {	
 #ifdef DEBUG_ATTR_VALIDATION
 	xmlSchemaWildcardNsPtr ns;	
 	printf("matching wildcard: [%d] of complexType: %s\n", type->attributeWildcard, type->name);
@@ -14114,14 +15179,19 @@
 			attrDecl = xmlSchemaGetAttribute(ctxt->schema, 
 			    attr->name, nsURI);		
 			if (attrDecl != NULL) {
-			    value = xmlNodeListGetString(elem->doc, attr->children, 1);
-			    ctxt->cur = (xmlNodePtr) attr;
-			    ctxt->node = attr->children;
-			    ctxt->type = attrDecl->subtypes;
-			    ret = xmlSchemaValidateSimpleTypeValue(ctxt, value, 1, 1, 1);
-			    ctxt->type = type;
+			    value = xmlNodeListGetString(elem->doc, 
+				attr->children, 1);
+			    ctxt->node = (xmlNodePtr) attr;
+			    ctxt->cur = attr->children;
+			    /*
+			    * NOTE: This call also checks the content nodes 
+			    * for correct type.
+			    */
+			    ret = xmlSchemaValidateSimpleTypeValue(ctxt, 
+				attrDecl->subtypes, value, 1, 1, 1, 1);
 			    if (ret != 0) 
-				curState->state = XML_SCHEMAS_ATTR_INVALID_VALUE;   				
+				curState->state = 
+				XML_SCHEMAS_ATTR_INVALID_VALUE;
 			    else
 				curState->state = XML_SCHEMAS_ATTR_CHECKED;
 			    curState->decl = attrDecl;
@@ -14140,6 +15210,7 @@
 	    curState = curState->next;
         }
     }
+
     /*
     * Report missing and illegal attributes.
     */
@@ -14154,7 +15225,11 @@
 		    /* TODO: "prohibited" won't ever be touched here!. 
 		      (curState->state == XML_SCHEMAS_ATTR_PROHIBITED))
 		    */
-		    if (type->attributeWildcard == NULL) {
+		    /*
+		    * TODO: One might report different error messages 
+		    * for the following errors.
+		    */
+		    if ((type == NULL) || (type->attributeWildcard == NULL)) {
 			xmlSchemaVIllegalAttrErr(ctxt, 
 			    XML_SCHEMAV_CVC_COMPLEX_TYPE_3_2_1, attr);
 		    } else {
@@ -14172,6 +15247,7 @@
 	                "xmlSchemaValidateAttributes: redundant call by type: %s\n",
 	                type->name);
 #endif
+    ctxt->node = oldnode;
     return (ctxt->err);
 }
 
@@ -14186,95 +15262,58 @@
  *     number otherwise and -1 in case of internal or API error.
  */
 static int
-xmlSchemaValidateElement(xmlSchemaValidCtxtPtr ctxt, xmlNodePtr elem)
+xmlSchemaValidateElement(xmlSchemaValidCtxtPtr ctxt)
 {
-    xmlSchemaElementPtr elemDecl;
+    xmlSchemaElementPtr elemDecl;    
     int ret;
-    xmlSchemaAttrStatePtr attrs, attrTop;
 
-    if (elem->ns != NULL) {
-        elemDecl = xmlHashLookup3(ctxt->schema->elemDecl,
-                                  elem->name, elem->ns->href, NULL);
-    } else {
-        elemDecl = xmlHashLookup3(ctxt->schema->elemDecl,
-                                  elem->name, NULL, NULL);
-    }
     /* 
-    * This one is called by xmlSchemaValidateDocument and 
-    * xmlSchemaValidateAnyInernal. 
+    * This one is called by xmlSchemaValidateDocument and
+    * xmlSchemaValidateOneElement.
+    */  
+    /*
+    * Assemble new schemata using xsi.
     */
-
-    /*
-     * 3.3.4 : 1
-     */
+    if (ctxt->options & XML_SCHEMA_VAL_XSI_ASSEMBLE) {	
+	ret = xmlSchemaAssembleByXSIElem(ctxt, ctxt->node);
+	if (ret == -1) {
+	    xmlSchemaVCustomErr(ctxt, 
+		XML_SCHEMAV_INTERNAL,
+		ctxt->node, NULL, 	
+		"Internal error: xmlSchemaValidateElement, "
+		"assembling schema by xsi", NULL);
+	    return (-1);
+	}
+	/*
+	* NOTE: We won't react on schema parser errors here.
+	* TODO: But a warning would be nice.
+	*/
+    }
+    	    
+    if (ctxt->node->ns != NULL)
+	elemDecl = xmlSchemaGetElem(ctxt->schema, ctxt->node->name, ctxt->node->ns->href);
+    else
+	elemDecl = xmlSchemaGetElem(ctxt->schema, ctxt->node->name, NULL);
+   
     if (elemDecl == NULL) {
+        xmlSchemaVCustomErr(ctxt, 
+	    XML_SCHEMAV_CVC_ELT_1,
+	    ctxt->node, NULL, 	  
+	    "No matching global declaration available", NULL);
+	return (XML_SCHEMAV_CVC_ELT_1);
+    }  
+               
+    ret = xmlSchemaValidateElementByDeclaration(ctxt, elemDecl);
+    if (ret < 0) {
 	xmlSchemaVCustomErr(ctxt,
-	    XML_SCHEMAV_CVC_ELT_1, 
-	    /* XML_SCHEMAS_ERR_UNDECLAREDELEM, */
-	    elem, NULL,
-	    "Global declaration is absent", NULL);
-        return (ctxt->err);
+	    XML_SCHEMAV_INTERNAL, ctxt->node, NULL,
+	    "Internal error: xmlSchemaValidateElement, "
+	    "calling validation by declaration", NULL);
     }
-    /* TODO: This should be already catched at the schema parsing level. */
-    if (elemDecl->subtypes == NULL) {
-	xmlSchemaVCustomErr(ctxt,
-	    XML_SCHEMAV_INTERNAL,
-	    /* XML_SCHEMAS_ERR_NOTYPE */
-	    elem, NULL,
-	    "The element declaration has no type assigned", NULL);        
-        return (ctxt->err);
-    }
-    /*
-     * Verify the attributes
-     */
-    attrs = ctxt->attr;
-    attrTop = ctxt->attrTop;
-    xmlSchemaRegisterAttributes(ctxt, elem->properties);
-    xmlSchemaValidateAttributes(ctxt, elem, elemDecl->subtypes);
-    if (ctxt->attr != NULL)
-	xmlSchemaFreeAttributeStates(ctxt->attr);
-    ctxt->attr = attrs;
-    ctxt->attrTop = attrTop;
-    /*
-     * Verify the element content recursively
-     */
-    if (elemDecl->contModel != NULL) {
-        ctxt->regexp = xmlRegNewExecCtxt(elemDecl->contModel,
-                                         (xmlRegExecCallbacks)
-                                         xmlSchemaValidateCallback, ctxt);
-#ifdef DEBUG_AUTOMATA
-        xmlGenericError(xmlGenericErrorContext, "====> %s\n", elem->name);
-#endif
-    }
-    xmlSchemaValidateType(ctxt, elem, elemDecl, elemDecl->subtypes);
-    if (elemDecl->contModel != NULL) {
-        ret = xmlRegExecPushString(ctxt->regexp, NULL, NULL);
-#ifdef DEBUG_AUTOMATA
-        xmlGenericError(xmlGenericErrorContext,
-                        "====> %s : %d\n", elem->name, ret);
-#endif
-	if (ret == 0) {
-	    /* TODO: error code. */
-            xmlSchemaVCustomErr(ctxt, XML_SCHEMAV_ELEMENT_CONTENT,
-		elem, elemDecl->subtypes, 
-		"The element content is not valid", NULL);
-        } else if (ret < 0) {
-	    xmlSchemaVCustomErr(ctxt, XML_SCHEMAV_ELEMENT_CONTENT,
-		elem, elemDecl->subtypes, 
-		"The element content is not valid", NULL);
-#ifdef DEBUG_CONTENT
-        else {
-            xmlGenericError(xmlGenericErrorContext,
-                            "Element %s content check succeeded\n",
-                            elem->name);
-
-#endif
-        }
-        xmlRegFreeExecCtxt(ctxt->regexp);
-    }
-    return (ctxt->err);
+    return (ret);   
 }
 
+
 /**
  * xmlSchemaValidateOneElement:
  * @ctxt:  a schema validation context
@@ -14288,19 +15327,21 @@
 int
 xmlSchemaValidateOneElement(xmlSchemaValidCtxtPtr ctxt, xmlNodePtr elem)
 {
-    if ((ctxt == NULL) || (elem == NULL))
+    if ((ctxt == NULL) || (elem == NULL) || (elem->type != XML_ELEMENT_NODE))
 	return (-1);
 
     ctxt->doc = elem->doc;
     ctxt->err = 0;
     ctxt->nberrors = 0;
-    return (xmlSchemaValidateElement(ctxt, elem));
+    ctxt->node = elem;
+    return (xmlSchemaValidateElement(ctxt));
 }
 
 /**
  * xmlSchemaValidateDocument:
  * @ctxt:  a schema validation context
  * @doc:  a parsed document tree
+ * @xsiAssemble: should schemata be added if requested by the instance?
  *
  * Validate a document tree in memory.
  *
@@ -14311,7 +15352,6 @@
 xmlSchemaValidateDocument(xmlSchemaValidCtxtPtr ctxt, xmlDocPtr doc)
 {
     xmlNodePtr root;
-    xmlSchemaElementPtr elemDecl;
      
     root = xmlDocGetRootElement(doc);
     if (root == NULL) {
@@ -14320,31 +15360,12 @@
 	    (xmlNodePtr) doc, NULL,
 	    "The document has no document element", NULL);
         return (ctxt->err);
-    }
-
-    if (root->ns != NULL)
-	elemDecl = xmlSchemaGetElem(ctxt->schema, root->name, root->ns->href);
-    else
-	elemDecl = xmlSchemaGetElem(ctxt->schema, root->name, NULL);
-    if (elemDecl == NULL) {
-        xmlSchemaVCustomErr(ctxt, 
-	    XML_SCHEMAV_CVC_ELT_1,
-	    root, NULL, 
-	    /* XML_SCHEMAS_ERR_UNDECLAREDELEM, */
-	    "Global declaration is absent", NULL);
-    } 
-    /*
-    * Removed, since xmlSchemaGetElem will return global declarations only.
-    *
-      else if ((elemDecl->flags & XML_SCHEMAS_ELEM_GLOBAL) == 0) {
-        xmlSchemaVErr(ctxt, root, XML_SCHEMAS_ERR_NOTTOPLEVEL,
-		      "Root element %s not global\n", root->name, NULL);
-      }
-    */
+    }    
     /*
      * Okay, start the recursive validation
      */
-    xmlSchemaValidateElement(ctxt, root);
+    ctxt->node = root;
+    xmlSchemaValidateElement(ctxt);
 
     return (ctxt->err);
 }
@@ -14452,6 +15473,56 @@
 	return (0);
 }
 
+#if 0 /* Will be enabled if it is clear what options are needed. */
+/**
+ * xmlSchemaValidCtxtSetOptions:
+ * @ctxt:	a schema validation context
+ * @options: a combination of xmlSchemaValidOption
+ *
+ * Sets the options to be used during the validation.
+ *
+ * Returns 0 in case of success, -1 in case of an
+ * API error.
+ */
+static int
+xmlSchemaValidCtxtSetOptions(xmlSchemaValidCtxtPtr ctxt,
+			     int options)
+					
+{
+    int i;
+
+    if (ctxt == NULL)
+	return (-1);
+    /*
+    * WARNING: Change the start value if adding to the
+    * xmlSchemaValidOption.
+    */
+    for (i = 1; i <= (int) sizeof(int) * 8; i++) {	
+        if (options & 1<<i) {
+	    return (-1);   
+        }	
+    }
+    ctxt->options = options;
+    return (0);      
+}
+
+/**
+ * xmlSchemaValidCtxtGetOptions:
+ * @ctxt:	a schema validation context 
+ *
+ * Returns the option combination of the validation context.
+ */
+static int
+xmlSchemaValidCtxtGetOptions(xmlSchemaValidCtxtPtr ctxt)
+					
+{    
+    if (ctxt == NULL)
+	return (-1);
+    else 
+	return (ctxt->options);    
+}
+#endif
+
 /**
  * xmlSchemaValidateDoc:
  * @ctxt:  a schema validation context
@@ -14473,7 +15544,7 @@
     ctxt->doc = doc;
     ctxt->err = 0; 
     ctxt->nberrors = 0; 
-    
+        
     ret = xmlSchemaValidateDocument(ctxt, doc);
     return (ret);
 }