Contributed by: Matt Bishop / Kevin Krouse

port of xmlbeans to jdk1.3 on the branch 'xmlbeans-jdk13_branch'


git-svn-id: https://svn.apache.org/repos/asf/xmlbeans/branches/xmlbeans-jdk13_branch@110823 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/v1/README.txt b/v1/README.txt
index e10c26d..d8b1f1c 100644
--- a/v1/README.txt
+++ b/v1/README.txt
@@ -1,4 +1,4 @@
-XMLBeans v1.0.3
+XMLBeans v1.0.3 (jdk1.3 port)
 
 Welcome to XmlBeans!
 
diff --git a/v1/bin/dumpxsb b/v1/bin/dumpxsb
index e024da5..903b381 100755
--- a/v1/bin/dumpxsb
+++ b/v1/bin/dumpxsb
@@ -6,8 +6,12 @@
 
 if [ -e $XMLBEANS_HOME/build/ar/xbean.jar ]; then
     cp=$cp:$XMLBEANS_HOME/build/ar/xbean.jar;
+    cp=$cp:$XMLBEANS_HOME/build/lib/xml-apis.jar;
+    cp=$cp:$XMLBEANS_HOME/build/lib/xercesImpl.jar;
 elif [ -e $XMLBEANS_HOME/lib/xbean.jar ]; then
     cp=$cp:$XMLBEANS_HOME/lib/xbean.jar;
+    cp=$cp:$XMLBEANS_HOME/lib/xml-apis.jar;
+    cp=$cp:$XMLBEANS_HOME/lib/xercesImpl.jar;
 fi
 
 case "`uname`" in
diff --git a/v1/bin/dumpxsb.cmd b/v1/bin/dumpxsb.cmd
index 749fe1a..18ca9be 100644
--- a/v1/bin/dumpxsb.cmd
+++ b/v1/bin/dumpxsb.cmd
@@ -9,9 +9,9 @@
 set cp=
 
 if EXIST %XMLBEANS_HOME%\build\ar\xbean.jar. (
-    set cp=%cp%;%XMLBEANS_HOME%\build\ar\xbean.jar.
+    set cp=%XMLBEANS_HOME%\build\ar\xbean.jar;%XMLBEANS_HOME%\build\lib\xml-apis.jar;%XMLBEANS_HOME%\build\lib\xercesImpl.jar.
 ) else if EXIST %XMLBEANS_HOME%\lib\xbean.jar. (
-    set cp=%cp%;%XMLBEANS_HOME%\lib\xbean.jar.
+    set cp=%XMLBEANS_HOME%\build\lib\xbean.jar;%XMLBEANS_HOME%\lib\xml-apis.jar;%XMLBEANS_HOME%\lib\xercesImpl.jar.
 )
 
 java -classpath %cp% org.apache.xmlbeans.impl.tool.XsbDumper %*
diff --git a/v1/bin/jaxbc.cmd b/v1/bin/jaxbc.cmd
index a9d2079..a6de6ce 100644
--- a/v1/bin/jaxbc.cmd
+++ b/v1/bin/jaxbc.cmd
@@ -10,6 +10,8 @@
 set cp=
 set cp=%cp%;%XMLBEANS_HOME%\build\ar\xbean.jar
 set cp=%cp%;%XMLBEANS_HOME%\external\lib\jaxb-1.0\jaxb-api.jar
+set cp=%cp%;%XMLBEANS_HOME%\build\lib\xml-apis.jar
+set cp=%cp%;%XMLBEANS_HOME%\build\lib\xercesImpl.jar
 
 java -classpath %cp% org.apache.xmlbeans.impl.tool.SchemaCompiler -jaxb %*
 
diff --git a/v1/bin/random.cmd b/v1/bin/random.cmd
index 0727d26..3f5596b 100644
--- a/v1/bin/random.cmd
+++ b/v1/bin/random.cmd
@@ -9,8 +9,10 @@
 
 set cp=
 set cp=%cp%;%XMLBEANS_HOME%\build\ar\xbean.jar
+set cp=%cp%;%XMLBEANS_HOME%\build\lib\xml-apis.jar
+set cp=%cp%;%XMLBEANS_HOME%\build\lib\xercesImpl.jar
 set cp=%cp%;%XMLBEANS_HOME%\build\private\lib\random.jar
 set cp=%cp%;%XMLBEANS_HOME%\build\private\lib\easypo.jar
 
-rem java -ea -Dtreeasserts=true  -Dxbean.rootdir=%XMLBEANS_HOME% -classpath %cp% Random -noquery %*
-    java -ea -Dtreeasserts=false -Dxbean.rootdir=%XMLBEANS_HOME% -classpath %cp% Random -noquery %*
+rem java -Dxmlbeans.ea -Dtreeasserts=true  -Dxbean.rootdir=%XMLBEANS_HOME% -classpath %cp% Random -noquery %*
+    java -Dxmlbeans.ea -Dtreeasserts=false -Dxbean.rootdir=%XMLBEANS_HOME% -classpath %cp% Random -noquery %*
diff --git a/v1/bin/scomp b/v1/bin/scomp
index 27cbeee..f62e806 100755
--- a/v1/bin/scomp
+++ b/v1/bin/scomp
@@ -7,8 +7,12 @@
 
 if [ -e $XMLBEANS_HOME/build/ar/xbean.jar ]; then
     cp=$cp:$XMLBEANS_HOME/build/ar/xbean.jar;
+    cp=$cp:$XMLBEANS_HOME/build/lib/xml-apis.jar;
+    cp=$cp:$XMLBEANS_HOME/build/lib/xercesImpl.jar;
 elif [ -e $XMLBEANS_HOME/lib/xbean.jar ]; then
     cp=$cp:$XMLBEANS_HOME/lib/xbean.jar;
+    cp=$cp:$XMLBEANS_HOME/lib/xml-apis.jar;
+    cp=$cp:$XMLBEANS_HOME/lib/xercesImpl.jar;
 fi
 
 case "`uname`" in
diff --git a/v1/bin/scomp.cmd b/v1/bin/scomp.cmd
index 63fb056..fc4ce18 100644
--- a/v1/bin/scomp.cmd
+++ b/v1/bin/scomp.cmd
@@ -10,9 +10,9 @@
 set cp=
 
 if EXIST %XMLBEANS_HOME%\build\ar\xbean.jar. (
-    set cp=%cp%;%XMLBEANS_HOME%\build\ar\xbean.jar.
+    set cp=%XMLBEANS_HOME%\build\ar\xbean.jar;%XMLBEANS_HOME%\build\lib\xml-apis.jar;%XMLBEANS_HOME%\build\lib\xercesImpl.jar.
 ) else if EXIST %XMLBEANS_HOME%\lib\xbean.jar. (
-    set cp=%cp%;%XMLBEANS_HOME%\lib\xbean.jar.
+    set cp=%XMLBEANS_HOME%\build\lib\xbean.jar;%XMLBEANS_HOME%\lib\xml-apis.jar;%XMLBEANS_HOME%\lib\xercesImpl.jar.
 )
 
 java -classpath %cp% org.apache.xmlbeans.impl.tool.SchemaCompiler %*
diff --git a/v1/bin/scopy.cmd b/v1/bin/scopy.cmd
index 3529a62..dbdf34b 100644
--- a/v1/bin/scopy.cmd
+++ b/v1/bin/scopy.cmd
@@ -10,9 +10,9 @@
 set cp=
 
 if EXIST %XMLBEANS_HOME%\build\ar\xbean.jar. (
-    set cp=%cp%;%XMLBEANS_HOME%\build\ar\xbean.jar.
+    set cp=%XMLBEANS_HOME%\build\ar\xbean.jar;%XMLBEANS_HOME%\build\lib\xml-apis.jar;%XMLBEANS_HOME%\build\lib\xercesImpl.jar.
 ) else if EXIST %XMLBEANS_HOME%\lib\xbean.jar. (
-    set cp=%cp%;%XMLBEANS_HOME%\lib\xbean.jar.
+    set cp=%XMLBEANS_HOME%\build\lib\xbean.jar;%XMLBEANS_HOME%\lib\xml-apis.jar;%XMLBEANS_HOME%\lib\xercesImpl.jar.
 )
 
 java -classpath %cp% org.apache.xmlbeans.impl.tool.SchemaCopy %*
diff --git a/v1/bin/sdownload.cmd b/v1/bin/sdownload.cmd
index 1bb3e2b..1216957 100644
--- a/v1/bin/sdownload.cmd
+++ b/v1/bin/sdownload.cmd
@@ -10,9 +10,9 @@
 set cp=
 
 if EXIST %XMLBEANS_HOME%\build\ar\xbean.jar. (
-    set cp=%cp%;%XMLBEANS_HOME%\build\ar\xbean.jar.
+    set cp=%XMLBEANS_HOME%\build\ar\xbean.jar;%XMLBEANS_HOME%\build\lib\xml-apis.jar;%XMLBEANS_HOME%\build\lib\xercesImpl.jar.
 ) else if EXIST %XMLBEANS_HOME%\lib\xbean.jar. (
-    set cp=%cp%;%XMLBEANS_HOME%\lib\xbean.jar.
+    set cp=%XMLBEANS_HOME%\build\lib\xbean.jar;%XMLBEANS_HOME%\lib\xml-apis.jar;%XMLBEANS_HOME%\lib\xercesImpl.jar.
 )
 
 java -classpath %cp% org.apache.xmlbeans.impl.tool.SchemaResourceManager %*
diff --git a/v1/bin/sfactor.cmd b/v1/bin/sfactor.cmd
index 0334e32..379d55a 100644
--- a/v1/bin/sfactor.cmd
+++ b/v1/bin/sfactor.cmd
@@ -10,9 +10,9 @@
 set cp=
 
 if EXIST %XMLBEANS_HOME%\build\ar\xbean.jar. (
-    set cp=%cp%;%XMLBEANS_HOME%\build\ar\xbean.jar.
+    set cp=%XMLBEANS_HOME%\build\ar\xbean.jar;%XMLBEANS_HOME%\build\lib\xml-apis.jar;%XMLBEANS_HOME%\build\lib\xercesImpl.jar.
 ) else if EXIST %XMLBEANS_HOME%\lib\xbean.jar. (
-    set cp=%cp%;%XMLBEANS_HOME%\lib\xbean.jar.
+    set cp=%XMLBEANS_HOME%\build\lib\xbean.jar;%XMLBEANS_HOME%\lib\xml-apis.jar;%XMLBEANS_HOME%\lib\xercesImpl.jar.
 )
 
 java -classpath %cp% org.apache.xmlbeans.impl.tool.FactorImports %*
diff --git a/v1/bin/validate b/v1/bin/validate
index 9589dc9..2535583 100755
--- a/v1/bin/validate
+++ b/v1/bin/validate
@@ -8,8 +8,12 @@
 
 if [ -e $XMLBEANS_HOME/build/ar/xbean.jar ]; then
     cp=$cp:$XMLBEANS_HOME/build/ar/xbean.jar;
+    cp=$cp:$XMLBEANS_HOME/build/lib/xml-apis.jar;
+    cp=$cp:$XMLBEANS_HOME/build/lib/xercesImpl.jar;
 elif [ -e $XMLBEANS_HOME/lib/xbean.jar ]; then
     cp=$cp:$XMLBEANS_HOME/lib/xbean.jar;
+    cp=$cp:$XMLBEANS_HOME/lib/xml-apis.jar;
+    cp=$cp:$XMLBEANS_HOME/lib/xercesImpl.jar;
 fi
 
 case "`uname`" in
diff --git a/v1/bin/validate.cmd b/v1/bin/validate.cmd
index b03dd41..06d5a68 100644
--- a/v1/bin/validate.cmd
+++ b/v1/bin/validate.cmd
@@ -10,9 +10,9 @@
 set cp=
 
 if EXIST %XMLBEANS_HOME%\build\ar\xbean.jar. (
-    set cp=%cp%;%XMLBEANS_HOME%\build\ar\xbean.jar.
+    set cp=%XMLBEANS_HOME%\build\ar\xbean.jar;%XMLBEANS_HOME%\build\lib\xml-apis.jar;%XMLBEANS_HOME%\build\lib\xercesImpl.jar.
 ) else if EXIST %XMLBEANS_HOME%\lib\xbean.jar. (
-    set cp=%cp%;%XMLBEANS_HOME%\lib\xbean.jar.
+    set cp=%XMLBEANS_HOME%\build\lib\xbean.jar;%XMLBEANS_HOME%\lib\xml-apis.jar;%XMLBEANS_HOME%\lib\xercesImpl.jar.
 )
 
 java -classpath %cp% org.apache.xmlbeans.impl.tool.InstanceValidator %*
diff --git a/v1/bin/xpretty.cmd b/v1/bin/xpretty.cmd
index 01fe13b..d592033 100644
--- a/v1/bin/xpretty.cmd
+++ b/v1/bin/xpretty.cmd
@@ -8,9 +8,9 @@
 set cp=
 
 if EXIST %XMLBEANS_HOME%\build\ar\xbean.jar. (
-    set cp=%cp%;%XMLBEANS_HOME%\build\ar\xbean.jar.
+    set cp=%XMLBEANS_HOME%\build\ar\xbean.jar;%XMLBEANS_HOME%\build\lib\xml-apis.jar;%XMLBEANS_HOME%\build\lib\xercesImpl.jar.
 ) else if EXIST %XMLBEANS_HOME%\lib\xbean.jar. (
-    set cp=%cp%;%XMLBEANS_HOME%\lib\xbean.jar.
+    set cp=%XMLBEANS_HOME%\build\lib\xbean.jar;%XMLBEANS_HOME%\lib\xml-apis.jar;%XMLBEANS_HOME%\lib\xercesImpl.jar.
 )
 
 java -classpath %cp% org.apache.xmlbeans.impl.tool.PrettyPrinter %*
diff --git a/v1/bin/xsdtree.cmd b/v1/bin/xsdtree.cmd
index 426202c..0e08fba 100644
--- a/v1/bin/xsdtree.cmd
+++ b/v1/bin/xsdtree.cmd
@@ -8,9 +8,9 @@
 set cp=
 
 if EXIST %XMLBEANS_HOME%\build\ar\xbean.jar. (
-    set cp=%cp%;%XMLBEANS_HOME%\build\ar\xbean.jar.
+    set cp=%XMLBEANS_HOME%\build\ar\xbean.jar;%XMLBEANS_HOME%\build\lib\xml-apis.jar;%XMLBEANS_HOME%\build\lib\xercesImpl.jar.
 ) else if EXIST %XMLBEANS_HOME%\lib\xbean.jar. (
-    set cp=%cp%;%XMLBEANS_HOME%\lib\xbean.jar.
+    set cp=%XMLBEANS_HOME%\build\lib\xbean.jar;%XMLBEANS_HOME%\lib\xml-apis.jar;%XMLBEANS_HOME%\lib\xercesImpl.jar.
 )
 
 java -classpath %cp% org.apache.xmlbeans.impl.tool.TypeHierarchyPrinter %*
diff --git a/v1/bin/xstc.cmd b/v1/bin/xstc.cmd
index 33b8e7b..cab5a70 100644
--- a/v1/bin/xstc.cmd
+++ b/v1/bin/xstc.cmd
@@ -8,9 +8,9 @@
 set cp=
 
 if EXIST %XMLBEANS_HOME%\build\ar\xbean.jar. (
-    set cp=%cp%;%XMLBEANS_HOME%\build\ar\xbean.jar.
+    set cp=%XMLBEANS_HOME%\build\ar\xbean.jar;%XMLBEANS_HOME%\build\lib\xml-apis.jar;%XMLBEANS_HOME%\build\lib\xercesImpl.jar.
 ) else if EXIST %XMLBEANS_HOME%\lib\xbean.jar. (
-    set cp=%cp%;%XMLBEANS_HOME%\lib\xbean.jar.
+    set cp=%XMLBEANS_HOME%\build\lib\xbean.jar;%XMLBEANS_HOME%\lib\xml-apis.jar;%XMLBEANS_HOME%\lib\xercesImpl.jar.
 )
 
 java -classpath %cp% org.apache.xmlbeans.impl.tool.XSTCTester %*
diff --git a/v1/build.xml b/v1/build.xml
index b5f6f8d..bb1c46e 100644
--- a/v1/build.xml
+++ b/v1/build.xml
@@ -13,7 +13,7 @@
      limitations under the License. -->
 <project name="Xbean" default="default" basedir=".">
 
-  <property name="build.compiler" value="javac1.4"/>
+  <property name="build.compiler" value="javac1.3"/>
   <property name="product.version" value="1.0.3"/>
 
   <target name="usage">
@@ -56,10 +56,12 @@
        <java classname="Random" fork="true" failonerror="true">
           <classpath>
             <pathelement location="build/ar/xbean.jar"/>
+            <pathelement location="build/lib/xml-apis.jar"/>
+            <pathelement location="build/lib/xercesImpl.jar"/>
             <pathelement location="build/private/lib/easypo.jar"/>
             <pathelement location="build/private/lib/random.jar"/>
           </classpath>
-         <jvmarg value="-ea"/>
+         <jvmarg value="-Dxmlbeans.ea"/>
          <arg line="-seed 0 -i 20 -noquery"/>
        </java>
 
@@ -67,12 +69,14 @@
     <echo message="Running xbean product drt tests"/>
     <echo message="JUnit output being sent to build/test/output/drt-product.txt"/>
     <junit fork="yes" printsummary="yes" haltonfailure="yes" showoutput="yes">
-      <jvmarg value="-ea"/>
+      <jvmarg value="-Dxmlbeans.ea"/>
       <sysproperty key="xbean.rootdir" value="${basedir}"/>
       <sysproperty key="treeasserts" value="true"/>
       <classpath>
         <pathelement location="external/lib/junit.jar"/>
         <pathelement location="build/ar/xbean.jar"/>
+        <pathelement location="build/lib/xml-apis.jar"/>
+        <pathelement location="build/lib/xercesImpl.jar"/>
         <pathelement location="build/private/lib/drt.jar"/>
         <pathelement location="build/private/lib/easypo.jar"/>
         <pathelement location="build/private/lib/schemas.jar"/>
@@ -102,7 +106,7 @@
     <target name="extensionsTest" depends="extensions.compile">
       <echo message="JUnit output being sent to build/test/output/drt-extensions.txt"/>
       <junit fork="yes" printsummary="yes" haltonfailure="yes" showoutput="yes">
-        <jvmarg value="-ea"/>
+        <jvmarg value="-Dxmlbeans.ea"/>
         <classpath>
           <pathelement location="build/ar/xbean.jar" />
           <pathelement location="external/lib/junit.jar"/>
@@ -125,47 +129,57 @@
 
     <target name="build.simpleBeans" unless="simpleBeans.notRequired" depends="simpleBeans.check">
       <java classname="${schema_compiler}" fork="true" failonerror="true">
-        <jvmarg value="-ea"/>
+        <jvmarg value="-Dxmlbeans.ea"/>
         <classpath>
           <pathelement location="build/ar/xbean.jar" />
           <pathelement location="build/test/extensions"/>
+          <pathelement location="build/lib/xml-apis.jar"/>
+          <pathelement location="build/lib/xercesImpl.jar"/>
         </classpath>
         <arg line="-out build/private/lib/fixedAttrBean.jar test/src/extensions/fixedAttrBean/po.xsd"/>
       </java>
 
       <java classname="${schema_compiler}" fork="true" failonerror="true">
-        <jvmarg value="-ea"/>
+        <jvmarg value="-Dxmlbeans.ea"/>
         <classpath>
           <pathelement location="build/ar/xbean.jar" />
           <pathelement location="build/test/extensions"/>
+          <pathelement location="build/lib/xml-apis.jar"/>
+          <pathelement location="build/lib/xercesImpl.jar"/>
         </classpath>
         <arg line="-out build/private/lib/averageCase.jar test/src/extensions/averageCase/po.xsd"/>
       </java>
 
       <java classname="${schema_compiler}" fork="true" failonerror="true">
-        <jvmarg value="-ea"/>
+        <jvmarg value="-Dxmlbeans.ea"/>
         <classpath>
           <pathelement location="build/ar/xbean.jar" />
           <pathelement location="build/test/extensions"/>
+          <pathelement location="build/lib/xml-apis.jar"/>
+          <pathelement location="build/lib/xercesImpl.jar"/>
         </classpath>
         <arg line="-out build/private/lib/multInterfaces.jar test/src/extensions/multInterfaces/po.xsd"/>
       </java>
 
       <!-- **Pre/Post Handlers -->
       <java classname="${schema_compiler}" fork="true" failonerror="true">
-        <jvmarg value="-ea"/>
+        <jvmarg value="-Dxmlbeans.ea"/>
         <classpath>
           <pathelement location="build/ar/xbean.jar" />
           <pathelement location="build/test/extensions"/>
+          <pathelement location="build/lib/xml-apis.jar"/>
+          <pathelement location="build/lib/xercesImpl.jar"/>
         </classpath>
         <arg line="-out build/private/lib/readOnlyBean.jar test/src/extensions/prePostFeature/readOnlyBean/po.xsd"/>
       </java>
 
       <java classname="${schema_compiler}" fork="true" failonerror="true">
-        <jvmarg value="-ea"/>
+        <jvmarg value="-Dxmlbeans.ea"/>
         <classpath>
           <pathelement location="build/ar/xbean.jar" />
           <pathelement location="build/test/extensions"/>
+          <pathelement location="build/lib/xml-apis.jar"/>
+          <pathelement location="build/lib/xercesImpl.jar"/>
         </classpath>
         <arg line="-out build/private/lib/ValueRestriction.jar test/src/extensions/prePostFeature/ValueRestriction/company.xsd"/>
       </java>
@@ -181,56 +195,68 @@
       </javac>
 
       <java classname="${schema_compiler}" fork="true" failonerror="true">
-        <jvmarg value="-ea"/>
+        <jvmarg value="-Dxmlbeans.ea"/>
         <classpath>
           <pathelement location="build/ar/xbean.jar" />
           <pathelement location="build/test/extensions"/>
+          <pathelement location="build/lib/xml-apis.jar"/>
+          <pathelement location="build/lib/xercesImpl.jar"/>
         </classpath>
         <arg line="-out build/private/lib/extensions.jar test/src/extensions/myPackage"/>
       </java>
 
       <java classname="${schema_compiler}" fork="true" failonerror="true">
-        <jvmarg value="-ea"/>
+        <jvmarg value="-Dxmlbeans.ea"/>
         <classpath>
           <pathelement location="build/ar/xbean.jar" />
           <pathelement location="build/test/extensions"/>
+          <pathelement location="build/lib/xml-apis.jar"/>
+          <pathelement location="build/lib/xercesImpl.jar"/>
         </classpath>
         <arg line="-out build/private/lib/fixedAttrBean.jar test/src/extensions/fixedAttrBean"/>
       </java>
 
       <java classname="${schema_compiler}" fork="true" failonerror="true">
-        <jvmarg value="-ea"/>
+        <jvmarg value="-Dxmlbeans.ea"/>
         <classpath>
           <pathelement location="build/ar/xbean.jar" />
           <pathelement location="build/test/extensions"/>
+          <pathelement location="build/lib/xml-apis.jar"/>
+          <pathelement location="build/lib/xercesImpl.jar"/>
         </classpath>
         <arg line="-out build/private/lib/averageCase.jar test/src/extensions/averageCase"/>
       </java>
 
       <java classname="${schema_compiler}" fork="true" failonerror="true">
-        <jvmarg value="-ea"/>
+        <jvmarg value="-Dxmlbeans.ea"/>
         <classpath>
           <pathelement location="build/ar/xbean.jar" />
           <pathelement location="build/test/extensions"/>
+          <pathelement location="build/lib/xml-apis.jar"/>
+          <pathelement location="build/lib/xercesImpl.jar"/>
         </classpath>
         <arg line="-out build/private/lib/multInterfaces.jar test/src/extensions/multInterfaces"/>
       </java>
       <!--Pre Post Feature -->
 
       <java classname="${schema_compiler}" fork="true" failonerror="true">
-        <jvmarg value="-ea"/>
+        <jvmarg value="-Dxmlbeans.ea"/>
         <classpath>
           <pathelement location="build/ar/xbean.jar" />
           <pathelement location="build/test/extensions"/>
+          <pathelement location="build/lib/xml-apis.jar"/>
+          <pathelement location="build/lib/xercesImpl.jar"/>
         </classpath>
         <arg line="-out build/private/lib/readOnlyBean.jar test/src/extensions/prePostFeature/readOnlyBean"/>
       </java>
 
       <java classname="${schema_compiler}" fork="true" failonerror="true">
-        <jvmarg value="-ea"/>
+        <jvmarg value="-Dxmlbeans.ea"/>
         <classpath>
           <pathelement location="build/ar/xbean.jar" />
           <pathelement location="build/test/extensions"/>
+          <pathelement location="build/lib/xml-apis.jar"/>
+          <pathelement location="build/lib/xercesImpl.jar"/>
         </classpath>
         <arg line="-out build/private/lib/ValueRestriction.jar test/src/extensions/prePostFeature/ValueRestriction"/>
       </java>
@@ -278,7 +304,7 @@
     <!-- compare the contents of the first jar to the contents of the second jar -->
     <antcall target="zipcompare.classes" inheritAll="false"/>
     <java classname="zipcompare.ZipCompare"
-          classpath="build/private/classes/zipcompare"
+          classpath="build/private/classes/zipcompare:build/classes/common"
           fork="true"
           failonerror="true">
       <arg line="build/ar/xbean.jar build/private/lib/oldxbean.jar"/>
@@ -303,10 +329,11 @@
 
   <!-- zipcompare (for checking bootstrap) ============================ -->
 
-  <target name="zipcompare.classes">
+  <target name="zipcompare.classes" depends="common.classes">
     <mkdir dir="build/private/classes/zipcompare"/>
     <javac srcdir="src/zipcompare"
            destdir="build/private/classes/zipcompare"
+           classpath="build/classes/common"
            debug="on"/>
   </target>
 
@@ -315,6 +342,7 @@
   <path id="test.compile.path">
     <pathelement location="external/lib/junit.jar"/>
     <pathelement location="build/ar/xbean.jar"/>
+    <pathelement location="build/lib/xml-apis.jar"/>
     <pathelement location="build/private/lib/easypo.jar"/>
     <pathelement location="build/private/lib/ericschema.jar"/>
     <pathelement location="build/private/lib/schemas.jar"/>
@@ -328,6 +356,7 @@
 
   <path id="test.run.path">
     <pathelement location="build/ar/xbean.jar"/>
+    <pathelement location="build/lib/xml-apis.jar"/>
     <pathelement location="external/lib/junit.jar"/>
   </path>
 
@@ -340,7 +369,7 @@
        srcdir="test/src/drt"
        destdir="build/private/classes/drt"
        classpathref="test.compile.path"
-       source="1.4"
+       source="1.3"
        debug="on"/>
   </target>
 
@@ -352,6 +381,8 @@
 
   <path id="scomp.run.path">
     <pathelement location="build/lib/xbean.jar"/>
+    <pathelement location="build/lib/xml-apis.jar"/>
+    <pathelement location="build/lib/xercesImpl.jar"/>
   </path>
 
   <target name="stsschema.check">
@@ -363,7 +394,7 @@
 
   <target name="stsschema.jar" depends="stsschema.check, dirs, xbean" unless="stsschema.notRequired">
     <java classname="${schema_compiler}" classpathref="scomp.run.path" fork="true" failonerror="true">
-      <jvmarg value="-ea"/>
+      <jvmarg value="-Dxmlbeans.ea"/>
       <arg line="-out build/private/lib/stsschema.jar test/src/stsschema"/>
     </java>
   </target>
@@ -372,11 +403,12 @@
 
   <target name="soaptest.classes" depends="dirs, stsschema.jar">
     <mkdir dir="build/private/classes/soaptest"/>
-    <javac srcdir="test/src/soaptest" destdir="build/private/classes/soaptest" source="1.4" debug="on">
+    <javac srcdir="test/src/soaptest" destdir="build/private/classes/soaptest" source="1.3" debug="on">
       <classpath>
         <pathelement location="external/lib/jdom.jar"/>
         <pathelement location="external/lib/junit.jar"/>
         <pathelement location="build/ar/xbean.jar"/>
+        <pathelement location="build/lib/xml-apis.jar"/>
         <pathelement location="build/private/lib/stsschema.jar"/>
       </classpath>
     </javac>
@@ -395,7 +427,7 @@
        srcdir="test/src/erictest"
        destdir="build/private/classes/erictest"
        classpathref="test.compile.path"
-       source="1.4"
+       source="1.3"
        debug="on"/>
   </target>
 
@@ -411,7 +443,7 @@
        srcdir="test/src/random"
        destdir="build/private/classes/random"
        classpathref="test.compile.path"
-       source="1.4"
+       source="1.3"
        debug="on"/>
   </target>
 
@@ -423,7 +455,7 @@
 
   <target name="teststore.classes" depends="dirs">
     <mkdir dir="build/private/classes/teststore"/>
-    <javac srcdir="test/src/teststore" destdir="build/private/classes/teststore" source="1.4" debug="on">
+    <javac srcdir="test/src/teststore" destdir="build/private/classes/teststore" source="1.3" debug="on">
       <classpath>
         <pathelement location="build/private/classes/simpletypes"/>
         <pathelement location="build/private/classes/xmlcomp"/>
@@ -450,7 +482,7 @@
 
   <target name="simpletypes.jar" depends="simpletypes.check, dirs" unless="simpletype.notRequired">
     <java classname="${schema_compiler}" classpathref="scomp.run.path" fork="true" failonerror="true">
-      <jvmarg value="-ea"/>
+      <jvmarg value="-Dxmlbeans.ea"/>
       <arg line="-name schema.test.simple -out build/private/lib/simpletypes.jar test/cases/schema/simple"/>
     </java>
   </target>
@@ -466,7 +498,7 @@
 
   <target name="easypo.jar" depends="easypo.check, dirs, xbean" unless="easypo.notRequired">
     <java classname="${schema_compiler}" classpathref="scomp.run.path" fork="true" failonerror="true">
-      <jvmarg value="-ea"/>
+      <jvmarg value="-Dxmlbeans.ea"/>
       <arg line="-out build/private/lib/easypo.jar test/src/easypo"/>
     </java>
   </target>
@@ -480,7 +512,7 @@
   </target>
   <target name="numerals.jar" depends="numerals.check, dirs, xbean" unless="numerals.notRequired">
     <java classname="${schema_compiler}" classpathref="scomp.run.path" fork="true" failonerror="true">
-      <jvmarg value="-ea"/>
+      <jvmarg value="-Dxmlbeans.ea"/>
       <arg line="-out build/private/lib/numerals.jar test/src/numerals"/>
     </java>
   </target>
@@ -496,7 +528,7 @@
 
   <target name="schemas.jar" depends="schemas.check, dirs, xbean" unless="schemas.notRequired">
     <java classname="${schema_compiler}" classpathref="scomp.run.path" fork="true" failonerror="true">
-      <jvmarg value="-ea"/>
+      <jvmarg value="-Dxmlbeans.ea"/>
       <arg line="-out build/private/lib/schemas.jar test/src/schemas"/>
     </java>
   </target>
@@ -512,7 +544,7 @@
 
   <target name="ericschema.jar" depends="ericschema.check, dirs, xbean" unless="ericschema.notRequired">
     <java classname="${schema_compiler}" classpathref="scomp.run.path" fork="true" failonerror="true">
-      <jvmarg value="-ea"/>
+      <jvmarg value="-Dxmlbeans.ea"/>
       <arg line="-src build/private/src -out build/private/lib/ericschema.jar test/src/ericschema"/>
     </java>
   </target>
@@ -528,7 +560,7 @@
 
   <target name="enumtest.jar" depends="enumtest.check, dirs, xbean" unless="enumtest.notRequired">
     <java classname="${schema_compiler}" classpathref="scomp.run.path" fork="true" failonerror="true">
-      <jvmarg value="-ea"/>
+      <jvmarg value="-Dxmlbeans.ea"/>
       <arg line="-out build/private/lib/enumtest.jar test/src/enumtest"/>
     </java>
   </target>
@@ -544,7 +576,7 @@
 
   <target name="xstypes.jar" depends="xstypes.check, dirs, xbean" unless="xstypes.notRequired">
     <java classname="${schema_compiler}" classpathref="scomp.run.path" fork="true" failonerror="true">
-      <jvmarg value="-ea"/>
+      <jvmarg value="-Dxmlbeans.ea"/>
       <arg line="-out build/private/lib/xstypes.jar test/src/xstypes"/>
     </java>
   </target>
@@ -557,10 +589,10 @@
     <property name="docs.dir" value="build/docs"/>
     <delete dir="${docs.dir}"/>
     <mkdir dir="${docs.dir}"/>
-    <javadoc packagenames="*" sourcepath="src/xmlpublic" classpath="${javadoc.path}" destdir="${docs.dir}/reference" windowtitle="XMLBeans Documentation" source="1.4" stylesheetfile="docs/stylesheet.css">
+    <javadoc packagenames="*" sourcepath="src/xmlpublic" classpath="${javadoc.path}" destdir="${docs.dir}/reference" windowtitle="XMLBeans Documentation" source="1.3" stylesheetfile="docs/stylesheet.css">
       <link href="http://xml.apache.org/xmlbeans/docs/reference/index.html"/>
-      <link href="http://java.sun.com/j2se/1.4.2/docs/api/"/>
-      <link href="http://java.sun.com/j2ee/1.4/docs/api/"/>
+      <link href="http://java.sun.com/j2se/1.3.1/docs/api/"/>
+      <link href="http://java.sun.com/j2ee/1.3/docs/api/"/>
       <link href="http://xml.apache.org/xerces-j/apiDocs/"/>
       <classpath>
         <pathelement location="build/ar/xbean.jar"/>
@@ -583,7 +615,7 @@
       srcdir="test/src/streamtest"
       destdir="build/private/classes/streamtest"
       classpathref="test.compile.path"
-      source="1.4"
+      source="1.3"
       debug="on"/>
   </target>
 
@@ -600,7 +632,7 @@
     <java classname="streamtest.XmlStreamConformance"
           classpathref="run.streamconf.path"
           fork="true">
-      <jvmarg value="-ea"/>
+      <jvmarg value="-Dxmlbeans.ea"/>
       <!--arg line="test/cases/streamconf/small.xml" /-->
       <arg line="test/cases/streamconf/dtd.xml" />
     </java>
@@ -631,6 +663,8 @@
 
      <mkdir dir="build/private/xmlbeans-${product.version}/lib"/>
      <copy todir="build/private/xmlbeans-${product.version}/lib" file="build/ar/xbean.jar"/>
+     <copy todir="build/private/xmlbeans-${product.version}/lib" file="external/lib/xml-apis.jar"/>
+     <copy todir="build/private/xmlbeans-${product.version}/lib" file="external/lib/xercesImpl.jar"/>
      <copy todir="build/private/xmlbeans-${product.version}/lib" file="external/lib/jaxen-1.1-beta-2.jar"/>
      <copy todir="build/private/xmlbeans-${product.version}/lib" file="build/lib/xbean_xpath.jar"/>
 
@@ -701,7 +735,7 @@
   <!-- previously in xbean.xml -->
 
   <target name="xbean.jar"
-        depends="dirs, xmlpublic.classes, typestore.classes,
+        depends="dirs, xml-apis.jar, xercesImpl.jar, xmlpublic.classes, typestore.classes,
                  common.classes, typeimpl.classes, xmlcomp.classes,
                  xmlstore.classes,
                  oldxbean.jar, xsdschema.classes,
@@ -736,7 +770,7 @@
 
   <target name="xmlpublic.classes" depends="dirs, xmlinputstream.classes">
     <mkdir dir="build/classes/xmlpublic"/>
-    <javac srcdir="src/xmlpublic" destdir="build/classes/xmlpublic" source="1.4" debug="on">
+    <javac srcdir="src/xmlpublic" destdir="build/classes/xmlpublic" source="1.3" debug="on">
       <classpath>
         <pathelement location="build/classes/xmlinputstream"/>
       </classpath>
@@ -756,7 +790,7 @@
 
   <target name="typestore.classes" depends="dirs, xmlpublic.classes, common.classes, xmlinputstream.classes">
     <mkdir dir="build/classes/typestore"/>
-    <javac srcdir="src/typestore" destdir="build/classes/typestore" source="1.4" debug="on">
+    <javac srcdir="src/typestore" destdir="build/classes/typestore" source="1.3" debug="on">
       <classpath>
         <pathelement location="build/classes/xmlinputstream"/>
         <pathelement location="build/classes/xmlpublic"/>
@@ -770,11 +804,14 @@
 
   <target name="common.classes" depends="dirs, xmlpublic.jar, xmlinputstream.classes">
     <mkdir dir="build/classes/common"/>
-    <javac srcdir="src/common" destdir="build/classes/common" source="1.4" debug="on">
+    <javac destdir="build/classes/common" source="1.3" debug="on">
       <classpath>
         <pathelement location="build/classes/xmlinputstream"/>
         <pathelement location="build/lib/xmlpublic.jar"/>
+        <pathelement location="build/lib/xml-apis.jar"/>
       </classpath>
+      <src path="src/common"/>
+      <src path="src/typeimpl/org/apache/xmlbeans/impl/regex"/>
     </javac>
 
   </target>
@@ -783,7 +820,7 @@
 
   <target name="typeimpl.classes" depends="dirs, repackage.classes, xmlpublic.classes, typestore.classes, xsdschema.classes, configschema.classes, toolschema.classes">
     <mkdir dir="build/classes/typeimpl"/>
-    <javac destdir="build/classes/typeimpl" source="1.4" debug="on">
+    <javac destdir="build/classes/typeimpl" source="1.3" debug="on">
       <classpath>
         <pathelement location="build/classes/xmlinputstream"/>
         <pathelement location="build/classes/common"/>
@@ -793,6 +830,7 @@
         <pathelement location="build/classes/xmlconfig"/>
         <pathelement location="build/classes/configschema"/>
         <pathelement location="build/classes/xsdschema"/>
+        <pathelement location="build/lib/xml-apis.jar"/>
       </classpath>
 
         <src path="src/typeimpl"/>
@@ -816,7 +854,7 @@
 
   <target name="xmlcomp.classes" depends="dirs, repackage.classes, typeimpl.classes, xmlpublic.classes, typestore.classes">
     <mkdir dir="build/classes/xmlcomp"/>
-    <javac srcdir="src/xmlcomp" destdir="build/classes/xmlcomp" source="1.4" debug="on">
+    <javac srcdir="src/xmlcomp" destdir="build/classes/xmlcomp" source="1.3" debug="on">
       <classpath>
         <pathelement location="build/classes/xmlinputstream"/>
         <pathelement location="build/classes/xmlpublic"/>
@@ -827,6 +865,7 @@
         <pathelement location="build/classes/configschema"/>
         <pathelement location="build/classes/toolschema"/>
         <pathelement location="build/classes/xsdschema"/>
+        <pathelement location="build/lib/xml-apis.jar"/>
       </classpath>
     </javac>
 
@@ -837,12 +876,13 @@
   <target name="xmlstore.classes"
         depends="dirs, common.classes, typestore.classes, xmlpublic.classes">
     <mkdir dir="build/classes/xmlstore"/>
-    <javac srcdir="src/xmlstore" destdir="build/classes/xmlstore" source="1.4" debug="on">
+    <javac srcdir="src/xmlstore" destdir="build/classes/xmlstore" source="1.3" debug="on">
       <classpath id="xmlstore.compile.path">
         <pathelement location="build/classes/xmlinputstream"/>
         <pathelement location="build/classes/typestore"/>
         <pathelement location="build/classes/xmlpublic"/>
         <pathelement location="build/classes/common"/>
+        <pathelement location="build/lib/xml-apis.jar"/>
       </classpath>
     </javac>
 
@@ -858,6 +898,8 @@
 
   <path id="bootstrap.run.path">
     <pathelement location="build/private/lib/oldxbean.jar"/>
+    <pathelement location="build/lib/xml-apis.jar"/>
+    <pathelement location="build/lib/xercesImpl.jar"/>
   </path>
 
   <path id="bootstrap.compile.path">
@@ -885,7 +927,7 @@
     <delete dir="build/classes/xsdschema"/>
     <delete dir="build/src/xsdschema"/>
     <java classname="${bootstrap_schema_compiler}" classpathref="bootstrap.run.path" fork="true" failonerror="true">
-      <jvmarg value="-ea"/>
+      <jvmarg value="-Dxmlbeans.ea"/>
       <arg line="${repackage_arg} -name sXMLSCHEMA -cp ${xsdschema.compile.path} -srconly -d build/classes/xsdschema -src build/src/xsdschema src/xsdschema/schema"/>
     </java>
   </target>
@@ -907,7 +949,7 @@
     <delete dir="build/classes/xmlschema"/>
     <delete dir="build/src/xmlschema"/>
     <java classname="${bootstrap_schema_compiler}" classpathref="bootstrap.run.path" fork="true" failonerror="true">
-      <jvmarg value="-ea"/>
+      <jvmarg value="-Dxmlbeans.ea"/>
       <arg line="${repackage_arg} -name sXMLLANG -d build/classes/xmlschema -src build/src/xmlschema -srconly src/xmlschema/schema"/>
     </java>
   </target>
@@ -916,7 +958,7 @@
 
   <target name="xmlconfig.classes" depends="dirs, xmlpublic.jar, configschema.classes">
     <mkdir dir="build/classes/xmlconfig"/>
-    <javac srcdir="src/xmlconfig" destdir="build/classes/xmlconfig" source="1.4" debug="on">
+    <javac srcdir="src/xmlconfig" destdir="build/classes/xmlconfig" source="1.3" debug="on">
       <classpath>
         <pathelement location="build/lib/xmlpublic.jar"/>
         <pathelement location="build/classes/configschema"/>
@@ -941,7 +983,7 @@
   <target name="configschema.classes" depends="configschema.check, xmlpublic.classes, oldxbean.jar" unless="configschema.notRequired">
     <delete dir="build/classes/configschema"/>
     <java classname="${bootstrap_schema_compiler}" classpathref="bootstrap.run.path" fork="true" failonerror="true">
-      <jvmarg value="-ea"/>
+      <jvmarg value="-Dxmlbeans.ea"/>
       <arg line="${repackage_arg} -name sXMLCONFIG -srconly -src build/src/configschema -d build/classes/configschema src/configschema/schema"/>
     </java>
   </target>
@@ -963,7 +1005,7 @@
     <delete dir="build/classes/toolschema"/>
     <mkdir dir="build/src/toolschema"/>
     <java classname="${bootstrap_schema_compiler}" classpathref="bootstrap.run.path" fork="true" failonerror="true">
-      <jvmarg value="-ea"/>
+      <jvmarg value="-Dxmlbeans.ea"/>
       <arg line="${repackage_arg} -name sXMLTOOLS -srconly -src build/src/toolschema -d build/classes/toolschema src/toolschema"/>
     </java>
   </target>
@@ -982,6 +1024,7 @@
             <arg value="${replacement}"/>
             <classpath>
                 <pathelement location="build/classes/repackage"/>
+                <pathelement location="build/classes/common"/>
             </classpath>
         </java>
     </target>
@@ -1017,6 +1060,7 @@
         <java classname="repackage.Repackage" fork="true" failonerror="true">
             <classpath>
                 <pathelement location="build/classes/repackage"/>
+                <pathelement location="build/classes/common"/>
             </classpath>
             <arg line="${new_repackage_arg}"/>
         </java>
@@ -1044,7 +1088,34 @@
 
     <target name="repackage.classes">
         <mkdir dir="build/classes/repackage"/>
-        <javac srcdir="src/repackage" destdir="build/classes/repackage" source="1.4" debug="on"/>
+        <javac srcdir="src/repackage" destdir="build/classes/repackage" source="1.3" debug="on" classpath="build/classes/common"/>
+    </target>
+
+
+    <target name="check.xml-apis.jar">
+        <condition property="xml-apis.jar.exists">
+            <available file="build/lib/xml-apis.jar"/>
+        </condition>
+    </target>
+
+    <target name="xml-apis.jar" depends="check.xml-apis.jar, dirs" unless="xml-apis.jar.exists">
+        <get dest="external/lib/xml-apis-1.0.b2.jar"
+            src="http://www.ibiblio.org/maven/xml-apis/jars/xml-apis-1.0.b2.jar"
+            verbose="true" usetimestamp="true" ignoreerrors="true"/>
+        <copy file="external/lib/xml-apis-1.0.b2.jar" tofile="build/lib/xml-apis.jar" />
+    </target>
+
+    <target name="check.xercesImpl.jar">
+        <condition property="xercesImpl.jar.exists">
+            <available file="build/lib/xercesImpl.jar"/>
+        </condition>
+    </target>
+
+    <target name="xercesImpl.jar" depends="check.xercesImpl.jar, dirs" unless="xercesImpl.jar.exists">
+        <get dest="external/lib/xercesImpl-2.6.2.jar"
+            src="http://www.ibiblio.org/maven/xerces/jars/xercesImpl-2.6.2.jar"
+            verbose="true" usetimestamp="true" ignoreerrors="true"/>
+        <copy file="external/lib/xercesImpl-2.6.2.jar" tofile="build/lib/xercesImpl.jar" />
     </target>
 
    <target name="check.jaxen.jar">
@@ -1054,7 +1125,7 @@
    </target>
 
    <target name="jaxen.jar" depends="check.jaxen.jar, dirs" unless="jaxen.jar.exists">
-     <!--get dest="build/lib/jaxen.jar"
+     <!--get dest="external/lib/jaxen.jar"
           src="http://www.ibiblio.org/maven/jaxen/jars/jaxen-1.1-beta-2.jar"
           verbose="true" usetimestamp="true" ignoreerrors="true"/ -->
      <copy file="external/lib/jaxen-1.1-beta-2.jar" tofile="build/lib/jaxen.jar" />
@@ -1068,7 +1139,7 @@
        srcdir="src/xpath"
        destdir="build/private/classes/xpath"
        classpathref="xpath.compile.path"
-       source="1.4"
+       source="1.3"
        debug="on">
       <classpath id="xpath.compile.path">
           <pathelement location="build/lib/xmlpublic.jar"/>
@@ -1090,7 +1161,7 @@
        srcdir="test/src/xpath"
        destdir="build/private/classes/testxpath"
        classpathref="testxpath.compile.path"
-       source="1.4"
+       source="1.3"
        debug="on">
       <classpath id="testxpath.compile.path">
           <pathelement location="build/lib/xmlpublic.jar"/>
@@ -1109,7 +1180,6 @@
           <pathelement location="build/lib/xbean_xpath.jar"/>
           <pathelement location="build/private/classes/testxpath"/>
       </classpath>
-      <jvmarg value="-da"/>
       <arg line='test/cases/xpath/much_ado.xml "PLAY/ACT/SCENE/SPEECH/SPEAKER"'/>
     </java>
   </target>
diff --git a/v1/external/lib/junit.jar b/v1/external/lib/junit.jar
index 6ee43bb..674d71e 100644
--- a/v1/external/lib/junit.jar
+++ b/v1/external/lib/junit.jar
Binary files differ
diff --git a/v1/external/lib/oldxbean.jar b/v1/external/lib/oldxbean.jar
index ae81b22..460dd33 100644
--- a/v1/external/lib/oldxbean.jar
+++ b/v1/external/lib/oldxbean.jar
Binary files differ
diff --git a/v1/src/common/org/apache/xmlbeans/impl/common/EncodingMap.java b/v1/src/common/org/apache/xmlbeans/impl/common/EncodingMap.java
index 51ff8af..75bbdf6 100644
--- a/v1/src/common/org/apache/xmlbeans/impl/common/EncodingMap.java
+++ b/v1/src/common/org/apache/xmlbeans/impl/common/EncodingMap.java
@@ -15,6 +15,8 @@
 
 package org.apache.xmlbeans.impl.common;
 
+import org.apache.xmlbeans.XmlBeans;
+
 import java.util.HashMap;
 import java.util.Iterator;
 
@@ -38,20 +40,23 @@
     private final static void addMapping (
         String java, String iana, boolean isDefault )
     {
-        assert !_iana_to_java.containsKey( iana );
-        assert java.toUpperCase().equals( java );
-        assert iana.toUpperCase().equals( iana );
-        
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(!_iana_to_java.containsKey( iana ));
+            XmlBeans.assertTrue(java.equalsIgnoreCase( java ));
+        }
+
         _iana_to_java.put( iana, java );
 
         if (isDefault)
         {
-            assert !_java_to_iana.containsKey( java );
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(!_java_to_iana.containsKey( java ));
             _java_to_iana.put( java, iana );
         }
     }
 
-    private final static boolean completeMappings ( )
+    private final static void completeMappings ( )
     {
         HashMap m = new HashMap();
 
@@ -61,10 +66,8 @@
         for ( Iterator i = m.keySet().iterator() ; i.hasNext() ; )
         {
             Object k = i.next();
-            assert _java_to_iana.containsKey( k ): k;
+            XmlBeans.assertTrue(_java_to_iana.containsKey( k ), k.toString());
         }
-
-        return true;
     }
 
     static
@@ -395,6 +398,6 @@
         addMapping( "UNICODELITTLE", "UTF-16LE",               true  );
         addMapping( "UTF8",          "UTF-8",                  true  );
 
-        assert completeMappings();
+        if (XmlBeans.ASSERTS) completeMappings();
     };
 }
diff --git a/v1/src/common/org/apache/xmlbeans/impl/common/GenericXmlInputStream.java b/v1/src/common/org/apache/xmlbeans/impl/common/GenericXmlInputStream.java
index 2804b7e..0bf2380 100644
--- a/v1/src/common/org/apache/xmlbeans/impl/common/GenericXmlInputStream.java
+++ b/v1/src/common/org/apache/xmlbeans/impl/common/GenericXmlInputStream.java
@@ -20,6 +20,7 @@
 import org.apache.xmlbeans.xml.stream.XMLInputStream;
 import org.apache.xmlbeans.xml.stream.XMLName;
 import org.apache.xmlbeans.xml.stream.XMLStreamException;
+import org.apache.xmlbeans.XmlRuntimeException;
 
 public class GenericXmlInputStream implements XMLInputStream
 {
@@ -74,7 +75,7 @@
             }
             catch ( XMLStreamException e )
             {
-                throw new RuntimeException( e );
+                throw new XmlRuntimeException( e );
             }
             
             _master._initialized = true;
diff --git a/v1/src/common/org/apache/xmlbeans/impl/common/IOUtil.java b/v1/src/common/org/apache/xmlbeans/impl/common/IOUtil.java
index fe79ca0..acd9335 100644
--- a/v1/src/common/org/apache/xmlbeans/impl/common/IOUtil.java
+++ b/v1/src/common/org/apache/xmlbeans/impl/common/IOUtil.java
@@ -19,35 +19,15 @@
 import java.io.OutputStream;
 import java.io.IOException;
 import java.io.File;
-import java.io.FileInputStream;
 import java.io.FileOutputStream;
-import java.net.URI;
-import java.nio.channels.FileChannel;
+import java.net.URL;
+import java.net.MalformedURLException;
 
 public class IOUtil
 {
     public static void copyCompletely(InputStream input, OutputStream output)
         throws IOException
     {
-        //if both are file streams, use channel IO
-        if ((output instanceof FileOutputStream) && (input instanceof FileInputStream))
-        {
-            try
-            {
-                FileChannel target = ((FileOutputStream) output).getChannel();
-                FileChannel source = ((FileInputStream) input).getChannel();
-                
-                source.transferTo(0, Integer.MAX_VALUE, target);
-                
-                source.close();
-                target.close();
-                
-                return;
-            }
-            catch (Exception e)
-            { /* failover to byte stream version */ }
-        }
-        
         byte[] buf = new byte[8192];
         while (true)
         {
@@ -61,28 +41,17 @@
         try { output.close(); } catch (IOException ignore) {}
     }
 
-    public static void copyCompletely(URI input, URI output)
+    public static void copyCompletely(URL input, URL output)
         throws IOException
     {
         try
         {
-            InputStream in = null;
-            try
-            {
-                File f = new File(input);
-                if (f.exists())
-                    in = new FileInputStream(f);
-            }
-            catch (Exception notAFile)
-            {}
-            
-            File out = new File(output);
+            InputStream in = input.openStream();
+
+            File out = new File(output.getPath());
             File dir = out.getParentFile();
             dir.mkdirs();
             
-            if (in == null)
-                in = input.toURL().openStream();
-                
             IOUtil.copyCompletely(in, new FileOutputStream(out));
         }
         catch (IllegalArgumentException e)
@@ -91,4 +60,15 @@
         }
     }
 
+    public static URL fileToURL(File file)
+    {
+        try
+        {
+            return file.toURL();
+        }
+        catch (MalformedURLException e)
+        {
+            return null;
+        }
+    }
 }
diff --git a/v1/src/common/org/apache/xmlbeans/impl/common/IdentityConstraint.java b/v1/src/common/org/apache/xmlbeans/impl/common/IdentityConstraint.java
index e4af803..90114bc 100644
--- a/v1/src/common/org/apache/xmlbeans/impl/common/IdentityConstraint.java
+++ b/v1/src/common/org/apache/xmlbeans/impl/common/IdentityConstraint.java
@@ -18,6 +18,8 @@
 import org.apache.xmlbeans.impl.common.ValidatorListener.Event;
 import javax.xml.namespace.QName;
 import org.apache.xmlbeans.*;
+import org.apache.xmlbeans.impl.common.SequencedHashSet;
+
 import java.util.*;
 
 /**
@@ -117,7 +119,8 @@
 
         if (_errorListener != null)
         {
-            assert event != null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(event != null);
             
             _errorListener.add(
                 XmlError.forCursor( msg, event.getLocationAsCursor() ) );
@@ -154,8 +157,9 @@
      */
     static SchemaType getSimpleType(SchemaType st) 
     {
-        assert st.isSimpleType() || st.getContentType() == SchemaType.SIMPLE_CONTENT : 
-            st + " does not have simple content.";
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(st.isSimpleType() || st.getContentType() == SchemaType.SIMPLE_CONTENT,
+                st + " does not have simple content.");
 
         while (! st.isSimpleType() )
             st = st.getBaseType();
@@ -188,7 +192,7 @@
 
     public class SelectorState extends ConstraintState {
         SchemaIdentityConstraint _constraint;
-        Set _values = new LinkedHashSet();
+        Set _values = new SequencedHashSet();
         XPath.ExecutionContext _context;
 
         SelectorState(SchemaIdentityConstraint constraint, Event e, SchemaType st) {
@@ -423,7 +427,7 @@
 
     public class IdState extends ConstraintState
     {
-        Set _values = new LinkedHashSet();
+        Set _values = new SequencedHashSet();
 
         IdState() { }
 
diff --git a/v1/src/common/org/apache/xmlbeans/impl/common/IdentityMap.java b/v1/src/common/org/apache/xmlbeans/impl/common/IdentityMap.java
new file mode 100644
index 0000000..c76a342
--- /dev/null
+++ b/v1/src/common/org/apache/xmlbeans/impl/common/IdentityMap.java
@@ -0,0 +1,151 @@
+/**
+ * Copyright (c) 2003-2004, Joe Walnes
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this list of
+ * conditions and the following disclaimer. Redistributions in binary form must reproduce
+ * the above copyright notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the distribution.
+ *
+ * Neither the name of XStream nor the names of its contributors may be used to endorse
+ * or promote products derived from this software without specific prior written
+ * permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+ * SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+ * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
+ * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+ * DAMAGE.
+ */
+
+package org.apache.xmlbeans.impl.common;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Behaves the same way as JDK1.4 java.util.IdentityHashMap, but in JDK1.3 as well.
+ * <p/>
+ * Modified version of ObjectIdDictionary from XStream.
+ */
+public class IdentityMap implements Map
+{
+    private transient Map map;
+
+    private static class KeyWrapper
+    {
+        private final Object obj;
+
+        public KeyWrapper(Object obj)
+        {
+            this.obj = obj;
+        }
+
+        public int hashCode()
+        {
+            return System.identityHashCode(obj);
+        }
+
+        public boolean equals(Object other)
+        {
+            return obj == ((KeyWrapper)other).obj;
+        }
+
+        public String toString()
+        {
+            return obj.toString();
+        }
+    }
+
+    public IdentityMap()
+    {
+        map = new HashMap();
+    }
+
+    public int size()
+    {
+        return map.size();
+    }
+
+    public boolean isEmpty()
+    {
+        return map.isEmpty();
+    }
+
+    public boolean containsKey(Object key)
+    {
+        return map.containsKey(new KeyWrapper(key));
+    }
+
+    public boolean containsValue(Object value)
+    {
+        return map.containsValue(value);
+    }
+
+    public Object get(Object key)
+    {
+        return map.get(new KeyWrapper(key));
+    }
+
+    public Object put(Object key, Object value)
+    {
+        return map.put(new KeyWrapper(key), value);
+    }
+
+    public Object remove(Object key)
+    {
+        return map.remove(new KeyWrapper(key));
+    }
+
+    public void putAll(Map t)
+    {
+        throw new UnsupportedOperationException("unimplemented");
+    }
+
+    public void clear()
+    {
+        map.clear();
+    }
+
+    public int hashCode()
+    {
+        return map.hashCode();
+    }
+
+    public Set keySet()
+    {
+        return map.keySet();
+    }
+
+    public Collection values()
+    {
+        return map.values();
+    }
+
+    public Set entrySet()
+    {
+        return map.entrySet();
+    }
+
+    public Iterator iterator()
+    {
+        return map.keySet().iterator();
+    }
+
+    public boolean equals(Object o)
+    {
+        throw new RuntimeException("unimplemented");
+    }
+
+}
diff --git a/v1/src/common/org/apache/xmlbeans/impl/common/NameUtil.java b/v1/src/common/org/apache/xmlbeans/impl/common/NameUtil.java
index 393ff4d..6c1da90 100644
--- a/v1/src/common/org/apache/xmlbeans/impl/common/NameUtil.java
+++ b/v1/src/common/org/apache/xmlbeans/impl/common/NameUtil.java
@@ -495,7 +495,7 @@
         List result = null;
 
         if ( i >= 0 && uri.substring(0, i).equals("java"))
-            result =  Arrays.asList(uri.substring(i + 1).split("\\."));
+            result = Arrays.asList(StringUtils.split(uri.substring(i + 1), '.'));
 
         else {
             result = new ArrayList();
diff --git a/v1/src/common/org/apache/xmlbeans/impl/common/NetUtils.java b/v1/src/common/org/apache/xmlbeans/impl/common/NetUtils.java
new file mode 100644
index 0000000..7fc8ee7
--- /dev/null
+++ b/v1/src/common/org/apache/xmlbeans/impl/common/NetUtils.java
@@ -0,0 +1,502 @@
+/*
+
+ ============================================================================
+                   The Apache Software License, Version 1.1
+ ============================================================================
+
+ Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without modifica-
+ tion, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of  source code must  retain the above copyright  notice,
+    this list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright notice,
+    this list of conditions and the following disclaimer in the documentation
+    and/or other materials provided with the distribution.
+
+ 3. The end-user documentation included with the redistribution, if any, must
+    include  the following  acknowledgment:  "This product includes  software
+    developed  by the  Apache Software Foundation  (http://www.apache.org/)."
+    Alternately, this  acknowledgment may  appear in the software itself,  if
+    and wherever such third-party acknowledgments normally appear.
+
+ 4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
+    used to  endorse or promote  products derived from  this software without
+    prior written permission. For written permission, please contact
+    apache@apache.org.
+
+ 5. Products  derived from this software may not  be called "Apache", nor may
+    "Apache" appear  in their name,  without prior written permission  of the
+    Apache Software Foundation.
+
+ THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
+ APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
+ INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
+ DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
+ ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
+ (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
+ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This software  consists of voluntary contributions made  by many individuals
+ on  behalf of the Apache Software  Foundation and was  originally created by
+ Stefano Mazzocchi  <stefano@apache.org>. For more  information on the Apache
+ Software Foundation, please see <http://www.apache.org/>.
+
+*/
+package org.apache.xmlbeans.impl.common;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.UnsupportedEncodingException;
+
+import java.util.BitSet;
+import java.util.Iterator;
+import java.util.Map;
+
+
+/**
+ * A collection of <code>File</code>, <code>URL</code> and filename
+ * utility methods
+ *
+ * @author <a href="mailto:stefano@apache.org">Stefano Mazzocchi</a>
+ * @version CVS $Id: NetUtils.java,v 1.1.2.1 2004/06/19 03:07:39 daveremy Exp $
+ */
+
+public class NetUtils {
+
+    /**
+     * Array containing the safe characters set as defined by RFC 1738
+     */
+    private static BitSet safeCharacters;
+
+
+    private static final char[] hexadecimal =
+    {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
+     'A', 'B', 'C', 'D', 'E', 'F'};
+
+    static {
+        safeCharacters = new BitSet(256);
+        int i;
+        // 'lowalpha' rule
+        for (i = 'a'; i <= 'z'; i++) {
+            safeCharacters.set(i);
+        }
+        // 'hialpha' rule
+        for (i = 'A'; i <= 'Z'; i++) {
+            safeCharacters.set(i);
+        }
+        // 'digit' rule
+        for (i = '0'; i <= '9'; i++) {
+            safeCharacters.set(i);
+        }
+
+        // 'safe' rule
+        safeCharacters.set('$');
+        safeCharacters.set('-');
+        safeCharacters.set('_');
+        safeCharacters.set('.');
+        safeCharacters.set('+');
+
+        // 'extra' rule
+        safeCharacters.set('!');
+        safeCharacters.set('*');
+        safeCharacters.set('\'');
+        safeCharacters.set('(');
+        safeCharacters.set(')');
+        safeCharacters.set(',');
+
+        // special characters common to http: file: and ftp: URLs ('fsegment' and 'hsegment' rules)
+        safeCharacters.set('/');
+        safeCharacters.set(':');
+        safeCharacters.set('@');
+        safeCharacters.set('&');
+        safeCharacters.set('=');
+    }
+
+    /**
+     * Decode a path.
+     *
+     * <p>Interprets %XX (where XX is hexadecimal number) as UTF-8 encoded bytes.
+     * <p>The validity of the input path is not checked (i.e. characters that were not encoded will
+     * not be reported as errors).
+     * <p>This method differs from URLDecoder.decode in that it always uses UTF-8 (while URLDecoder
+     * uses the platform default encoding, often ISO-8859-1), and doesn't translate + characters to spaces.
+     *
+     * @param path the path to decode
+     * @return the decoded path
+     */
+    public static String decodePath(String path) {
+        StringBuffer translatedPath = new StringBuffer(path.length());
+        byte[] encodedchars = new byte[path.length() / 3];
+        int i = 0;
+        int length = path.length();
+        int encodedcharsLength = 0;
+        while (i < length) {
+            if (path.charAt(i) == '%') {
+                // we must process all consecutive %-encoded characters in one go, because they represent
+                // an UTF-8 encoded string, and in UTF-8 one character can be encoded as multiple bytes
+                while (i < length && path.charAt(i) == '%') {
+                    if (i + 2 < length) {
+                        try {
+                            byte x = (byte)Integer.parseInt(path.substring(i + 1, i + 3), 16);
+                            encodedchars[encodedcharsLength] = x;
+                        } catch (NumberFormatException e) {
+                            throw new IllegalArgumentException("NetUtils.decodePath: illegal hex characters in pattern %" + path.substring(i + 1, i + 3));
+                        }
+                        encodedcharsLength++;
+                        i += 3;
+                    } else {
+                        throw new IllegalArgumentException("NetUtils.decodePath: % character should be followed by 2 hexadecimal characters.");
+                    }
+                }
+                try {
+                    String translatedPart = new String(encodedchars, 0, encodedcharsLength, "UTF-8");
+                    translatedPath.append(translatedPart);
+                } catch (UnsupportedEncodingException e) {
+                    // the situation that UTF-8 is not supported is quite theoretical, so throw a runtime exception
+                    throw new RuntimeException("Problem in decodePath: UTF-8 encoding not supported.");
+                }
+                encodedcharsLength = 0;
+            } else {
+                // a normal character
+                translatedPath.append(path.charAt(i));
+                i++;
+            }
+        }
+        return translatedPath.toString();
+    }
+
+    /**
+     * Encode a path as required by the URL specificatin (<a href="http://www.ietf.org/rfc/rfc1738.txt">
+     * RFC 1738</a>). This differs from <code>java.net.URLEncoder.encode()</code> which encodes according
+     * to the <code>x-www-form-urlencoded</code> MIME format.
+     *
+     * @param path the path to encode
+     * @return the encoded path
+     */
+    public static String encodePath(String path) {
+       // taken from org.apache.catalina.servlets.DefaultServlet ;)
+
+        /**
+         * Note: This code portion is very similar to URLEncoder.encode.
+         * Unfortunately, there is no way to specify to the URLEncoder which
+         * characters should be encoded. Here, ' ' should be encoded as "%20"
+         * and '/' shouldn't be encoded.
+         */
+
+        int maxBytesPerChar = 10;
+        StringBuffer rewrittenPath = new StringBuffer(path.length());
+        ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar);
+        OutputStreamWriter writer = null;
+        try {
+            writer = new OutputStreamWriter(buf, "UTF8");
+        } catch (Exception e) {
+            e.printStackTrace();
+            writer = new OutputStreamWriter(buf);
+        }
+
+        for (int i = 0; i < path.length(); i++) {
+            int c = path.charAt(i);
+            if (safeCharacters.get(c)) {
+                rewrittenPath.append((char)c);
+            } else {
+                // convert to external encoding before hex conversion
+                try {
+                    writer.write(c);
+                    writer.flush();
+                } catch(IOException e) {
+                    buf.reset();
+                    continue;
+                }
+                byte[] ba = buf.toByteArray();
+                for (int j = 0; j < ba.length; j++) {
+                    // Converting each byte in the buffer
+                    byte toEncode = ba[j];
+                    rewrittenPath.append('%');
+                    int low = (toEncode & 0x0f);
+                    int high = ((toEncode & 0xf0) >> 4);
+                    rewrittenPath.append(hexadecimal[high]);
+                    rewrittenPath.append(hexadecimal[low]);
+                }
+                buf.reset();
+            }
+        }
+
+        return rewrittenPath.toString();
+    }
+
+    /**
+     * Returns the path of the given resource.
+     *
+     * @param uri The URI of the resource
+     * @return the resource path
+     */
+    public static String getPath(String uri) {
+        int i = uri.lastIndexOf('/');
+        if (i > -1) {
+            return uri.substring(0, i);
+        }
+        i = uri.indexOf(':');
+        return (i > -1) ? uri.substring(i + 1, uri.length()) : "";
+    }
+
+    /**
+     * Remove path and file information from a filename returning only its
+     * extension  component
+     *
+     * @param uri The filename
+     * @return The filename extension (with starting dot!)
+     */
+    public static String getExtension(String uri) {
+        int dot = uri.lastIndexOf('.');
+        if (dot > -1) {
+            uri = uri.substring(dot);
+            int slash = uri.lastIndexOf('/');
+            if (slash > -1) {
+                return null;
+            } else {
+                int sharp = uri.lastIndexOf('#');
+                if (sharp > -1) {
+                    // uri starts with dot already
+                    return uri.substring(0, sharp);
+                } else {
+                    int mark = uri.lastIndexOf('?');
+                    if (mark > -1) {
+                        // uri starts with dot already
+                        return uri.substring(0, mark);
+                    } else {
+                        return uri;
+                    }
+                }
+            }
+        } else {
+            return null;
+        }
+    }
+
+    /**
+     * Absolutize a relative resource path on the given absolute base path.
+     *
+     * @param path The absolute base path
+     * @param resource The relative resource path
+     * @return The absolutized resource path
+     */
+    public static String absolutize(String path, String resource) {
+        if (path == null || path.length() == 0) {
+            // Base path is empty
+            return resource;
+        }
+
+        if (resource == null || resource.length() == 0) {
+            // Resource path is empty
+            return path;
+        }
+
+        if (resource.charAt(0) == '/') {
+            // Resource path is already absolute
+            return resource;
+        }
+
+        int length = path.length() - 1;
+        boolean slash = (path.charAt(length) == '/');
+
+        StringBuffer b = new StringBuffer();
+        b.append(path);
+        if (!slash) {
+            b.append('/');
+        }
+        b.append(resource);
+        return b.toString();
+    }
+
+    /**
+     * Relativize an absolute resource on a given absolute path.
+     *
+     * @param path The absolute path
+     * @param absoluteResource The absolute resource
+     * @return the resource relative to the given path
+     */
+    public static String relativize(String path, String absoluteResource) {
+        if (path == null || "".equals(path)) {
+            return absoluteResource;
+        }
+
+        if (path.charAt(path.length() - 1) != '/') {
+            path += "/";
+        }
+
+        if (absoluteResource.startsWith(path)) {
+            // resource is direct descendant
+            return absoluteResource.substring(path.length());
+        } else {
+            // resource is not direct descendant
+            int index = StringUtils.matchStrings(path, absoluteResource);
+            if (index > 0 && path.charAt(index-1) != '/') {
+                index = path.substring(0, index).lastIndexOf('/');
+                index++;
+            }
+            String pathDiff = path.substring(index);
+            String resource = absoluteResource.substring(index);
+            int levels = StringUtils.count(pathDiff, '/');
+            StringBuffer b = new StringBuffer();
+            for (int i = 0; i < levels; i++) {
+                b.append("../");
+            }
+            b.append(resource);
+            return b.toString();
+        }
+    }
+
+    /**
+     * Normalize a uri containing ../ and ./ paths.
+     *
+     * @param uri The uri path to normalize
+     * @return The normalized uri
+     */
+    public static String normalize(String uri) {
+        String[] dirty = StringUtils.split(uri, '/');
+        int length = dirty.length;
+        String[] clean = new String[length];
+
+        boolean path;
+        boolean finished;
+        while (true) {
+            path = false;
+            finished = true;
+            for (int i = 0, j = 0; (i < length) && (dirty[i] != null); i++) {
+                if (".".equals(dirty[i])) {
+                    // ignore
+                } else if ("..".equals(dirty[i])) {
+                    clean[j++] = dirty[i];
+                    if (path) finished = false;
+                } else {
+                    if ((i+1 < length) && ("..".equals(dirty[i+1]))) {
+                        i++;
+                    } else {
+                        clean[j++] = dirty[i];
+                        path = true;
+                    }
+                }
+            }
+            if (finished) {
+                break;
+            } else {
+                dirty = clean;
+                clean = new String[length];
+            }
+        }
+
+        StringBuffer b = new StringBuffer(uri.length());
+        for (int i = 0; (i < length) && (clean[i] != null); i++) {
+            b.append(clean[i]);
+            if ((i+1 < length) && (clean[i+1] != null)) {
+                b.append("/");
+            }
+        }
+        return b.toString();
+    }
+
+    /**
+     * Remove parameters from a uri.
+     * Resulting Map will have either String for single value attributes,
+     * or String arrays for multivalue attributes.
+     *
+     * @param uri The uri path to deparameterize.
+     * @param parameters The map that collects parameters.
+     * @return The cleaned uri
+     */
+    public static String deparameterize(String uri, Map parameters) {
+        int i = uri.lastIndexOf('?');
+        if (i == -1) {
+            return uri;
+        }
+
+        String[] params = StringUtils.split(uri.substring(i + 1), '&');
+        for (int j = 0; j < params.length; j++) {
+            String p = params[j];
+            int k = p.indexOf('=');
+            if (k == -1) {
+                break;
+            }
+            String name = p.substring(0, k);
+            String value = p.substring(k + 1);
+            Object values = parameters.get(name);
+            if (values == null) {
+                parameters.put(name, value);
+            } else if (values.getClass().isArray()) {
+                String[] v1 = (String[])values;
+                String[] v2 = new String[v1.length + 1];
+                System.arraycopy(v1, 0, v2, 0, v1.length);
+                v2[v1.length] = value;
+                parameters.put(name, v2);
+            } else {
+                parameters.put(name, new String[]{values.toString(), value});
+            }
+        }
+        return uri.substring(0, i);
+    }
+
+    /**
+     * Add parameters stored in the Map to the uri string.
+     * Map can contain Object values which will be converted to the string,
+     * or Object arrays, which will be treated as multivalue attributes.
+     *
+     * @param uri The uri to add parameters into
+     * @param parameters The map containing parameters to be added
+     * @return The uri with added parameters
+     */
+    public static String parameterize(String uri, Map parameters) {
+        if (parameters.size() == 0) {
+            return uri;
+        }
+
+        StringBuffer buffer = new StringBuffer(uri);
+        if (uri.indexOf('?') == -1) {
+            buffer.append('?');
+        } else {
+            buffer.append('&');
+        }
+
+        for (Iterator i = parameters.entrySet().iterator(); i.hasNext();) {
+            Map.Entry entry = (Map.Entry)i.next();
+            if (entry.getValue().getClass().isArray()) {
+                Object[] value = (Object[])entry.getValue();
+                for (int j = 0; j < value.length; j++) {
+                    if (j > 0) {
+                        buffer.append('&');
+                    }
+                    buffer.append(entry.getKey());
+                    buffer.append('=');
+                    buffer.append(value[j]);
+                }
+            } else {
+                buffer.append(entry.getKey());
+                buffer.append('=');
+                buffer.append(entry.getValue());
+            }
+            if (i.hasNext()) {
+                buffer.append('&');
+            }
+        }
+        return buffer.toString();
+    }
+
+
+
+    /**
+     * Remove any authorisation details from a URI
+     */
+    public static String removeAuthorisation(String uri) {
+        if (uri.indexOf("@")!=-1 && (uri.startsWith("ftp://") || uri.startsWith("http://"))) {
+            return uri.substring(0, uri.indexOf(":")+2)+uri.substring(uri.indexOf("@")+1);
+        }
+
+        return uri;
+    }
+}
diff --git a/v1/src/common/org/apache/xmlbeans/impl/common/QNameHelper.java b/v1/src/common/org/apache/xmlbeans/impl/common/QNameHelper.java
index c6b852f..aa02d11 100644
--- a/v1/src/common/org/apache/xmlbeans/impl/common/QNameHelper.java
+++ b/v1/src/common/org/apache/xmlbeans/impl/common/QNameHelper.java
@@ -27,6 +27,7 @@
 
 import org.apache.xmlbeans.SchemaType;
 import org.apache.xmlbeans.SchemaField;
+import org.apache.xmlbeans.XmlBeans;
 
 public class QNameHelper
 {
@@ -155,7 +156,8 @@
                 inputBytes = new byte[0];
             }
             byte[] digest = md.digest(inputBytes);
-            assert(digest.length == 20); // SHA1 160 bits == 20 bytes
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(digest.length == 20); // SHA1 160 bits == 20 bytes
             result = new StringBuffer("URI_SHA_1_");
             for (int j = 0; j < digest.length; j++)
             {
diff --git a/v1/src/common/org/apache/xmlbeans/impl/common/SequencedHashMap.java b/v1/src/common/org/apache/xmlbeans/impl/common/SequencedHashMap.java
new file mode 100644
index 0000000..b1c3c33
--- /dev/null
+++ b/v1/src/common/org/apache/xmlbeans/impl/common/SequencedHashMap.java
@@ -0,0 +1,1004 @@
+/*   Copyright 2004 The Apache Software Foundation

+ *

+ *   Licensed under the Apache License, Version 2.0 (the "License");

+ *   you may not use this file except in compliance with the License.

+ *   You may obtain a copy of the License at

+ *

+ *       http://www.apache.org/licenses/LICENSE-2.0

+ *

+ *   Unless required by applicable law or agreed to in writing, software

+ *   distributed under the License is distributed on an "AS IS" BASIS,

+ *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

+ *   See the License for the specific language governing permissions and

+ *  limitations under the License.

+ */

+

+package org.apache.xmlbeans.impl.common;

+

+import java.io.Externalizable;

+import java.io.ObjectInput;

+import java.io.ObjectOutput;

+import java.io.IOException;

+

+import java.util.Collection;

+import java.util.Collections;

+import java.util.HashMap;

+import java.util.Iterator;

+import java.util.AbstractCollection;

+import java.util.AbstractSet;

+import java.util.ArrayList;

+import java.util.List;

+import java.util.Map;

+import java.util.Set;

+import java.util.NoSuchElementException;

+import java.util.ConcurrentModificationException;

+

+// from commons-collection

+/**

+ *  A map of objects whose mapping entries are sequenced based on the order in

+ *  which they were added.  This data structure has fast <I>O(1)</I> search

+ *  time, deletion time, and insertion time.

+ *

+ *  <P>Although this map is sequenced, it cannot implement {@link

+ *  java.util.List} because of incompatible interface definitions.  The remove

+ *  methods in List and Map have different return values (see: {@link

+ *  java.util.List#remove(Object)} and {@link java.util.Map#remove(Object)}).

+ *

+ *  <P>This class is not thread safe.  When a thread safe implementation is

+ *  required, use {@link Collections#synchronizedMap(Map)} as it is documented,

+ *  or use explicit synchronization controls.

+ *

+ * @author <a href="mailto:mas@apache.org">Michael A. Smith</A>

+ * @author <a href="mailto:dlr@collab.net">Daniel Rall</a>

+ * @author <a href="mailto:hps@intermeta.de">Henning P. Schmiedehausen</a>

+ */

+public class SequencedHashMap implements Map, Cloneable, Externalizable {

+

+    /**

+     *  {@link java.util.Map.Entry} that doubles as a node in the linked list

+     *  of sequenced mappings.

+     **/

+    private static class Entry implements Map.Entry {

+        // Note: This class cannot easily be made clonable.  While the actual

+        // implementation of a clone would be simple, defining the semantics is

+        // difficult.  If a shallow clone is implemented, then entry.next.prev !=

+        // entry, which is unintuitive and probably breaks all sorts of assumptions

+        // in code that uses this implementation.  If a deep clone is

+        // implementated, then what happens when the linked list is cyclical (as is

+        // the case with SequencedHashMap)?  It's impossible to know in the clone

+        // when to stop cloning, and thus you end up in a recursive loop,

+        // continuously cloning the "next" in the list.

+

+        private final Object key;

+        private Object value;

+

+        // package private to allow the SequencedHashMap to access and manipulate

+        // them.

+        Entry next = null;

+        Entry prev = null;

+

+        public Entry(Object key, Object value) {

+            this.key = key;

+            this.value = value;

+        }

+

+        // per Map.Entry.getKey()

+        public Object getKey() {

+            return this.key;

+        }

+

+        // per Map.Entry.getValue()

+        public Object getValue() {

+            return this.value;

+        }

+

+        // per Map.Entry.setValue()

+        public Object setValue(Object value) {

+            Object oldValue = this.value;

+            this.value = value;

+            return oldValue;

+        }

+

+        public int hashCode() {

+            // implemented per api docs for Map.Entry.hashCode()

+            return ((getKey() == null ? 0 : getKey().hashCode()) ^

+                    (getValue() == null ? 0 : getValue().hashCode()));

+        }

+

+        public boolean equals(Object obj) {

+            if (obj == null) return false;

+            if (obj == this) return true;

+            if (!(obj instanceof Map.Entry)) return false;

+

+            Map.Entry other = (Map.Entry)obj;

+

+            // implemented per api docs for Map.Entry.equals(Object)

+            return ((getKey() == null ?

+                    other.getKey() == null :

+                    getKey().equals(other.getKey())) &&

+                    (getValue() == null ?

+                    other.getValue() == null :

+                    getValue().equals(other.getValue())));

+        }

+

+        public String toString() {

+            return "[" + getKey() + "=" + getValue() + "]";

+        }

+    }

+

+    /**

+     *  Construct an empty sentinel used to hold the head (sentinel.next) and the

+     *  tail (sentinel.prev) of the list.  The sentinal has a <code>null</code>

+     *  key and value.

+     **/

+    private static final Entry createSentinel() {

+        Entry s = new Entry(null, null);

+        s.prev = s;

+        s.next = s;

+        return s;

+    }

+

+    /**

+     *  Sentinel used to hold the head and tail of the list of entries.

+     **/

+    private Entry sentinel;

+

+    /**

+     *  Map of keys to entries

+     **/

+    private HashMap entries;

+

+    /**

+     *  Holds the number of modifications that have occurred to the map,

+     *  excluding modifications made through a collection view's iterator

+     *  (e.g. entrySet().iterator().remove()).  This is used to create a

+     *  fail-fast behavior with the iterators.

+     **/

+    private transient long modCount = 0;

+

+    /**

+     *  Construct a new sequenced hash map with default initial size and load

+     *  factor.

+     **/

+    public SequencedHashMap() {

+        sentinel = createSentinel();

+        entries = new HashMap();

+    }

+

+    /**

+     *  Construct a new sequenced hash map with the specified initial size and

+     *  default load factor.

+     *

+     *  @param initialSize the initial size for the hash table

+     *

+     *  @see HashMap#HashMap(int)

+     **/

+    public SequencedHashMap(int initialSize) {

+        sentinel = createSentinel();

+        entries = new HashMap(initialSize);

+    }

+

+    /**

+     *  Construct a new sequenced hash map with the specified initial size and

+     *  load factor.

+     *

+     *  @param initialSize the initial size for the hash table

+     *

+     *  @param loadFactor the load factor for the hash table.

+     *

+     *  @see HashMap#HashMap(int,float)

+     **/

+    public SequencedHashMap(int initialSize, float loadFactor) {

+        sentinel = createSentinel();

+        entries = new HashMap(initialSize, loadFactor);

+    }

+

+    /**

+     *  Construct a new sequenced hash map and add all the elements in the

+     *  specified map.  The order in which the mappings in the specified map are

+     *  added is defined by {@link #putAll(Map)}.

+     **/

+    public SequencedHashMap(Map m) {

+        this();

+        putAll(m);

+    }

+

+    /**

+     *  Removes an internal entry from the linked list.  This does not remove

+     *  it from the underlying map.

+     **/

+    private void removeEntry(Entry entry) {

+        entry.next.prev = entry.prev;

+        entry.prev.next = entry.next;

+    }

+

+    /**

+     *  Inserts a new internal entry to the tail of the linked list.  This does

+     *  not add the entry to the underlying map.

+     **/

+    private void insertEntry(Entry entry) {

+        entry.next = sentinel;

+        entry.prev = sentinel.prev;

+        sentinel.prev.next = entry;

+        sentinel.prev = entry;

+    }

+

+    // per Map.size()

+

+    /**

+     *  Implements {@link Map#size()}.

+     */

+    public int size() {

+        // use the underlying Map's size since size is not maintained here.

+        return entries.size();

+    }

+

+    /**

+     *  Implements {@link Map#isEmpty()}.

+     */

+    public boolean isEmpty() {

+        // for quick check whether the map is entry, we can check the linked list

+        // and see if there's anything in it.

+        return sentinel.next == sentinel;

+    }

+

+    /**

+     *  Implements {@link Map#containsKey(Object)}.

+     */

+    public boolean containsKey(Object key) {

+        // pass on to underlying map implementation

+        return entries.containsKey(key);

+    }

+

+    /**

+     *  Implements {@link Map#containsValue(Object)}.

+     */

+    public boolean containsValue(Object value) {

+        // unfortunately, we cannot just pass this call to the underlying map

+        // because we are mapping keys to entries, not keys to values.  The

+        // underlying map doesn't have an efficient implementation anyway, so this

+        // isn't a big deal.

+

+        // do null comparison outside loop so we only need to do it once.  This

+        // provides a tighter, more efficient loop at the expense of slight

+        // code duplication.

+        if (value == null) {

+            for (Entry pos = sentinel.next; pos != sentinel; pos = pos.next) {

+                if (pos.getValue() == null) return true;

+            }

+        }

+        else {

+            for (Entry pos = sentinel.next; pos != sentinel; pos = pos.next) {

+                if (value.equals(pos.getValue())) return true;

+            }

+        }

+        return false;

+    }

+

+    /**

+     *  Implements {@link Map#get(Object)}.

+     */

+    public Object get(Object o) {

+        // find entry for the specified key object

+        Entry entry = (Entry)entries.get(o);

+        if (entry == null) return null;

+

+        return entry.getValue();

+    }

+

+    /**

+     *  Return the entry for the "oldest" mapping.  That is, return the Map.Entry

+     *  for the key-value pair that was first put into the map when compared to

+     *  all the other pairings in the map.  This behavior is equivalent to using

+     *  <code>entrySet().iterator().next()</code>, but this method provides an

+     *  optimized implementation.

+     *

+     *  @return The first entry in the sequence, or <code>null</code> if the

+     *  map is empty.

+     **/

+    public Map.Entry getFirst() {

+        // sentinel.next points to the "first" element of the sequence -- the head

+        // of the list, which is exactly the entry we need to return.  We must test

+        // for an empty list though because we don't want to return the sentinel!

+        return (isEmpty()) ? null : sentinel.next;

+    }

+

+    /**

+     *  Return the key for the "oldest" mapping.  That is, return the key for the

+     *  mapping that was first put into the map when compared to all the other

+     *  objects in the map.  This behavior is equivalent to using

+     *  <code>getFirst().getKey()</code>, but this method provides a slightly

+     *  optimized implementation.

+     *

+     *  @return The first key in the sequence, or <code>null</code> if the

+     *  map is empty.

+     **/

+    public Object getFirstKey() {

+        // sentinel.next points to the "first" element of the sequence -- the head

+        // of the list -- and the requisite key is returned from it.  An empty list

+        // does not need to be tested.  In cases where the list is empty,

+        // sentinel.next will point to the sentinel itself which has a null key,

+        // which is exactly what we would want to return if the list is empty (a

+        // nice convient way to avoid test for an empty list)

+        return sentinel.next.getKey();

+    }

+

+    /**

+     *  Return the value for the "oldest" mapping.  That is, return the value for

+     *  the mapping that was first put into the map when compared to all the

+     *  other objects in the map.  This behavior is equivalent to using

+     *  <code>getFirst().getValue()</code>, but this method provides a slightly

+     *  optimized implementation.

+     *

+     *  @return The first value in the sequence, or <code>null</code> if the

+     *  map is empty.

+     **/

+    public Object getFirstValue() {

+        // sentinel.next points to the "first" element of the sequence -- the head

+        // of the list -- and the requisite value is returned from it.  An empty

+        // list does not need to be tested.  In cases where the list is empty,

+        // sentinel.next will point to the sentinel itself which has a null value,

+        // which is exactly what we would want to return if the list is empty (a

+        // nice convient way to avoid test for an empty list)

+        return sentinel.next.getValue();

+    }

+

+    /**

+     *  Return the entry for the "newest" mapping.  That is, return the Map.Entry

+     *  for the key-value pair that was first put into the map when compared to

+     *  all the other pairings in the map.  The behavior is equivalent to:

+     *

+     *  <pre>

+     *    Object obj = null;

+     *    Iterator iter = entrySet().iterator();

+     *    while(iter.hasNext()) {

+     *      obj = iter.next();

+     *    }

+     *    return (Map.Entry)obj;

+     *  </pre>

+     *

+     *  However, the implementation of this method ensures an O(1) lookup of the

+     *  last key rather than O(n).

+     *

+     *  @return The last entry in the sequence, or <code>null</code> if the map

+     *  is empty.

+     **/

+    public Map.Entry getLast() {

+        // sentinel.prev points to the "last" element of the sequence -- the tail

+        // of the list, which is exactly the entry we need to return.  We must test

+        // for an empty list though because we don't want to return the sentinel!

+        return (isEmpty()) ? null : sentinel.prev;

+    }

+

+    /**

+     *  Return the key for the "newest" mapping.  That is, return the key for the

+     *  mapping that was last put into the map when compared to all the other

+     *  objects in the map.  This behavior is equivalent to using

+     *  <code>getLast().getKey()</code>, but this method provides a slightly

+     *  optimized implementation.

+     *

+     *  @return The last key in the sequence, or <code>null</code> if the map is

+     *  empty.

+     **/

+    public Object getLastKey() {

+        // sentinel.prev points to the "last" element of the sequence -- the tail

+        // of the list -- and the requisite key is returned from it.  An empty list

+        // does not need to be tested.  In cases where the list is empty,

+        // sentinel.prev will point to the sentinel itself which has a null key,

+        // which is exactly what we would want to return if the list is empty (a

+        // nice convient way to avoid test for an empty list)

+        return sentinel.prev.getKey();

+    }

+

+    /**

+     *  Return the value for the "newest" mapping.  That is, return the value for

+     *  the mapping that was last put into the map when compared to all the other

+     *  objects in the map.  This behavior is equivalent to using

+     *  <code>getLast().getValue()</code>, but this method provides a slightly

+     *  optimized implementation.

+     *

+     *  @return The last value in the sequence, or <code>null</code> if the map

+     *  is empty.

+     **/

+    public Object getLastValue() {

+        // sentinel.prev points to the "last" element of the sequence -- the tail

+        // of the list -- and the requisite value is returned from it.  An empty

+        // list does not need to be tested.  In cases where the list is empty,

+        // sentinel.prev will point to the sentinel itself which has a null value,

+        // which is exactly what we would want to return if the list is empty (a

+        // nice convient way to avoid test for an empty list)

+        return sentinel.prev.getValue();

+    }

+

+    /**

+     *  Implements {@link Map#put(Object, Object)}.

+     */

+    public Object put(Object key, Object value) {

+        modCount++;

+

+        Object oldValue = null;

+

+        // lookup the entry for the specified key

+        Entry e = (Entry)entries.get(key);

+

+        // check to see if it already exists

+        if (e != null) {

+            // remove from list so the entry gets "moved" to the end of list

+            removeEntry(e);

+

+            // update value in map

+            oldValue = e.setValue(value);

+

+            // Note: We do not update the key here because its unnecessary.  We only

+            // do comparisons using equals(Object) and we know the specified key and

+            // that in the map are equal in that sense.  This may cause a problem if

+            // someone does not implement their hashCode() and/or equals(Object)

+            // method properly and then use it as a key in this map.

+        }

+        else {

+            // add new entry

+            e = new Entry(key, value);

+            entries.put(key, e);

+        }

+        // assert(entry in map, but not list)

+

+        // add to list

+        insertEntry(e);

+

+        return oldValue;

+    }

+

+    /**

+     *  Implements {@link Map#remove(Object)}.

+     */

+    public Object remove(Object key) {

+        Entry e = removeImpl(key);

+        return (e == null) ? null : e.getValue();

+    }

+

+    /**

+     *  Fully remove an entry from the map, returning the old entry or null if

+     *  there was no such entry with the specified key.

+     **/

+    private Entry removeImpl(Object key) {

+        Entry e = (Entry)entries.remove(key);

+        if (e == null) return null;

+        modCount++;

+        removeEntry(e);

+        return e;

+    }

+

+    /**

+     *  Adds all the mappings in the specified map to this map, replacing any

+     *  mappings that already exist (as per {@link Map#putAll(Map)}).  The order

+     *  in which the entries are added is determined by the iterator returned

+     *  from {@link Map#entrySet()} for the specified map.

+     *

+     *  @param t the mappings that should be added to this map.

+     *

+     *  @exception NullPointerException if <code>t</code> is <code>null</code>

+     **/

+    public void putAll(Map t) {

+        Iterator iter = t.entrySet().iterator();

+        while (iter.hasNext()) {

+            Map.Entry entry = (Map.Entry)iter.next();

+            put(entry.getKey(), entry.getValue());

+        }

+    }

+

+    /**

+     *  Implements {@link Map#clear()}.

+     */

+    public void clear() {

+        modCount++;

+

+        // remove all from the underlying map

+        entries.clear();

+

+        // and the list

+        sentinel.next = sentinel;

+        sentinel.prev = sentinel;

+    }

+

+    /**

+     *  Implements {@link Map#equals(Object)}.

+     */

+    public boolean equals(Object obj) {

+        if (obj == null) return false;

+        if (obj == this) return true;

+

+        if (!(obj instanceof Map)) return false;

+

+        return entrySet().equals(((Map)obj).entrySet());

+    }

+

+    /**

+     *  Implements {@link Map#hashCode()}.

+     */

+    public int hashCode() {

+        return entrySet().hashCode();

+    }

+

+    /**

+     *  Provides a string representation of the entries within the map.  The

+     *  format of the returned string may change with different releases, so this

+     *  method is suitable for debugging purposes only.  If a specific format is

+     *  required, use {@link #entrySet()}.{@link Set#iterator() iterator()} and

+     *  iterate over the entries in the map formatting them as appropriate.

+     **/

+    public String toString() {

+        StringBuffer buf = new StringBuffer();

+        buf.append('[');

+        for (Entry pos = sentinel.next; pos != sentinel; pos = pos.next) {

+            buf.append(pos.getKey());

+            buf.append('=');

+            buf.append(pos.getValue());

+            if (pos.next != sentinel) {

+                buf.append(',');

+            }

+        }

+        buf.append(']');

+

+        return buf.toString();

+    }

+

+    /**

+     *  Implements {@link Map#keySet()}.

+     */

+    public Set keySet() {

+        return new AbstractSet() {

+

+            // required impls

+            public Iterator iterator() {

+                return new OrderedIterator(KEY);

+            }

+

+            public boolean remove(Object o) {

+                Entry e = SequencedHashMap.this.removeImpl(o);

+                return (e != null);

+            }

+

+            // more efficient impls than abstract set

+            public void clear() {

+                SequencedHashMap.this.clear();

+            }

+

+            public int size() {

+                return SequencedHashMap.this.size();

+            }

+

+            public boolean isEmpty() {

+                return SequencedHashMap.this.isEmpty();

+            }

+

+            public boolean contains(Object o) {

+                return SequencedHashMap.this.containsKey(o);

+            }

+

+        };

+    }

+

+    /**

+     *  Implements {@link Map#values()}.

+     */

+    public Collection values() {

+        return new AbstractCollection() {

+            // required impl

+            public Iterator iterator() {

+                return new OrderedIterator(VALUE);

+            }

+

+            public boolean remove(Object value) {

+                // do null comparison outside loop so we only need to do it once.  This

+                // provides a tighter, more efficient loop at the expense of slight

+                // code duplication.

+                if (value == null) {

+                    for (Entry pos = sentinel.next; pos != sentinel; pos = pos.next) {

+                        if (pos.getValue() == null) {

+                            SequencedHashMap.this.removeImpl(pos.getKey());

+                            return true;

+                        }

+                    }

+                }

+                else {

+                    for (Entry pos = sentinel.next; pos != sentinel; pos = pos.next) {

+                        if (value.equals(pos.getValue())) {

+                            SequencedHashMap.this.removeImpl(pos.getKey());

+                            return true;

+                        }

+                    }

+                }

+

+                return false;

+            }

+

+            // more efficient impls than abstract collection

+            public void clear() {

+                SequencedHashMap.this.clear();

+            }

+

+            public int size() {

+                return SequencedHashMap.this.size();

+            }

+

+            public boolean isEmpty() {

+                return SequencedHashMap.this.isEmpty();

+            }

+

+            public boolean contains(Object o) {

+                return SequencedHashMap.this.containsValue(o);

+            }

+        };

+    }

+

+    /**

+     *  Implements {@link Map#entrySet()}.

+     */

+    public Set entrySet() {

+        return new AbstractSet() {

+            // helper

+            private Entry findEntry(Object o) {

+                if (o == null) return null;

+                if (!(o instanceof Map.Entry)) return null;

+

+                Map.Entry e = (Map.Entry)o;

+                Entry entry = (Entry)entries.get(e.getKey());

+                if (entry != null && entry.equals(e))

+                    return entry;

+                else

+                    return null;

+            }

+

+            // required impl

+            public Iterator iterator() {

+                return new OrderedIterator(ENTRY);

+            }

+

+            public boolean remove(Object o) {

+                Entry e = findEntry(o);

+                if (e == null) return false;

+

+                return SequencedHashMap.this.removeImpl(e.getKey()) != null;

+            }

+

+            // more efficient impls than abstract collection

+            public void clear() {

+                SequencedHashMap.this.clear();

+            }

+

+            public int size() {

+                return SequencedHashMap.this.size();

+            }

+

+            public boolean isEmpty() {

+                return SequencedHashMap.this.isEmpty();

+            }

+

+            public boolean contains(Object o) {

+                return findEntry(o) != null;

+            }

+        };

+    }

+

+    // constants to define what the iterator should return on "next"

+    private static final int KEY = 0;

+    private static final int VALUE = 1;

+    private static final int ENTRY = 2;

+    private static final int REMOVED_MASK = 0x80000000;

+

+    private class OrderedIterator implements Iterator {

+        /**

+         *  Holds the type that should be returned from the iterator.  The value

+         *  should be either {@link #KEY}, {@link #VALUE}, or {@link #ENTRY}.  To

+         *  save a tiny bit of memory, this field is also used as a marker for when

+         *  remove has been called on the current object to prevent a second remove

+         *  on the same element.  Essientially, if this value is negative (i.e. the

+         *  bit specified by {@link #REMOVED_MASK} is set), the current position

+         *  has been removed.  If positive, remove can still be called.

+         **/

+        private int returnType;

+

+        /**

+         *  Holds the "current" position in the iterator.  When pos.next is the

+         *  sentinel, we've reached the end of the list.

+         **/

+        private Entry pos = sentinel;

+

+        /**

+         *  Holds the expected modification count.  If the actual modification

+         *  count of the map differs from this value, then a concurrent

+         *  modification has occurred.

+         **/

+        private transient long expectedModCount = modCount;

+

+        /**

+         *  Construct an iterator over the sequenced elements in the order in which

+         *  they were added.  The {@link #next()} method returns the type specified

+         *  by <code>returnType</code> which must be either {@link #KEY}, {@link

+         *  #VALUE}, or {@link #ENTRY}.

+         **/

+        public OrderedIterator(int returnType) {

+            //// Since this is a private inner class, nothing else should have

+            //// access to the constructor.  Since we know the rest of the outer

+            //// class uses the iterator correctly, we can leave of the following

+            //// check:

+            //if(returnType >= 0 && returnType <= 2) {

+            //  throw new IllegalArgumentException("Invalid iterator type");

+            //}

+

+            // Set the "removed" bit so that the iterator starts in a state where

+            // "next" must be called before "remove" will succeed.

+            this.returnType = returnType | REMOVED_MASK;

+        }

+

+        /**

+         *  Returns whether there is any additional elements in the iterator to be

+         *  returned.

+         *

+         *  @return <code>true</code> if there are more elements left to be

+         *  returned from the iterator; <code>false</code> otherwise.

+         **/

+        public boolean hasNext() {

+            return pos.next != sentinel;

+        }

+

+        /**

+         *  Returns the next element from the iterator.

+         *

+         *  @return the next element from the iterator.

+         *

+         *  @exception NoSuchElementException if there are no more elements in the

+         *  iterator.

+         *

+         *  @exception ConcurrentModificationException if a modification occurs in

+         *  the underlying map.

+         **/

+        public Object next() {

+            if (modCount != expectedModCount) {

+                throw new ConcurrentModificationException();

+            }

+            if (pos.next == sentinel) {

+                throw new NoSuchElementException();

+            }

+

+            // clear the "removed" flag

+            returnType = returnType & ~REMOVED_MASK;

+

+            pos = pos.next;

+            switch (returnType) {

+                case KEY:

+                    return pos.getKey();

+                case VALUE:

+                    return pos.getValue();

+                case ENTRY:

+                    return pos;

+                default:

+                    // should never happen

+                    throw new Error("bad iterator type: " + returnType);

+            }

+

+        }

+

+        /**

+         *  Removes the last element returned from the {@link #next()} method from

+         *  the sequenced map.

+         *

+         *  @exception IllegalStateException if there isn't a "last element" to be

+         *  removed.  That is, if {@link #next()} has never been called, or if

+         *  {@link #remove()} was already called on the element.

+         *

+         *  @exception ConcurrentModificationException if a modification occurs in

+         *  the underlying map.

+         **/

+        public void remove() {

+            if ((returnType & REMOVED_MASK) != 0) {

+                throw new IllegalStateException("remove() must follow next()");

+            }

+            if (modCount != expectedModCount) {

+                throw new ConcurrentModificationException();

+            }

+

+            SequencedHashMap.this.removeImpl(pos.getKey());

+

+            // update the expected mod count for the remove operation

+            expectedModCount++;

+

+            // set the removed flag

+            returnType = returnType | REMOVED_MASK;

+        }

+    }

+

+    // APIs maintained from previous version of SequencedHashMap for backwards

+    // compatibility

+

+    /**

+     * Creates a shallow copy of this object, preserving the internal structure

+     * by copying only references.  The keys and values themselves are not

+     * <code>clone()</code>'d.  The cloned object maintains the same sequence.

+     *

+     * @return A clone of this instance.

+     *

+     * @exception CloneNotSupportedException if clone is not supported by a

+     * subclass.

+     */

+    public Object clone() throws CloneNotSupportedException {

+        // yes, calling super.clone() silly since we're just blowing away all

+        // the stuff that super might be doing anyway, but for motivations on

+        // this, see:

+        // http://www.javaworld.com/javaworld/jw-01-1999/jw-01-object.html

+        SequencedHashMap map = (SequencedHashMap)super.clone();

+

+        // create new, empty sentinel

+        map.sentinel = createSentinel();

+

+        // create a new, empty entry map

+        // note: this does not preserve the initial capacity and load factor.

+        map.entries = new HashMap();

+

+        // add all the mappings

+        map.putAll(this);

+

+        // Note: We cannot just clone the hashmap and sentinel because we must

+        // duplicate our internal structures.  Cloning those two will not clone all

+        // the other entries they reference, and so the cloned hash map will not be

+        // able to maintain internal consistency because there are two objects with

+        // the same entries.  See discussion in the Entry implementation on why we

+        // cannot implement a clone of the Entry (and thus why we need to recreate

+        // everything).

+

+        return map;

+    }

+

+    /**

+     *  Returns the Map.Entry at the specified index

+     *

+     *  @exception ArrayIndexOutOfBoundsException if the specified index is

+     *  <code>&lt; 0</code> or <code>&gt;</code> the size of the map.

+     **/

+    private Map.Entry getEntry(int index) {

+        Entry pos = sentinel;

+

+        if (index < 0) {

+            throw new ArrayIndexOutOfBoundsException(index + " < 0");

+        }

+

+        // loop to one before the position

+        int i = -1;

+        while (i < (index - 1) && pos.next != sentinel) {

+            i++;

+            pos = pos.next;

+        }

+        // pos.next is the requested position

+

+        // if sentinel is next, past end of list

+        if (pos.next == sentinel) {

+            throw new ArrayIndexOutOfBoundsException(index + " >= " + (i + 1));

+        }

+

+        return pos.next;

+    }

+

+    /**

+     * Returns the key at the specified index.

+     *

+     *  @exception ArrayIndexOutOfBoundsException if the <code>index</code> is

+     *  <code>&lt; 0</code> or <code>&gt;</code> the size of the map.

+     */

+    public Object get(int index) {

+        return getEntry(index).getKey();

+    }

+

+    /**

+     * Returns the value at the specified index.

+     *

+     *  @exception ArrayIndexOutOfBoundsException if the <code>index</code> is

+     *  <code>&lt; 0</code> or <code>&gt;</code> the size of the map.

+     */

+    public Object getValue(int index) {

+        return getEntry(index).getValue();

+    }

+

+    /**

+     * Returns the index of the specified key.

+     */

+    public int indexOf(Object key) {

+        Entry e = (Entry)entries.get(key);

+        int pos = 0;

+        while (e.prev != sentinel) {

+            pos++;

+            e = e.prev;

+        }

+        return pos;

+    }

+

+    /**

+     * Returns a key iterator.

+     */

+    public Iterator iterator() {

+        return keySet().iterator();

+    }

+

+    /**

+     * Returns the last index of the specified key.

+     */

+    public int lastIndexOf(Object key) {

+        // keys in a map are guarunteed to be unique

+        return indexOf(key);

+    }

+

+    /**

+     * Returns a List view of the keys rather than a set view.  The returned

+     * list is unmodifiable.  This is required because changes to the values of

+     * the list (using {@link java.util.ListIterator#set(Object)}) will

+     * effectively remove the value from the list and reinsert that value at

+     * the end of the list, which is an unexpected side effect of changing the

+     * value of a list.  This occurs because changing the key, changes when the

+     * mapping is added to the map and thus where it appears in the list.

+     *

+     * <P>An alternative to this method is to use {@link #keySet()}

+     *

+     * @see #keySet()

+     * @return The ordered list of keys.

+     */

+    public List sequence() {

+        List l = new ArrayList(size());

+        Iterator iter = keySet().iterator();

+        while (iter.hasNext()) {

+            l.add(iter.next());

+        }

+

+        return Collections.unmodifiableList(l);

+    }

+

+    /**

+     * Removes the element at the specified index.

+     *

+     * @param index The index of the object to remove.

+     * @return      The previous value coressponding the <code>key</code>, or

+     *              <code>null</code> if none existed.

+     *

+     * @exception ArrayIndexOutOfBoundsException if the <code>index</code> is

+     * <code>&lt; 0</code> or <code>&gt;</code> the size of the map.

+     */

+    public Object remove(int index) {

+        return remove(get(index));

+    }

+

+    // per Externalizable.readExternal(ObjectInput)

+

+    /**

+     *  Deserializes this map from the given stream.

+     *

+     *  @param in the stream to deserialize from

+     *  @throws IOException if the stream raises it

+     *  @throws ClassNotFoundException if the stream raises it

+     */

+    public void readExternal(ObjectInput in)

+            throws IOException, ClassNotFoundException {

+        int size = in.readInt();

+        for (int i = 0; i < size; i++) {

+            Object key = in.readObject();

+            Object value = in.readObject();

+            put(key, value);

+        }

+    }

+

+    /**

+     *  Serializes this map to the given stream.

+     *

+     *  @param out  the stream to serialize to

+     *  @throws IOException  if the stream raises it

+     */

+    public void writeExternal(ObjectOutput out) throws IOException {

+        out.writeInt(size());

+        for (Entry pos = sentinel.next; pos != sentinel; pos = pos.next) {

+            out.writeObject(pos.getKey());

+            out.writeObject(pos.getValue());

+        }

+    }

+

+    // add a serial version uid, so that if we change things in the future

+    // without changing the format, we can still deserialize properly.

+    private static final long serialVersionUID = 3380552487888102930L;

+

+}

diff --git a/v1/src/common/org/apache/xmlbeans/impl/common/SequencedHashSet.java b/v1/src/common/org/apache/xmlbeans/impl/common/SequencedHashSet.java
new file mode 100644
index 0000000..2dbae51
--- /dev/null
+++ b/v1/src/common/org/apache/xmlbeans/impl/common/SequencedHashSet.java
@@ -0,0 +1,193 @@
+/*   Copyright 2004 The Apache Software Foundation
+ *
+ *   Licensed under the Apache License, Version 2.0 (the "License");
+ *   you may not use this file except in compliance with the License.
+ *   You may obtain a copy of the License at
+ *
+ *       http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *   Unless required by applicable law or agreed to in writing, software
+ *   distributed under the License is distributed on an "AS IS" BASIS,
+ *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *   See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.xmlbeans.impl.common;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.AbstractSet;
+import java.util.Set;
+
+/**
+ * Behaves the same way as JDK1.4 java.util.LinkedHashSet, but in JDK1.3 as well.
+ * Backed by SequencedHashMap to preserve iteration order.
+ */
+public class SequencedHashSet extends AbstractSet implements Set,
+    Cloneable /*, java.io.Serializable */
+{
+    private transient SequencedHashMap map;
+
+    // Dummy value
+    private static final Object EXISTS = new Object();
+
+    /**
+     * Constructs a new, empty sequenced set.
+     */
+    public SequencedHashSet()
+    {
+        map = new SequencedHashMap();
+    }
+
+    /**
+     * Constructs a new sequenced set containing the elements in the specified
+     * collection.
+     */
+    public SequencedHashSet(Collection c)
+    {
+        map = new SequencedHashMap(c.size());
+        addAll(c);
+    }
+
+    /**
+     * Constructs a new, empty sequenced set with
+     * the specified initial capacity and the specified load factor.
+     *
+     * @param      initialSize       the initial size of the hash map.
+     * @param      loadFactor        the load factor of the hash map.
+     */
+    public SequencedHashSet(int initialSize, float loadFactor)
+    {
+        map = new SequencedHashMap(initialSize, loadFactor);
+    }
+
+    /**
+     * Constructs a new, empty sequenced set with the specified initial size.
+     *
+     * @param      initialSize   the initial size of the hash table.
+     */
+    public SequencedHashSet(int initialSize)
+    {
+        map = new SequencedHashMap(initialSize);
+    }
+
+    /**
+     * Returns an iterator over the elements in this set.
+     */
+    public Iterator iterator()
+    {
+        return map.keySet().iterator();
+    }
+
+    /**
+     * Returns the number of elements in this set (its cardinality).
+     */
+    public int size()
+    {
+        return map.size();
+    }
+
+    /**
+     * Returns <tt>true</tt> if this set contains no elements.
+     */
+    public boolean isEmpty()
+    {
+        return map.isEmpty();
+    }
+
+    /**
+     * Returns <tt>true</tt> if this set contains the specified element.
+     */
+    public boolean contains(Object o)
+    {
+        return map.containsKey(o);
+    }
+
+    /**
+     * Adds the specified element to this set if it is not already present.
+     */
+    public boolean add(Object o)
+    {
+        return map.put(o, EXISTS)==null;
+    }
+
+    /**
+     * Removes the given element from this set if it is present.
+     */
+    public boolean remove(Object o)
+    {
+        return map.remove(o)==EXISTS;
+    }
+
+    /**
+     * Removes all of the elements from this set.
+     */
+    public void clear()
+    {
+        map.clear();
+    }
+
+    /**
+     * Returns a shallow copy of this set.
+     *
+     * @return a shallow copy of this set.
+     */
+    public Object clone() throws CloneNotSupportedException
+    {
+        SequencedHashSet set = (SequencedHashSet)super.clone();
+        set.map = (SequencedHashMap)map.clone();
+        return set;
+    }
+
+    /*
+     * Save the state of this <tt>SequencedHashSet</tt> instance to a stream.
+     *
+     * @serialData The size of the backing <tt>SequencedHashMap</tt> instance
+     *             (int), and its load factor (float) are emitted, followed by
+     *             the size of the set (the number of elements it contains)
+     *             (int), followed by all of its elements (each an Object) in
+     *             no particular order.
+    private synchronized void writeObject(java.io.ObjectOutputStream s)
+        throws java.io.IOException
+    {
+        // Write out any hidden serialization magic
+        s.defaultWriteObject();
+
+        // Write out size
+        s.writeInt(map.size());
+
+        // Write out all elements in the proper order.
+        for (Iterator i=map.keySet().iterator(); i.hasNext(); )
+            s.writeObject(i.next());
+    }
+     */
+
+    /*
+     * Reconstitute the <tt>HashSet</tt> instance from a stream (that is,
+     * deserialize it).
+    private synchronized void readObject(java.io.ObjectInputStream s)
+        throws java.io.IOException, ClassNotFoundException {
+        // Read in any hidden serialization magic
+        s.defaultReadObject();
+
+        // Read in HashMap capacity and load factor and create backing HashMap
+        //int capacity = s.readInt();
+        //float loadFactor = s.readFloat();
+        //map = new SequencedHashMap(capacity, loadFactor);
+
+        // Read in size
+        int size = s.readInt();
+        map = new SequencedHashMap(size);
+
+        // Read in all elements in the proper order.
+        for (int i=0; i < size; i++)
+        {
+            Object e = s.readObject();
+            map.put(e, EXISTS);
+        }
+        throw new RuntimeException("readObject in SequencedHashSet");
+    }
+     */
+}
diff --git a/v1/src/common/org/apache/xmlbeans/impl/common/SniffedXmlInputStream.java b/v1/src/common/org/apache/xmlbeans/impl/common/SniffedXmlInputStream.java
index 611af92..fb4e99d 100644
--- a/v1/src/common/org/apache/xmlbeans/impl/common/SniffedXmlInputStream.java
+++ b/v1/src/common/org/apache/xmlbeans/impl/common/SniffedXmlInputStream.java
@@ -15,13 +15,14 @@
 
 package org.apache.xmlbeans.impl.common;
 
+import org.apache.xmlbeans.XmlBeans;
+
 import java.io.InputStream;
 import java.io.BufferedInputStream;
 import java.io.IOException;
 import java.io.ByteArrayInputStream;
 import java.io.InputStreamReader;
 import java.io.Reader;
-import java.nio.charset.Charset;
 
 public class SniffedXmlInputStream extends BufferedInputStream
 {
@@ -135,17 +136,6 @@
         }
     }
 
-    // BUGBUG in JDK: Charset.forName is not threadsafe, so we'll prime it
-    // with the common charsets.
-
-    private static Charset dummy1 = Charset.forName("UTF-8");
-    private static Charset dummy2 = Charset.forName("UTF-16");
-    private static Charset dummy3 = Charset.forName("UTF-16BE");
-    private static Charset dummy4 = Charset.forName("UTF-16LE");
-    private static Charset dummy5 = Charset.forName("ISO-8859-1");
-    private static Charset dummy6 = Charset.forName("US-ASCII");
-    private static Charset dummy7 = Charset.forName("Cp1252");
-
 
     private String sniffForXmlDecl(String encoding) throws IOException
     {
@@ -155,9 +145,7 @@
             byte[] bytebuf = new byte[MAX_SNIFFED_BYTES];
             int bytelimit = readAsMuchAsPossible(bytebuf, 0, MAX_SNIFFED_BYTES);
 
-            // BUGBUG in JDK: Charset.forName is not threadsafe.
-            Charset charset = Charset.forName(encoding);
-            Reader reader = new InputStreamReader(new ByteArrayInputStream(bytebuf, 0, bytelimit), charset);
+            Reader reader = new InputStreamReader(new ByteArrayInputStream(bytebuf, 0, bytelimit), encoding);
             char[] buf = new char[bytelimit];
             int limit = 0;
             while (limit < bytelimit)
@@ -205,7 +193,8 @@
 
     private static int firstIndexOf(String s, char[] buf, int startAt, int limit)
     {
-        assert(s.length() > 0);
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(s.length() > 0);
         char[] lookFor = s.toCharArray();
 
         char firstchar = lookFor[0];
diff --git a/v1/src/common/org/apache/xmlbeans/impl/common/SniffedXmlReader.java b/v1/src/common/org/apache/xmlbeans/impl/common/SniffedXmlReader.java
index b497814..9a8f371 100644
--- a/v1/src/common/org/apache/xmlbeans/impl/common/SniffedXmlReader.java
+++ b/v1/src/common/org/apache/xmlbeans/impl/common/SniffedXmlReader.java
@@ -18,7 +18,6 @@
 import java.io.IOException;
 import java.io.Reader;
 import java.io.BufferedReader;
-import java.nio.charset.Charset;
 
 public class SniffedXmlReader extends BufferedReader
 {
@@ -44,17 +43,6 @@
         return total;
     }
 
-    // BUGBUG in JDK: Charset.forName is not threadsafe, so we'll prime it
-    // with the common charsets.
-
-    private static Charset dummy1 = Charset.forName("UTF-8");
-    private static Charset dummy2 = Charset.forName("UTF-16");
-    private static Charset dummy3 = Charset.forName("UTF-16BE");
-    private static Charset dummy4 = Charset.forName("UTF-16LE");
-    private static Charset dummy5 = Charset.forName("ISO-8859-1");
-    private static Charset dummy6 = Charset.forName("US-ASCII");
-    private static Charset dummy7 = Charset.forName("Cp1252");
-
 
     private String sniffForXmlDecl() throws IOException
     {
diff --git a/v1/src/common/org/apache/xmlbeans/impl/common/StringUtils.java b/v1/src/common/org/apache/xmlbeans/impl/common/StringUtils.java
new file mode 100644
index 0000000..ee98626
--- /dev/null
+++ b/v1/src/common/org/apache/xmlbeans/impl/common/StringUtils.java
@@ -0,0 +1,206 @@
+/*
+
+ ============================================================================
+                   The Apache Software License, Version 1.1
+ ============================================================================
+
+ Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without modifica-
+ tion, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of  source code must  retain the above copyright  notice,
+    this list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright notice,
+    this list of conditions and the following disclaimer in the documentation
+    and/or other materials provided with the distribution.
+
+ 3. The end-user documentation included with the redistribution, if any, must
+    include  the following  acknowledgment:  "This product includes  software
+    developed  by the  Apache Software Foundation  (http://www.apache.org/)."
+    Alternately, this  acknowledgment may  appear in the software itself,  if
+    and wherever such third-party acknowledgments normally appear.
+
+ 4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
+    used to  endorse or promote  products derived from  this software without
+    prior written permission. For written permission, please contact
+    apache@apache.org.
+
+ 5. Products  derived from this software may not  be called "Apache", nor may
+    "Apache" appear  in their name,  without prior written permission  of the
+    Apache Software Foundation.
+
+ THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
+ APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
+ INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
+ DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
+ ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
+ (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
+ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ This software  consists of voluntary contributions made  by many individuals
+ on  behalf of the Apache Software  Foundation and was  originally created by
+ Stefano Mazzocchi  <stefano@apache.org>. For more  information on the Apache
+ Software Foundation, please see <http://www.apache.org/>.
+
+*/
+package org.apache.xmlbeans.impl.common;
+
+import org.apache.xmlbeans.impl.regex.RegularExpression;
+import org.apache.xmlbeans.impl.regex.Match;
+
+import java.util.ArrayList;
+
+
+/**
+ * A collection of <code>String</code> handling utility methods.
+ *
+ * @author <a href="mailto:ricardo@apache.org">Ricardo Rocha</a>
+ * @author <a href="mailto:stefano@apache.org">Stefano Mazzocchi</a>
+ * @version StringUtils.java,v 1.1 2003/03/09 00:09:43
+ */
+public class StringUtils {
+
+    /**
+     * Counts the occurrence of the given char in the string.
+     *
+     * @param str The string to be tested
+     * @param c the char to be counted
+     * @return the occurrence of the character in the string.
+     */
+    public static int count(String str, char c) {
+        int index = 0;
+        char[] chars = str.toCharArray();
+        for (int i = 0; i < chars.length; i++) {
+            if (chars[i] == c) index++;
+        }
+        return index;
+    }
+
+    /**
+     * Matches two strings.
+     *
+     * @param a The first string
+     * @param b The second string
+     * @return the index where the two strings stop matching starting from 0
+     */
+    public static int matchStrings(String a, String b) {
+        int i;
+        char[] ca = a.toCharArray();
+        char[] cb = b.toCharArray();
+        int len = ( ca.length < cb.length ) ? ca.length : cb.length;
+
+        for (i = 0; i < len; i++) {
+            if (ca[i] != cb[i]) break;
+        }
+
+        return i;
+    }
+
+
+    public static boolean matches(String source, String pattern)
+    {
+        RegularExpression re = new RegularExpression(pattern);
+        return re.matches(source);
+    }
+
+
+    /**
+     * Splits a string by the delimiter character passed in.  Faster than using patterns.
+     */
+    public static String[] split(String source, char delim)
+    {
+        ArrayList result = new ArrayList(3);
+        int pos = 0;
+        int start = 0;
+        int len = source.length();
+
+        while (true)
+        {
+            while (pos < len && delim == source.charAt(pos))
+                pos++;
+            if (pos >= len)
+                break;
+            start = pos;
+            while (pos < len && delim != source.charAt(pos))
+                pos++;
+            result.add(source.substring(start, pos));
+        }
+
+        //If no delimiter found, return the whole string
+        if (result.size() == 0)
+            result.add(source);
+
+        return (String[]) result.toArray(new String[result.size()]);
+    }
+
+
+    /**
+     * Behaves exactly like JDK 1.4 String.split()
+     */
+    public static String[] split(String source, String delimPattern)
+    {
+        ArrayList result = new ArrayList(3);
+        RegularExpression re = new RegularExpression(delimPattern);
+        Match matcher = new Match();
+
+        if (re.matches(source, matcher))
+        {
+            int groups = matcher.getNumberOfGroups();
+            int start = 0;
+            for (int i = 0; i < groups; i++)
+            {
+                result.add(source.substring(start, matcher.getBeginning(i)));
+                start = matcher.getEnd(i);
+            }
+            result.add(source.substring(start));
+        }
+        else
+        {
+            //If no delimiter found, return the whole string
+            result.add(source);
+        }
+
+        return (String[]) result.toArray(new String[result.size()]);
+    }
+
+
+    /**
+     * Replaces the replacement string in the target StringBuffer using the Match parameter.
+     * It assumes that the pattern doesn't have nested captured groups.
+     */
+    public static void replaceAll(Match matcher, StringBuffer target, String replace)
+    {
+        int groups = matcher.getNumberOfGroups();
+        if (groups == 0)
+            return;
+
+        for (int i = 0; i < groups; i++)
+            target.replace(matcher.getBeginning(i), matcher.getEnd(i), replace);
+    }
+
+
+    /**
+     * Behaves exactly like JDK 1.4's String.replaceAll()
+     */
+    public static String replaceAll(String source, String pattern, String replace)
+    {
+        RegularExpression re = new RegularExpression(pattern);
+        Match matcher = new Match();
+
+        if (re.matches(source, matcher))
+        {
+            StringBuffer sb = new StringBuffer(source);
+            replaceAll(matcher, sb, replace);
+
+            return new String(sb);
+        }
+
+        //nothing to replace
+        return source;
+    }
+}
diff --git a/v1/src/common/org/apache/xmlbeans/impl/common/XPath.java b/v1/src/common/org/apache/xmlbeans/impl/common/XPath.java
index dd7a538..f210379 100644
--- a/v1/src/common/org/apache/xmlbeans/impl/common/XPath.java
+++ b/v1/src/common/org/apache/xmlbeans/impl/common/XPath.java
@@ -23,6 +23,7 @@
 import java.util.HashMap;
 import org.apache.xmlbeans.XmlError;
 import org.apache.xmlbeans.XmlException;
+import org.apache.xmlbeans.XmlBeans;
 import org.apache.xmlbeans.impl.common.XMLChar;
 
 public class XPath
@@ -80,7 +81,8 @@
         
         public final int element ( QName name )
         {
-            assert name != null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue( name != null );
             
             _stack.add( name );
             
@@ -130,7 +132,8 @@
 
             private void backtrack ( )
             {
-                assert _curr != null;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue ( _curr != null );
                 
                 if (_curr._hasBacktrack)
                 {
@@ -138,7 +141,8 @@
                     return;
                 }
 
-                assert !_curr._deep;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue ( !_curr._deep );
 
                 _curr = _curr._prev;
 
@@ -158,8 +162,11 @@
             
             int start ( )
             {
-                assert _curr != null;
-                assert _curr._prev == null;
+                if (XmlBeans.ASSERTS)
+                {
+                    XmlBeans.assertTrue ( _curr != null );
+                    XmlBeans.assertTrue ( _curr._prev == null );
+                }
 
                 if (_curr._name != null)
                     return _curr._flags;
@@ -180,7 +187,8 @@
                 if (_curr == null)
                     return 0;
 
-                assert _curr._name != null;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue ( _curr._name != null );
 
                 if (!_curr._attr && _curr.match( name ))
                 {
@@ -266,9 +274,10 @@
     {
         CompilationContext ( Map namespaces, String currentNodeVar )
         {
-            assert
-                _currentNodeVar == null ||
-                    _currentNodeVar.startsWith( "$" );
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue (
+                    _currentNodeVar == null ||
+                    _currentNodeVar.startsWith( "$" ) );
 
             if (currentNodeVar == null)
                 _currentNodeVar = "$this";
@@ -331,7 +340,8 @@
 
         void advance ( int count )
         {
-            assert count >= 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue ( count >= 0 );
             
             while ( count-- > 0 )
                 advance();
@@ -431,7 +441,8 @@
         
         private boolean tokenize ( String s )
         {
-            assert s.length() > 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue ( s.length() > 0 );
             
             int offset = 0;
 
@@ -450,9 +461,12 @@
 
         private boolean tokenize ( String s1, String s2 )
         {
-            assert s1.length() > 0;
-            assert s2.length() > 0;
-            
+            if (XmlBeans.ASSERTS)
+            {
+                XmlBeans.assertTrue ( s1.length() > 0 );
+                XmlBeans.assertTrue ( s2.length() > 0 );
+            }
+
             int offset = 0;
 
             while ( isWhitespace( offset ) )
@@ -478,10 +492,13 @@
 
         private boolean tokenize ( String s1, String s2, String s3 )
         {
-            assert s1.length() > 0;
-            assert s2.length() > 0;
-            assert s3.length() > 0;
-            
+            if (XmlBeans.ASSERTS)
+            {
+                XmlBeans.assertTrue ( s1.length() > 0 );
+                XmlBeans.assertTrue ( s2.length() > 0 );
+                XmlBeans.assertTrue ( s3.length() > 0 );
+            }
+
             int offset = 0;
 
             while ( isWhitespace( offset ) )
@@ -780,8 +797,8 @@
                 }
 
                 // The first part of a deep segment always backtracks to itself
-                
-                assert s._deep;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue ( s._deep );
 
                 s._hasBacktrack = true;
                 s._backtrack = s;
diff --git a/v1/src/common/org/apache/xmlbeans/impl/common/XmlEncodingSniffer.java b/v1/src/common/org/apache/xmlbeans/impl/common/XmlEncodingSniffer.java
index 614bbfe..d2c022d 100644
--- a/v1/src/common/org/apache/xmlbeans/impl/common/XmlEncodingSniffer.java
+++ b/v1/src/common/org/apache/xmlbeans/impl/common/XmlEncodingSniffer.java
@@ -15,6 +15,8 @@
 
 package org.apache.xmlbeans.impl.common;
 
+import org.apache.xmlbeans.XmlBeans;
+
 import java.io.Reader;
 import java.io.InputStream;
 import java.io.InputStreamReader;
@@ -55,7 +57,8 @@
         {
             SniffedXmlInputStream sniffed = new SniffedXmlInputStream(_stream);
             _xmlencoding = sniffed.getXmlEncoding();
-            assert(_xmlencoding != null);
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(_xmlencoding != null);
             _stream = sniffed;
         }
 
diff --git a/v1/src/common/org/apache/xmlbeans/impl/common/XmlErrorPrinter.java b/v1/src/common/org/apache/xmlbeans/impl/common/XmlErrorPrinter.java
index eae88ac..7b5bb0f 100644
--- a/v1/src/common/org/apache/xmlbeans/impl/common/XmlErrorPrinter.java
+++ b/v1/src/common/org/apache/xmlbeans/impl/common/XmlErrorPrinter.java
@@ -20,17 +20,17 @@
 import java.util.AbstractCollection;
 import java.util.Iterator;
 import java.util.Collections;
-import java.net.URI;
+import java.net.URL;
 
 public class XmlErrorPrinter extends AbstractCollection
 {
     private boolean _noisy;
-    private URI _baseURI;
+    private URL _baseURL;
 
-    public XmlErrorPrinter(boolean noisy, URI baseURI)
+    public XmlErrorPrinter(boolean noisy, URL baseURL)
     {
         _noisy = noisy;
-        _baseURI = baseURI;
+        _baseURL = baseURL;
     }
 
     public boolean add(Object o)
@@ -40,9 +40,9 @@
             XmlError err = (XmlError)o;
             if (err.getSeverity() == XmlError.SEVERITY_ERROR ||
                 err.getSeverity() == XmlError.SEVERITY_WARNING)
-                System.err.println(err.toString(_baseURI));
+                System.err.println(err.toString(_baseURL));
             else if (_noisy)
-                System.out.println(err.toString(_baseURI));
+                System.out.println(err.toString(_baseURL));
         }
         return false;
     }
diff --git a/v1/src/common/org/apache/xmlbeans/impl/common/readme.txt b/v1/src/common/org/apache/xmlbeans/impl/common/readme.txt
index ea25143..f4540d8 100644
--- a/v1/src/common/org/apache/xmlbeans/impl/common/readme.txt
+++ b/v1/src/common/org/apache/xmlbeans/impl/common/readme.txt
@@ -1,5 +1,5 @@
 There are isolated files in this directory taken from the Apache
-Xerces-J 2.0 project
+Xerces-J 2.0 project, Cocoon 2.1 project, Commons collections
 
 It contains very minor modifications including a change in namespace.
 
diff --git a/v1/src/repackage/repackage/EditBuildScript.java b/v1/src/repackage/repackage/EditBuildScript.java
index 6df16e8..a7a0bee 100644
--- a/v1/src/repackage/repackage/EditBuildScript.java
+++ b/v1/src/repackage/repackage/EditBuildScript.java
@@ -37,7 +37,7 @@
 
         String tokenStr = "<property name=\"" + args[ 1 ] + "\" value=\"";
                          
-        int i = sb.indexOf( tokenStr );
+        int i = new String(sb).indexOf( tokenStr );
 
         if (i < 0)
             throw new IllegalArgumentException( "Can't find token: " + tokenStr );
diff --git a/v1/src/repackage/repackage/Repackage.java b/v1/src/repackage/repackage/Repackage.java
index 2115e5d..31bf518 100644
--- a/v1/src/repackage/repackage/Repackage.java
+++ b/v1/src/repackage/repackage/Repackage.java
@@ -15,9 +15,12 @@
 
 package repackage;
 
+import org.apache.xmlbeans.impl.regex.RegularExpression;
+import org.apache.xmlbeans.impl.regex.Match;
+import org.apache.xmlbeans.impl.common.StringUtils;
+
 import java.io.*;
 import java.util.*;
-import java.util.regex.*;
 
 public class Repackage
 {
@@ -25,37 +28,37 @@
     {
         new Repackage().repackage( args );
     }
-    
+
     public void repackage ( String[] args ) throws Exception
     {
         if (args.length != 2 || !args[0].equals( "-repackage" ))
             throw new RuntimeException( "Usage: repackage -repackage [spec]" );
-        
+
         _repackager = new Repackager( args[ 1 ] );
 
         _fromPackages = _repackager.getFromPackages();
         _toPackages = _repackager.getToPackages();
-        
+
         _packagePattern =
-            Pattern.compile( "^\\s*package\\s+((?:\\w|\\.)*)\\s*;", Pattern.MULTILINE );
-        
+            new RegularExpression( "^\\s*package\\s+((?:\\w|\\.)*)\\s*;", "m");
+
         _moveAlongFiles = new ArrayList();
         _movedDirs = new HashMap();
-        
+
         File currentDir   = new File( "." );
         File buildDir     = new File( currentDir, "build" );
         File repackageDir = new File( buildDir, "repackage" );
 
         System.out.println( "Deleting repackage dir ..." );
-        
+
         recursiveDelete( repackageDir );
 
         repackageDir.mkdirs();
-        
+
         ArrayList files = new ArrayList();
 
         fillFiles( files, currentDir );
-        
+
         System.out.println( "Repackaging " + files.size() + " files ..." );
 
         int prefixLength = currentDir.getCanonicalPath().length();
@@ -71,7 +74,7 @@
 
             repackageFile( name );
         }
-        
+
         finishMovingFiles();
     }
 
@@ -92,7 +95,7 @@
     {
         _moveAlongFiles.add(name);
     }
-    
+
     public void finishMovingFiles ( )
         throws IOException
     {
@@ -100,12 +103,12 @@
         {
             String name = (String) i.next();
             String toName = name;
-            
+
             String srcDir = Repackager.dirForPath( name );
             String toDir = (String) _movedDirs.get( srcDir );
-            
+
             if (toDir != null)
-                toName = new File( toDir, new File( name ).getName() ).toString(); 
+                toName = new File( toDir, new File( name ).getName() ).toString();
 
             if (name.endsWith( ".html" ))
                 repackageNonJavaFile( name, toName );
@@ -120,39 +123,41 @@
         StringBuffer sb = readFile( new File( _sourceBase, name ) );
 
         _repackager.repackage( sb );
-        
+
         writeFile( new File( _targetBase, name ), sb );
     }
-    
+
     public void repackageNonJavaFile ( String sourceName, String targetName )
         throws IOException
     {
         StringBuffer sb = readFile( new File( _sourceBase, sourceName ) );
 
         _repackager.repackage( sb );
-        
+
         writeFile( new File( _targetBase, targetName ), sb );
     }
-    
+
     public void repackageJavaFile ( String name )
         throws IOException
     {
         StringBuffer sb = readFile( new File( _sourceBase, name ) );
 
-        Matcher packageMatcher = _packagePattern.matcher( sb );
+        Match packageMatcher = new Match();
 
-        if (packageMatcher.find())
+        if (_packagePattern.matches(sb.toString(), packageMatcher))
         {
-            String pkg = packageMatcher.group( 1 );
-            int pkgStart = packageMatcher.start( 1 );
-            int pkgEnd = packageMatcher.end( 1 );
-            
-            if (packageMatcher.find())
-                throw new RuntimeException( "Two package specifications found: " + name );
-            
-            List filePath = Repackager.splitPath( name, File.separatorChar );
+            String pkg = packageMatcher.getCapturedText( 1 );
+            int pkgStart = packageMatcher.getBeginning( 1 );
+            int pkgEnd = packageMatcher.getEnd( 1 );
+
+            //group 0 is the whole package statement, 1 is package name
+            if (packageMatcher.getNumberOfGroups() > 2)
+                throw new RuntimeException( "More than one package specifications found: "
+                        + name + ", numGroups=" + packageMatcher.getNumberOfGroups() );
+
+            List filePath = Arrays.asList(StringUtils.split( name, File.separatorChar ));
             String srcDir = Repackager.dirForPath( name );
-            
+
             // Sort the repackage spec so that longer from's are first to match
             // longest package first
 
@@ -178,7 +183,7 @@
                     break;
             }
 
-            List pkgPath = Repackager.splitPath( pkg, '.' );
+            List pkgPath = Arrays.asList(StringUtils.split( pkg, '.' ));
 
             int f = filePath.size() - 2;
 
@@ -190,7 +195,7 @@
 
             List changeTo = null;
             List changeFrom = null;
-            
+
             from:
             for ( int i = 0 ; i < _fromPackages.size() ; i ++ )
             {
@@ -221,11 +226,11 @@
                         newPkg += ".";
                         newName += File.separatorChar;
                     }
-                    
+
                     newPkg += changeTo.get( i );
                     newName += changeTo.get( i );
                 }
-                
+
                 for ( int i = filePath.size() - pkgPath.size() - 2 ; i >= 0 ; i-- )
                     newName = (String) filePath.get( i ) + File.separatorChar + newName;
 
@@ -241,7 +246,7 @@
 
                 name = newName;
                 String newDir = Repackager.dirForPath( name );
-                
+
                 if (!srcDir.equals(newDir))
                 {
                     _movedDirs.put(srcDir, newDir);
@@ -250,7 +255,7 @@
         }
 
         _repackager.repackage( sb );
-        
+
         writeFile( new File( _targetBase, name ), sb );
     }
 
@@ -258,7 +263,7 @@
         throws IOException
     {
         f.getParentFile().mkdirs();
-        
+
         OutputStream out = new FileOutputStream( f );
         Writer w = new OutputStreamWriter( out );
         Reader r = new StringReader( chars.toString() );
@@ -269,7 +274,7 @@
         w.close();
         out.close();
     }
-    
+
     StringBuffer readFile ( File f )
         throws IOException
     {
@@ -285,20 +290,20 @@
 
         return w.getBuffer();
     }
-    
+
     public void copyFile ( File from, File to ) throws IOException
     {
         to.getParentFile().mkdirs();
-        
+
         FileInputStream in = new FileInputStream( from );
         FileOutputStream out = new FileOutputStream( to );
 
         copy( in, out );
-        
+
         out.close();
         in.close();
     }
-    
+
     public void copy ( InputStream in, OutputStream out ) throws IOException
     {
         byte[] buffer = new byte [ 1024 * 16 ];
@@ -313,7 +318,7 @@
             out.write( buffer, 0, n );
         }
     }
-    
+
     public void copy ( Reader r, Writer w ) throws IOException
     {
         char[] buffer = new char [ 1024 * 16 ];
@@ -328,7 +333,7 @@
             w.write( buffer, 0, n );
         }
     }
-    
+
     public void fillFiles ( ArrayList files, File file ) throws IOException
     {
         if (!file.isDirectory())
@@ -341,7 +346,7 @@
 
         if (file.getName().equals( "build" ))
             return;
-        
+
         // Exclude CVS directories
         if (file.getName().equals( "CVS" ))
             return;
@@ -373,11 +378,11 @@
 
     private List _fromPackages;
     private List _toPackages;
-    
-    private Pattern _packagePattern;
+
+    private RegularExpression _packagePattern;
 
     private Repackager _repackager;
-    
+
     private Map _movedDirs;
     private List _moveAlongFiles;
 }
diff --git a/v1/src/repackage/repackage/Repackager.java b/v1/src/repackage/repackage/Repackager.java
index 39473dd..301578b 100644
--- a/v1/src/repackage/repackage/Repackager.java
+++ b/v1/src/repackage/repackage/Repackager.java
@@ -15,10 +15,12 @@
 
 package repackage;
 
+import org.apache.xmlbeans.impl.common.StringUtils;
+import org.apache.xmlbeans.impl.regex.Match;
+import org.apache.xmlbeans.impl.regex.RegularExpression;
+
 import java.util.List;
 import java.util.ArrayList;
-import java.util.regex.Pattern;
-import java.util.regex.Matcher;
 import java.io.File;
 
 public class Repackager
@@ -27,26 +29,26 @@
     {
         _fromPackages = new ArrayList();
         _toPackages = new ArrayList();
-        
-        List repackages = splitPath( repackageSpecs, ';' );
+
+        String[] repackages = StringUtils.split( repackageSpecs, ';' );
 
         // Sort the repackage spec so that longer from's are first to match
         // longest package first
-        
+
         for ( ; ; )
         {
             boolean swapped = false;
 
-            for ( int i = 1 ; i < repackages.size() ; i++ )
+            for ( int i = 1 ; i < repackages.length ; i++ )
             {
-                String spec1 = (String) repackages.get( i - 1 );
-                String spec2 = (String) repackages.get( i );
-                
+                String spec1 = repackages[ i - 1 ];
+                String spec2 = repackages[ i ];
+
                 if (spec1.indexOf( ':' ) < spec2.indexOf( ':' ))
                 {
-                    repackages.set( i - 1, spec2 );
-                    repackages.set( i, spec1 );
-                    
+                    repackages[ i - 1 ] = spec2;
+                    repackages[ i ] = spec1;
+
                     swapped = true;
                 }
             }
@@ -55,10 +57,10 @@
                 break;
         }
 
-        for ( int i = 0 ; i < repackages.size() ; i++ )
+        for ( int i = 0 ; i < repackages.length ; i++ )
         {
-            String spec = (String) repackages.get( i );
-            
+            String spec = repackages[ i ];
+
             int j = spec.indexOf( ':' );
 
             if (j < 0 || spec.indexOf( ':', j + 1 ) >= 0)
@@ -67,11 +69,11 @@
             String from = spec.substring( 0, j );
             String to = spec.substring( j + 1 );
 
-            _fromPackages.add( Repackager.splitPath( from, '.' ) );
-            _toPackages.add( Repackager.splitPath( to, '.' ) );
+            _fromPackages.add( StringUtils.split( from, '.' ) );
+            _toPackages.add( StringUtils.split( to, '.' ) );
         }
 
-        _fromMatchers = new Matcher [ _fromPackages.size() * 2 ];
+        _fromPatterns = new RegularExpression [ _fromPackages.size() * 2 ];
         _toPackageNames = new String [ _fromPackages.size() * 2 ];
 
         addPatterns( '.', 0 );
@@ -86,7 +88,7 @@
             List to = (List) _toPackages.get( i );
 
             String pattern = "";
-            
+
             for ( int j = 0 ; j < from.size() ; j++ )
             {
                 if (j > 0)
@@ -94,9 +96,9 @@
 
                 pattern += from.get( j );
             }
-            
+
             String toPackage = "";
-            
+
             for ( int j = 0 ; j < to.size() ; j++ )
             {
                 if (j > 0)
@@ -105,21 +107,20 @@
                 toPackage += to.get( j );
             }
 
-            _fromMatchers[ off + i ] = Pattern.compile( pattern ).matcher( null );
+            _fromPatterns[ off + i ] = new RegularExpression( pattern );
             _toPackageNames[ off + i ] = toPackage;
         }
     }
 
     public void repackage ( StringBuffer sb )
     {
-        for ( int i = 0 ; i < _fromMatchers.length ; i++ )
+        for ( int i = 0 ; i < _fromPatterns.length ; i++ )
         {
-            Matcher matcher = (Matcher) _fromMatchers[ i ];
+            Match matcher = new Match();
+            boolean matches = _fromPatterns[ i ].matches(sb.toString());
 
-            matcher.reset( sb );
-
-            while ( matcher.find() )
-                sb.replace( matcher.start(), matcher.end(), _toPackageNames[ i ] );
+            if (matches)
+                StringUtils.replaceAll(matcher, sb, _toPackageNames[ i ]);
         }
     }
 
@@ -132,29 +133,7 @@
     {
         return _toPackages;
     }
-    
-    public static ArrayList splitPath ( String path, char separator )
-    {
-        ArrayList components = new ArrayList();
-        
-        for ( ; ; )
-        {
-            int i = path.indexOf( separator );
 
-            if (i < 0)
-                break;
-
-            components.add( path.substring( 0, i ) );
-            
-            path = path.substring( i + 1 );
-        }
-
-        if (path.length() > 0)
-            components.add( path );
-
-        return components;
-    }
-    
     public static String dirForPath ( String path )
     {
         return new File(path).getParent();
@@ -162,7 +141,7 @@
 
     private List _fromPackages;
     private List _toPackages;
-    
-    private Matcher[] _fromMatchers;
+
+    private RegularExpression[] _fromPatterns;
     private String[]  _toPackageNames;
 }
\ No newline at end of file
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/BuiltinSchemaTypeSystem.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/BuiltinSchemaTypeSystem.java
index 8f53a26..c38d944 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/BuiltinSchemaTypeSystem.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/BuiltinSchemaTypeSystem.java
@@ -24,6 +24,7 @@
 import org.apache.xmlbeans.SchemaIdentityConstraint;
 import org.apache.xmlbeans.SchemaParticle;
 import org.apache.xmlbeans.QNameSet;
+import org.apache.xmlbeans.XmlBeans;
 import org.apache.xmlbeans.SchemaAttributeModel;
 import org.apache.xmlbeans.SchemaComponent;
 import org.apache.xmlbeans.impl.common.QNameHelper;
@@ -592,7 +593,8 @@
                 break;
 
             default:
-                assert(false);
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(false);
 
             case SchemaType.BTC_ANY_SIMPLE:
                 base = ST_ANY_TYPE; break;
@@ -702,7 +704,8 @@
         }
         else
         {
-            assert (btc == SchemaType.BTC_ANY_TYPE || btc == SchemaType.BTC_NOT_BUILTIN);
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue (btc == SchemaType.BTC_ANY_TYPE || btc == SchemaType.BTC_NOT_BUILTIN);
         }
         result.setBaseTypeRef(base == null ? null : base.getRef());
         result.setBaseDepth(base == null ? 0 : ((SchemaTypeImpl)base).getBaseDepth() + 1);
@@ -727,7 +730,8 @@
         switch (btc)
         {
             default:
-                assert(false);
+                if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(false);
 
             case SchemaType.BTC_ANY_TYPE:
             case SchemaType.BTC_ANY_SIMPLE:
@@ -888,7 +892,8 @@
         switch (btc)
         {
             default:
-                assert(false);
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(false);
 
             case SchemaType.BTC_ANY_TYPE:
             case SchemaType.BTC_NOT_BUILTIN:
@@ -1002,7 +1007,8 @@
         {
             org.apache.xmlbeans.impl.regex.RegularExpression p = null;
             try { p = org.apache.xmlbeans.impl.regex.SchemaRegularExpression.forPattern(pattern); }
-            catch (org.apache.xmlbeans.impl.regex.ParseException e) { assert false; }
+            catch (org.apache.xmlbeans.impl.regex.ParseException e)
+                { if (XmlBeans.ASSERTS) XmlBeans.assertTrue(false); }
             result.setPatterns(new org.apache.xmlbeans.impl.regex.RegularExpression[] {p});
         }
         result.setPatternFacet(hasPattern);
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaAttributeGroupImpl.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaAttributeGroupImpl.java
index 973fe14..bb8c40e 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaAttributeGroupImpl.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaAttributeGroupImpl.java
@@ -20,6 +20,7 @@
 import org.apache.xmlbeans.SchemaAttributeGroup;
 import org.apache.xmlbeans.XmlObject;
 import org.apache.xmlbeans.SchemaTypeSystem;
+import org.apache.xmlbeans.XmlBeans;
 
 public class SchemaAttributeGroupImpl implements SchemaAttributeGroup
 {
@@ -43,7 +44,8 @@
 
     public void init(QName name, String targetNamespace, boolean chameleon, boolean redefinition, XmlObject x)
     {
-        assert _name == null || name.equals( _name );
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(_name == null || name.equals( _name ));
 
         _name = name;
         _parseTNS = targetNamespace;
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaAttributeModelImpl.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaAttributeModelImpl.java
index f1febba..d741014 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaAttributeModelImpl.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaAttributeModelImpl.java
@@ -20,10 +20,11 @@
 import org.apache.xmlbeans.QNameSet;
 import org.apache.xmlbeans.QNameSetBuilder;
 import org.apache.xmlbeans.SchemaLocalAttribute;
+import org.apache.xmlbeans.impl.common.SequencedHashMap;
+
 import javax.xml.namespace.QName;
 
 import java.util.Map;
-import java.util.LinkedHashMap;
 
 public class SchemaAttributeModelImpl implements SchemaAttributeModel
 {
@@ -33,14 +34,14 @@
 
     public SchemaAttributeModelImpl()
     {
-        attrMap = new LinkedHashMap();
+        attrMap = new SequencedHashMap();
         wcSet = null;
         wcProcess = NONE;
     }
 
     public SchemaAttributeModelImpl(SchemaAttributeModel sam)
     {
-        attrMap = new LinkedHashMap();
+        attrMap = new SequencedHashMap();
         if (sam == null)
         {
             wcSet = null;
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaGlobalElementImpl.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaGlobalElementImpl.java
index 02db289..c75e3f7 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaGlobalElementImpl.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaGlobalElementImpl.java
@@ -19,16 +19,18 @@
 import org.apache.xmlbeans.SchemaComponent;
 import org.apache.xmlbeans.SchemaTypeSystem;
 import org.apache.xmlbeans.XmlObject;
+import org.apache.xmlbeans.impl.common.SequencedHashSet;
+
 import javax.xml.namespace.QName;
 
-import java.util.LinkedHashSet;
 import java.util.Set;
+import java.util.HashSet;
 
 public class SchemaGlobalElementImpl extends SchemaLocalElementImpl
         implements SchemaGlobalElement
 {
     private static final QName[] EMPTY_QNAME_ARRAY = new QName[0];
-    private Set _sgMembers = new LinkedHashSet();
+    private Set _sgMembers = new SequencedHashSet();
     private boolean _finalExt;
     private boolean _finalRest;
     private SchemaTypeSystem _typeSystem;
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaIdentityConstraintImpl.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaIdentityConstraintImpl.java
index f073367..0c4b04f 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaIdentityConstraintImpl.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaIdentityConstraintImpl.java
@@ -18,6 +18,7 @@
 import org.apache.xmlbeans.SchemaIdentityConstraint;
 import org.apache.xmlbeans.SchemaTypeSystem;
 import org.apache.xmlbeans.SchemaComponent;
+import org.apache.xmlbeans.XmlBeans;
 import org.apache.xmlbeans.XmlObject;
 import org.apache.xmlbeans.impl.common.XPath;
 import javax.xml.namespace.QName;
@@ -57,7 +58,8 @@
                 p = _selectorPath;
             }
             catch (XPath.XPathCompileException e) {
-                assert false: "Failed to compile xpath. Should be caught by compiler " + e;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(false);
                 return null;
             }
         }
@@ -73,12 +75,14 @@
     }
 
     public void setSelector(String selector) {
-        assert selector != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(selector != null);
         _selector = selector;
     }
 
     public void setFields(String[] fields) {
-        assert fields != null && fields.length > 0;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(fields != null && fields.length > 0);
         _fields = fields;
     }
 
@@ -96,7 +100,8 @@
                 p = _fieldPaths;
             }
             catch (XPath.XPathCompileException e) {
-                assert false: "Failed to compile xpath. Should be caught by compiler " + e;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(false);
                 return null;
             }
         }
@@ -121,7 +126,8 @@
     }
 
     public void setConstraintCategory(int type) {
-        assert type >= CC_KEY && type <= CC_UNIQUE;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(type >= CC_KEY && type <= CC_UNIQUE);
         _type = type;
     }
 
@@ -130,7 +136,8 @@
     }
 
     public void setName(QName name) {
-        assert name != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(name != null);
         _name = name;
     }
 
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaModelGroupImpl.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaModelGroupImpl.java
index fc21c47..0c82ec7 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaModelGroupImpl.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaModelGroupImpl.java
@@ -17,6 +17,7 @@
 
 import org.apache.xmlbeans.SchemaModelGroup;
 import org.apache.xmlbeans.SchemaComponent;
+import org.apache.xmlbeans.XmlBeans;
 import org.apache.xmlbeans.XmlObject;
 import org.apache.xmlbeans.SchemaTypeSystem;
 import javax.xml.namespace.QName;
@@ -43,7 +44,8 @@
 
     public void init(QName name, String targetNamespace, boolean chameleon, boolean redefinition, XmlObject x)
     {
-        assert _name == null || name.equals( _name );
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(_name == null || name.equals( _name ));
         
         _name = name;
         _parseTNS = targetNamespace;
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeCodePrinter.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeCodePrinter.java
index 0ce47d9..1f313a7 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeCodePrinter.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeCodePrinter.java
@@ -31,6 +31,7 @@
 import org.apache.xmlbeans.SchemaTypeSystem;
 import org.apache.xmlbeans.SchemaProperty;
 import org.apache.xmlbeans.SchemaStringEnumEntry;
+import org.apache.xmlbeans.XmlBeans;
 import org.apache.xmlbeans.XmlObject;
 
 /**
@@ -261,8 +262,8 @@
         emit("{");
         indent();
         emit("try { return (org.apache.xmlbeans.SchemaTypeSystem)Class.forName(\"org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl\", true, " + shortName + ".class.getClassLoader()).getConstructor(new Class[] { Class.class }).newInstance(new java.lang.Object[] { " + shortName + ".class }); }");
-        emit("catch (ClassNotFoundException e) { throw new RuntimeException(\"Cannot load org.apache.xmlbeans.impl.SchemaTypeSystemImpl: make sure xbean.jar is on the classpath.\", e); }");
-        emit("catch (Exception e) { throw new RuntimeException(\"Could not instantiate SchemaTypeSystemImpl (\" + e.toString() + \"): is the version of xbean.jar correct?\", e); }");
+        emit("catch (ClassNotFoundException e) { throw new org.apache.xmlbeans.XmlRuntimeException(\"Cannot load org.apache.xmlbeans.impl.SchemaTypeSystemImpl: make sure xbean.jar is on the classpath.\", e); }");
+        emit("catch (Exception e) { throw new org.apache.xmlbeans.XmlRuntimeException(\"Could not instantiate SchemaTypeSystemImpl (\" + e.toString() + \"): is the version of xbean.jar correct?\", e); }");
         outdent();
         emit("}");
         outdent();
@@ -473,9 +474,10 @@
                 emit(" * An XML attribute type.");
             }
             else
-                assert false;
+                if (XmlBeans.ASSERTS) XmlBeans.assertTrue( false );
 
-            assert( thename != null );
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue( thename != null );
             
             emit(" * Localname: " + thename.getLocalPart());
             emit(" * Namespace: " + thename.getNamespaceURI());
@@ -893,7 +895,8 @@
                 return "java.lang.Object";
 
             default:
-                assert(false);
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(false);
                 throw new IllegalStateException();
         }
     }
@@ -1079,7 +1082,8 @@
                 switch (sType.getDecimalSize())
                 {
                     default:
-                        assert(false);
+                        if (XmlBeans.ASSERTS)
+                            XmlBeans.assertTrue(false);
                     case SchemaType.SIZE_BIG_DECIMAL:
                         return "org.apache.xmlbeans.impl.values.JavaDecimalHolderEx";
                     case SchemaType.SIZE_BIG_INTEGER:
@@ -1110,7 +1114,8 @@
             case SchemaType.BTC_DURATION:
                 return "org.apache.xmlbeans.impl.values.JavaGDurationHolderEx";
             default:
-                assert(false) : "unrecognized primitive type";
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(false, "unrecognized primitive type");
                 return null;
         }
     }
@@ -1135,7 +1140,8 @@
 
             case SchemaType.ATOMIC:
                 // We should only get called for restrictions
-                assert(! sType.isBuiltinType());
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(! sType.isBuiltinType());
                 return getAtomicRestrictionType(sType);
 
             case SchemaType.LIST:
@@ -1648,7 +1654,8 @@
                        String xtype)
         throws IOException
     {
-        assert setIdentifier != null && identifier != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(setIdentifier != null && identifier != null);
 
         emit(xtype + " target = null;");
 
@@ -1679,7 +1686,8 @@
                 break;
 
             default:
-                assert false : "Bad behaviour type: " + nullBehaviour;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(false, "Bad behaviour type: " + nullBehaviour);
         }
 
         endBlock();
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeImpl.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeImpl.java
index 4ed4868..b92250e 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeImpl.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeImpl.java
@@ -18,6 +18,7 @@
 import org.apache.xmlbeans.impl.values.*;
 import org.apache.xmlbeans.impl.regex.RegularExpression;
 import org.apache.xmlbeans.impl.common.QNameHelper;
+import org.apache.xmlbeans.impl.common.SequencedHashSet;
 import org.apache.xmlbeans.impl.config.ExtensionHolder;
 import org.apache.xmlbeans.XmlObject;
 import org.apache.xmlbeans.SchemaGlobalElement;
@@ -37,6 +38,7 @@
 import org.apache.xmlbeans.StringEnumAbstractBase;
 import org.apache.xmlbeans.SchemaStringEnumEntry;
 import org.apache.xmlbeans.SchemaTypeLoader;
+import org.apache.xmlbeans.XmlBeans;
 
 import java.lang.reflect.Constructor;
 import java.util.*;
@@ -754,7 +756,7 @@
         // Add entries for each element property for substitution group members
         if (_propertyModelByElementName != null)
         {
-            _validSubstitutions = new LinkedHashSet();
+            _validSubstitutions = new SequencedHashSet();
             Collection eltProps = _propertyModelByElementName.values();
             for (Iterator it = eltProps.iterator() ; it.hasNext() ; )
             {
@@ -1088,8 +1090,8 @@
 
     private void computeFlatUnionModel()
     {
-        Set constituentMemberTypes = new LinkedHashSet();
-        Set allSubTypes = new LinkedHashSet();
+        Set constituentMemberTypes = new SequencedHashSet();
+        Set allSubTypes = new SequencedHashSet();
         SchemaType commonBaseType = null;
 
         allSubTypes.add(this);
@@ -1118,7 +1120,8 @@
                     commonBaseType = mImpl.getCommonBaseType(commonBaseType);
                     break;
                 default:
-                    assert(false);
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(false);
             }
         }
 
@@ -1891,7 +1894,8 @@
                 break;
             sImpl1 = (SchemaTypeImpl)sImpl1.getBaseType();
             sImpl2 = (SchemaTypeImpl)sImpl2.getBaseType();
-            assert(sImpl1 != null && sImpl2 != null); // must meet at anyType
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(sImpl1 != null && sImpl2 != null); // must meet at anyType
         }
         return sImpl1;
     }
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderBase.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderBase.java
index 7b7c249..4094738 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderBase.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderBase.java
@@ -16,6 +16,8 @@
 package org.apache.xmlbeans.impl.schema;
 
 import org.apache.xmlbeans.impl.common.QNameHelper;
+import org.apache.xmlbeans.impl.common.IOUtil;
+import org.apache.xmlbeans.impl.common.NetUtils;
 import org.apache.xmlbeans.impl.values.XmlStore;
 import org.apache.xmlbeans.impl.validator.ValidatingXMLInputStream;
 
@@ -26,11 +28,13 @@
 import org.apache.xmlbeans.SchemaModelGroup;
 import org.apache.xmlbeans.SchemaType;
 import org.apache.xmlbeans.SchemaTypeLoader;
+import org.apache.xmlbeans.XmlBeans;
 import org.apache.xmlbeans.XmlSaxHandler;
 import org.apache.xmlbeans.XmlException;
 import org.apache.xmlbeans.XmlObject;
 import org.apache.xmlbeans.XmlOptions;
 import org.apache.xmlbeans.XmlFactoryHook;
+import org.apache.xmlbeans.XmlRuntimeException;
 
 import java.lang.reflect.Method;
 import java.lang.reflect.InvocationTargetException;
@@ -86,13 +90,13 @@
         }
         catch ( InvocationTargetException e )
         {
-            IllegalStateException ise = new IllegalStateException( e.getCause().getMessage() );
+            XmlRuntimeException ise = new XmlRuntimeException( e.getTargetException().getMessage() );
             ise.initCause( e );
             throw ise;
         }
         catch ( Exception e )
         {
-            IllegalStateException ise = new IllegalStateException( e.getMessage() );
+            XmlRuntimeException ise = new XmlRuntimeException( e.getMessage() );
             ise.initCause( e );
             throw ise;
         }
@@ -114,7 +118,8 @@
         if (ref == null)
             return null;
         SchemaType result = ref.get();
-        assert(result != null);
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(result != null);
         return result;
     }
 
@@ -124,7 +129,8 @@
         if (ref == null)
             return null;
         SchemaType result = ref.get();
-        assert(result != null);
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(result != null);
         return result;
     }
 
@@ -134,7 +140,8 @@
         if (ref == null)
             return null;
         SchemaType result = ref.get();
-        assert(result != null);
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(result != null);
         return result;
     }
 
@@ -144,7 +151,8 @@
         if (ref == null)
             return null;
         SchemaModelGroup result = ref.get();
-        assert(result != null);
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(result != null);
         return result;
     }
 
@@ -154,7 +162,8 @@
         if (ref == null)
             return null;
         SchemaAttributeGroup result = ref.get();
-        assert(result != null);
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(result != null);
         return result;
     }
 
@@ -164,7 +173,8 @@
         if (ref == null)
             return null;
         SchemaGlobalElement result = ref.get();
-        assert(result != null);
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(result != null);
         return result;
     }
 
@@ -174,7 +184,8 @@
         if (ref == null)
             return null;
         SchemaGlobalAttribute result = ref.get();
-        assert(result != null);
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(result != null);
         return result;
     }
 
@@ -214,13 +225,13 @@
         if (options == null)
         {
             options = new XmlOptions();
-            options.put( XmlOptions.DOCUMENT_SOURCE_NAME, file.toURI().normalize().toString() );
+            options.put( XmlOptions.DOCUMENT_SOURCE_NAME, NetUtils.normalize(IOUtil.fileToURL(file).toString()) );
         }
 
         else if (! options.hasOption(XmlOptions.DOCUMENT_SOURCE_NAME))
         {
             options = new XmlOptions( options );
-            options.put( XmlOptions.DOCUMENT_SOURCE_NAME, file.toURI().normalize().toString() );
+            options.put( XmlOptions.DOCUMENT_SOURCE_NAME, NetUtils.normalize(IOUtil.fileToURL(file).toString()) );
         }
 
         InputStream fis = new FileInputStream( file );
@@ -259,8 +270,8 @@
 
             do {
                 conn = url.openConnection();
-                conn.addRequestProperty("User-Agent", "Apache XMLBeans/1.0.3");
-                conn.addRequestProperty("Accept", "application/xml, text/xml, */*");
+                conn.setRequestProperty("User-Agent", "Apache XMLBeans/1.0.3");
+                conn.setRequestProperty("Accept", "application/xml, text/xml, */*");
                 if (conn instanceof HttpURLConnection)
                 {
                     HttpURLConnection httpcon = (HttpURLConnection)conn;
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderImpl.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderImpl.java
index a480c1a..9eb9e42 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderImpl.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderImpl.java
@@ -23,8 +23,10 @@
 import org.apache.xmlbeans.SchemaAttributeGroup;
 import org.apache.xmlbeans.SchemaTypeSystem;
 import org.apache.xmlbeans.SchemaIdentityConstraint;
+import org.apache.xmlbeans.XmlBeans;
 import org.apache.xmlbeans.impl.common.QNameHelper;
 import org.apache.xmlbeans.impl.common.XBeanDebug;
+import org.apache.xmlbeans.impl.common.IdentityMap;
 import javax.xml.namespace.QName;
 
 import java.io.InputStream;
@@ -34,7 +36,6 @@
 import java.util.Collections;
 import java.util.ArrayList;
 import java.util.List;
-import java.util.IdentityHashMap;
 
 public class SchemaTypeLoaderImpl extends SchemaTypeLoaderBase
 {
@@ -118,7 +119,7 @@
     private static class SubLoaderList
     {
         private List theList = new ArrayList();
-        private Map seen = new IdentityHashMap();
+        private Map seen = new IdentityMap();
 
         private boolean add(SchemaTypeLoader loader)
         {
@@ -305,7 +306,8 @@
                 if (ts != null)
                 {
                     result = ts.findTypeRef(name);
-                    assert(result != null) : "Type system registered type " + QNameHelper.pretty(name) + " but does not return it";
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(result != null, "Type system registered type " + QNameHelper.pretty(name) + " but does not return it");
                 }
             }
             _typeCache.put(name, result);
@@ -329,7 +331,8 @@
                 if (ts != null)
                 {
                     result = ts.typeForClassname(classname);
-                    assert(result != null) : "Type system registered type " + classname + " but does not return it";
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(result != null, "Type system registered type " + classname + " but does not return it");
                 }
             }
             _classnameCache.put(classname, result);
@@ -351,7 +354,8 @@
                 if (ts != null)
                 {
                     result = ts.findDocumentTypeRef(name);
-                    assert(result != null) : "Type system registered element " + QNameHelper.pretty(name) + " but does not contain document type";
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(result != null, "Type system registered element " + QNameHelper.pretty(name) + " but does not contain document type");
                 }
             }
             _documentCache.put(name, result);
@@ -373,7 +377,8 @@
                 if (ts != null)
                 {
                     result = ts.findAttributeTypeRef(name);
-                    assert(result != null) : "Type system registered attribute " + QNameHelper.pretty(name) + " but does not contain attribute type";
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(result != null, "Type system registered attribute " + QNameHelper.pretty(name) + " but does not contain attribute type");
                 }
             }
             _attributeCache.put(name, result);
@@ -395,7 +400,8 @@
                 if (ts != null)
                 {
                     result = ts.findElementRef(name);
-                    assert(result != null) : "Type system registered element " + QNameHelper.pretty(name) + " but does not return it";
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(result != null, "Type system registered element " + QNameHelper.pretty(name) + " but does not return it");
                 }
             }
             _elementCache.put(name, result);
@@ -417,7 +423,8 @@
                 if (ts != null)
                 {
                     result = ts.findAttributeRef(name);
-                    assert(result != null) : "Type system registered attribute " + QNameHelper.pretty(name) + " but does not return it";
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(result != null, "Type system registered attribute " + QNameHelper.pretty(name) + " but does not return it");
                 }
             }
             _attributeCache.put(name, result);
@@ -439,7 +446,8 @@
                 if (ts != null)
                 {
                     result = ts.findModelGroupRef(name);
-                    assert(result != null) : "Type system registered model group " + QNameHelper.pretty(name) + " but does not return it";
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(result != null, "Type system registered model group " + QNameHelper.pretty(name) + " but does not return it");
                 }
             }
             _modelGroupCache.put(name, result);
@@ -461,7 +469,8 @@
                 if (ts != null)
                 {
                     result = ts.findAttributeGroupRef(name);
-                    assert(result != null) : "Type system registered attribute group " + QNameHelper.pretty(name) + " but does not return it";
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(result != null, "Type system registered attribute group " + QNameHelper.pretty(name) + " but does not return it");
                 }
             }
             _attributeGroupCache.put(name, result);
@@ -483,7 +492,8 @@
                 if (ts != null)
                 {
                     result = ts.findIdentityConstraintRef(name);
-                    assert(result != null) : "Type system registered identity constraint " + QNameHelper.pretty(name) + " but does not return it";
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(result != null, "Type system registered identity constraint " + QNameHelper.pretty(name) + " but does not return it");
                 }
             }
             _idConstraintCache.put(name, result);
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeSystemCompiler.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeSystemCompiler.java
index 8c9cf79..0dfb9a0 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeSystemCompiler.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeSystemCompiler.java
@@ -23,7 +23,6 @@
 import java.util.Map;
 import java.util.List;
 import java.util.Arrays;
-import java.net.URI;
 
 import org.w3.x2001.xmlSchema.SchemaDocument.Schema;
 import org.w3.x2001.xmlSchema.SchemaDocument;
@@ -45,7 +44,7 @@
         private XmlOptions options;
         private Collection errorListener;
         private boolean javaize;
-        private URI baseURI;
+        private String baseURI;
         private Map sourcesToCopyMap;
 
         public String getName()
@@ -118,12 +117,12 @@
             this.javaize = javaize;
         }
 
-        public URI getBaseURI()
+        public String getBaseURI()
         {
             return baseURI;
         }
 
-        public void setBaseURI(URI baseURI)
+        public void setBaseURI(String baseURI)
         {
             this.baseURI = baseURI;
         }
@@ -146,7 +145,7 @@
     
     /* package!!! */ static SchemaTypeSystemImpl compileImpl(
         String name, Schema[] schemas, Config[] configs,
-        SchemaTypeLoader linkTo, XmlOptions options, Collection outsideErrors, boolean javaize, URI baseURI, Map sourcesToCopyMap)
+        SchemaTypeLoader linkTo, XmlOptions options, Collection outsideErrors, boolean javaize, String baseURI, Map sourcesToCopyMap)
     {
         if (linkTo == null)
             throw new IllegalArgumentException("Must supply linkTo");
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeSystemImpl.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeSystemImpl.java
index 3227afc..9b61118 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeSystemImpl.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeSystemImpl.java
@@ -61,8 +61,14 @@
 import org.apache.xmlbeans.SimpleValue;
 import org.apache.xmlbeans.SchemaTypeLoaderException;
 import org.apache.xmlbeans.SchemaField;
+import org.apache.xmlbeans.XmlBeans;
+import org.apache.xmlbeans.XmlRuntimeException;
 import org.apache.xmlbeans.soap.SOAPArrayType;
 import org.apache.xmlbeans.soap.SchemaWSDLArrayType;
+
+import org.apache.xmlbeans.impl.common.SequencedHashMap;
+import org.apache.xmlbeans.impl.common.SequencedHashSet;
+
 import org.apache.xml.xmlbeans.x2004.x02.xbean.config.ConfigDocument.Config;
 import org.apache.xml.xmlbeans.x2004.x02.xbean.config.ConfigDocument;
 import org.w3.x2001.xmlSchema.SchemaDocument;
@@ -383,7 +389,7 @@
     private Map buildTypeRefsByClassname()
     {
         List allSeenTypes = new ArrayList();
-        Map result = new LinkedHashMap();
+        Map result = new SequencedHashMap();
         allSeenTypes.addAll(Arrays.asList(documentTypes()));
         allSeenTypes.addAll(Arrays.asList(attributeTypes()));
         allSeenTypes.addAll(Arrays.asList(globalTypes()));
@@ -404,7 +410,7 @@
 
     private Map buildTypeRefsByClassname(Map typesByClassname)
     {
-        Map result = new LinkedHashMap();
+        Map result = new SequencedHashMap();
         for (Iterator i = typesByClassname.keySet().iterator(); i.hasNext(); )
         {
             String className = (String)i.next();
@@ -415,7 +421,7 @@
 
     private static Map buildComponentRefMap(SchemaComponent[] components)
     {
-        Map result = new LinkedHashMap();
+        Map result = new SequencedHashMap();
         for (int i = 0; i < components.length; i++)
             result.put(components[i].getName(), components[i].getComponentRef());
         return result;
@@ -423,7 +429,7 @@
 
     private static Map buildDocumentMap(SchemaType[] types)
     {
-        Map result = new LinkedHashMap();
+        Map result = new SequencedHashMap();
         for (int i = 0; i < types.length; i++)
             result.put(types[i].getDocumentElementName(), types[i].getRef());
         return result;
@@ -431,7 +437,7 @@
 
     private static Map buildAttributeTypeMap(SchemaType[] types)
     {
-        Map result = new LinkedHashMap();
+        Map result = new SequencedHashMap();
         for (int i = 0; i < types.length; i++)
             result.put(types[i].getAttributeTypeAttributeName(), types[i].getRef());
         return result;
@@ -537,7 +543,8 @@
                                 SchemaType[] documentTypes,
                                 SchemaType[] attributeTypes)
     {
-        assert(_classloader == null);
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(_classloader == null);
         _localHandles = new HandlePool();
         _globalElements = buildComponentRefMap(globalElements);
         _globalAttributes = buildComponentRefMap(globalAttributes);
@@ -550,7 +557,8 @@
 
     public void loadFromStscState(StscState state)
     {
-        assert(_classloader == null);
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(_classloader == null);
         _localHandles = new HandlePool();
         _globalElements = buildComponentRefMap(state.globalElements());
         _globalAttributes = buildComponentRefMap(state.globalAttributes());
@@ -656,8 +664,8 @@
 
     class HandlePool
     {
-        private Map _handlesToRefs = new LinkedHashMap();
-        private Map _componentsToHandles = new LinkedHashMap(); // populated on write
+        private Map _handlesToRefs = new SequencedHashMap();
+        private Map _componentsToHandles = new SequencedHashMap(); // populated on write
         private boolean _started;
 
         /**
@@ -820,7 +828,7 @@
         void startWriteMode()
         {
             _started = true;
-            _componentsToHandles = new LinkedHashMap();
+            _componentsToHandles = new SequencedHashMap();
             for (Iterator i = _handlesToRefs.keySet().iterator(); i.hasNext(); )
             {
                 String handle = (String)i.next();
@@ -1505,7 +1513,8 @@
                     else
                     {
                         SchemaField sf = type.getContainerField();
-                        assert (sf != null);
+                        if (XmlBeans.ASSERTS)
+                            XmlBeans.assertTrue(sf != null);
                         if (sf.isAttribute())
                         {
                             writeString("_XR_" + QNameHelper.pretty(sf.getName()));
@@ -1519,7 +1528,8 @@
                     return;
 
                 default:
-                    assert(false);
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(false);
                     throw new SchemaTypeLoaderException("Cannot write handle for component " + comp, _name, _handle, SchemaTypeLoaderException.BAD_HANDLE);
             }
         }
@@ -1870,7 +1880,7 @@
                     attrModel.setWildcardProcess(readShort());
 
                     // Attribute Property Table
-                    Map attrProperties = new LinkedHashMap();
+                    Map attrProperties = new SequencedHashMap();
                     short attrPropCount = readShort();
                     for (int i = 0; i < attrPropCount; i++)
                     {
@@ -1898,7 +1908,7 @@
 
                         // Element Property Table
 
-                        elemProperties = new LinkedHashMap();
+                        elemProperties = new SequencedHashMap();
                         short elemPropCount = readShort();
                         for (int i = 0; i < elemPropCount; i++)
                         {
@@ -2204,7 +2214,8 @@
         void readExtensionsList()
         {
             int count = readShort();
-            assert count == 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(count == 0);
 
             for (int i = 0; i < count; i++)
             {
@@ -2229,7 +2240,7 @@
             }
             catch ( XmlException e )
             {
-                throw new RuntimeException( e.getMessage(), e );
+                throw new XmlRuntimeException( e.getMessage(), e );
             }
         }
 
@@ -2241,7 +2252,7 @@
             }
             catch ( XmlException e )
             {
-                throw new RuntimeException( e.getMessage(), e );
+                throw new XmlRuntimeException( e.getMessage(), e );
             }
         }
 
@@ -2493,7 +2504,7 @@
             if (!prop.isAttribute() && atLeast(2, 17, 0))
             {
                 short size = readShort();
-                LinkedHashSet qnames = new LinkedHashSet(size);
+                SequencedHashSet qnames = new SequencedHashSet();
                 for (int i = 0 ; i < size ; i++)
                     qnames.add(readQName());
                 prop.setAcceptedNames(qnames);
@@ -2562,7 +2573,8 @@
             switch (btc)
             {
                 default:
-                    assert(false);
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(false);
                 case 0:
                     return new XmlValueRef(typeref, null);
                 case -1:
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeVisitorImpl.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeVisitorImpl.java
index 8bbdb40..09814d5 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeVisitorImpl.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/SchemaTypeVisitorImpl.java
@@ -21,6 +21,7 @@
 import org.apache.xmlbeans.SchemaParticle;
 import org.apache.xmlbeans.SchemaLocalElement;
 import org.apache.xmlbeans.SchemaField;
+import org.apache.xmlbeans.XmlBeans;
 
 import java.util.Arrays;
 
@@ -328,7 +329,8 @@
             minmax: switch (_top._curPart.getParticleType())
             {
                 default:
-                    assert(false);
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(false);
 
                 case SchemaParticle.WILDCARD:
                     if (!_top._curPart.canStartWithElement(eltName))
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscChecker.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscChecker.java
index 344daec..6e39bd6 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscChecker.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscChecker.java
@@ -26,6 +26,7 @@
 import org.apache.xmlbeans.SchemaGlobalElement;
 import org.apache.xmlbeans.XmlID;
 import org.apache.xmlbeans.XmlAnySimpleType;
+import org.apache.xmlbeans.XmlBeans;
 import org.apache.xmlbeans.impl.common.XmlErrorContext;
 import org.apache.xmlbeans.impl.common.XBeanDebug;
 import org.apache.xmlbeans.impl.common.QNameHelper;
@@ -279,7 +280,8 @@
                     // 5.3 ... then the particle of the complex type definition itself must be a ·valid restriction· of the particle of the {content type} of the {base type definition}
                     SchemaParticle baseModel = baseType.getContentModel();
                     SchemaParticle derivedModel = sType.getContentModel();
-                    assert(baseModel != null && derivedModel != null);
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(baseModel != null && derivedModel != null);
                     if (baseModel == null || derivedModel == null)
                     {
                         XBeanDebug.logStackTrace("Null models that weren't caught by EMPTY_CONTENT: " + baseType + " (" + baseModel + "), " + sType + " (" + derivedModel + ")");
@@ -346,7 +348,8 @@
                             restrictionValid = false;
                             break;
                         default:
-                            assert false : XBeanDebug.logStackTrace("Unknown schema type for Derived Type");
+                            if (XmlBeans.ASSERTS)
+                                XmlBeans.assertTrue(false, XBeanDebug.logStackTrace("Unknown schema type for Derived Type"));
                     }
                     break;
                 case SchemaParticle.WILDCARD:
@@ -367,7 +370,8 @@
                             restrictionValid = nsRecurseCheckCardinality(baseModel, derivedModel, errors, context);
                             break;
                         default:
-                            assert false : XBeanDebug.logStackTrace("Unknown schema type for Derived Type");
+                            if (XmlBeans.ASSERTS)
+                                XmlBeans.assertTrue(false, XBeanDebug.logStackTrace("Unknown schema type for Derived Type"));
                     }
                     break;
                 case SchemaParticle.ALL:
@@ -390,7 +394,8 @@
                             restrictionValid = recurseUnordered(baseModel, derivedModel, errors, context);
                             break;
                         default:
-                            assert false : XBeanDebug.logStackTrace("Unknown schema type for Derived Type");
+                            if (XmlBeans.ASSERTS)
+                                XmlBeans.assertTrue(false, XBeanDebug.logStackTrace("Unknown schema type for Derived Type"));
                     }
                     break;
                 case SchemaParticle.CHOICE:
@@ -413,7 +418,8 @@
                             restrictionValid = mapAndSum(baseModel, derivedModel, errors, context);
                             break;
                         default:
-                            assert false : XBeanDebug.logStackTrace("Unknown schema type for Derived Type");
+                            if (XmlBeans.ASSERTS)
+                                XmlBeans.assertTrue(false, XBeanDebug.logStackTrace("Unknown schema type for Derived Type"));
                     }
                     break;
                 case SchemaParticle.SEQUENCE:
@@ -437,11 +443,13 @@
                             restrictionValid = recurse(baseModel, derivedModel, errors, context);
                             break;
                         default:
-                            assert false : XBeanDebug.logStackTrace("Unknown schema type for Derived Type");
+                            if (XmlBeans.ASSERTS)
+                                XmlBeans.assertTrue(false, XBeanDebug.logStackTrace("Unknown schema type for Derived Type"));
                     }
                     break;
                 default:
-                    assert false : XBeanDebug.logStackTrace("Unknown schema type for Base Type");
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(false, XBeanDebug.logStackTrace("Unknown schema type for Base Type"));
 
             }
         }
@@ -451,8 +459,11 @@
 
     private static boolean mapAndSum(SchemaParticle baseModel, SchemaParticle derivedModel, Collection errors, XmlObject context)  {
         // mapAndSum is call if base: CHOICE, derived: SEQUENCE
-        assert baseModel.getParticleType() == SchemaParticle.CHOICE;
-        assert derivedModel.getParticleType() == SchemaParticle.SEQUENCE;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(baseModel.getParticleType() == SchemaParticle.CHOICE);
+            XmlBeans.assertTrue(derivedModel.getParticleType() == SchemaParticle.SEQUENCE);
+        }
         boolean mapAndSumValid = true;
         // Schema Component Constraint: Particle Derivation OK (Sequence:Choice -- MapAndSum)
         // For a sequence group particle to be a ·valid restriction· of a choice group particle all of the following
@@ -545,9 +556,10 @@
         // base: ALL, derived: ELEMENT
         // base: CHOICE, derived: ELEMENT
         // base: SEQUENCE, derived: ELEMENT
-        assert (baseModel.getParticleType() == SchemaParticle.ALL && derivedModel.getParticleType() == SchemaParticle.ELEMENT)
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue((baseModel.getParticleType() == SchemaParticle.ALL && derivedModel.getParticleType() == SchemaParticle.ELEMENT)
                 || (baseModel.getParticleType() == SchemaParticle.CHOICE && derivedModel.getParticleType() == SchemaParticle.ELEMENT)
-                || (baseModel.getParticleType() == SchemaParticle.SEQUENCE && derivedModel.getParticleType() == SchemaParticle.ELEMENT);
+                || (baseModel.getParticleType() == SchemaParticle.SEQUENCE && derivedModel.getParticleType() == SchemaParticle.ELEMENT));
         // Schema Component Constraint: Particle Derivation OK (Elt:All/Choice/Sequence -- RecurseAsIfGroup)
 
         // For an element declaration particle to be a ·valid restriction· of a group particle
@@ -571,7 +583,8 @@
 
     private static boolean recurseLax(SchemaParticle baseModel, SchemaParticle derivedModel, Collection errors, XmlObject context)  {
         // recurseLax is called if base: CHOICE, derived: CHOICE
-        assert baseModel.getParticleType() == SchemaParticle.CHOICE && derivedModel.getParticleType() == SchemaParticle.CHOICE;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(baseModel.getParticleType() == SchemaParticle.CHOICE && derivedModel.getParticleType() == SchemaParticle.CHOICE);
         boolean recurseLaxValid = true;
         //Schema Component Constraint: Particle Derivation OK (Choice:Choice -- RecurseLax)
         // For a choice group particle to be a ·valid restriction· of another choice group particle all of the
@@ -627,7 +640,8 @@
 
     private static boolean recurseUnordered(SchemaParticle baseModel, SchemaParticle derivedModel, Collection errors, XmlObject context) {
         // recurseUnorder is called when base: ALL and derived: SEQ
-        assert baseModel.getParticleType() == SchemaParticle.ALL && derivedModel.getParticleType() == SchemaParticle.SEQUENCE;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(baseModel.getParticleType() == SchemaParticle.ALL && derivedModel.getParticleType() == SchemaParticle.SEQUENCE);
         boolean recurseUnorderedValid = true;
         // Schema Component Constraint: Particle Derivation OK (Sequence:All -- RecurseUnordered)
         // For a sequence group particle to be a ·valid restriction· of an all group particle all of the
@@ -828,10 +842,13 @@
         // base: ANY, derived: ALL
         // base: ANY, derived: CHOICE
         // base: ANY, derived: SEQUENCE
-        assert baseModel.getParticleType() == SchemaParticle.WILDCARD;
-        assert (derivedModel.getParticleType() == SchemaParticle.ALL)
-                || (derivedModel.getParticleType() == SchemaParticle.CHOICE)
-                || (derivedModel.getParticleType() == SchemaParticle.SEQUENCE);
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(baseModel.getParticleType() == SchemaParticle.WILDCARD);
+            XmlBeans.assertTrue((derivedModel.getParticleType() == SchemaParticle.ALL)
+                    || (derivedModel.getParticleType() == SchemaParticle.CHOICE)
+                    || (derivedModel.getParticleType() == SchemaParticle.SEQUENCE));
+        }
         boolean nsRecurseCheckCardinality = true;
         // For a group particle to be a ·valid restriction· of a wildcard particle all of the following must be true:
         // 1 Every member of the {particles} of the group is a ·valid restriction· of the wildcard as defined by Particle Valid (Restriction) (§3.9.6).
@@ -1189,8 +1206,11 @@
 
     private static boolean nsSubset(SchemaParticle baseModel, SchemaParticle derivedModel, Collection errors, XmlObject context) {
         // nsSubset is called when base: ANY, derived: ANY
-        assert baseModel.getParticleType() == SchemaParticle.WILDCARD;
-        assert derivedModel.getParticleType() == SchemaParticle.WILDCARD;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(baseModel.getParticleType() == SchemaParticle.WILDCARD);
+            XmlBeans.assertTrue(derivedModel.getParticleType() == SchemaParticle.WILDCARD);
+        }
         boolean nsSubset = false;
         // For a wildcard particle to be a ·valid restriction· of another wildcard particle all of the following must be true:
         // 1 R's occurrence range must be a valid restriction of B's occurrence range as defined by Occurrence Range OK (§3.9.6).
@@ -1214,7 +1234,8 @@
 
     private static boolean nsCompat(SchemaParticle baseModel, SchemaLocalElement derivedElement, Collection errors, XmlObject context) {
         // nsCompat is called when base: ANY, derived: ELEMENT
-        assert baseModel.getParticleType() == SchemaParticle.WILDCARD;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(baseModel.getParticleType() == SchemaParticle.WILDCARD);
         boolean nsCompat = false;
         // For an element declaration particle to be a ·valid restriction· of a wildcard particle all of the following must be true:
         // 1 The element declaration's {target namespace} is ·valid· with respect to the wildcard's {namespace constraint}
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscComplexTypeResolver.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscComplexTypeResolver.java
index 2f00384..79711f7 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscComplexTypeResolver.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscComplexTypeResolver.java
@@ -39,6 +39,8 @@
 import org.apache.xmlbeans.SchemaLocalAttribute;
 import org.apache.xmlbeans.SchemaLocalElement;
 import org.apache.xmlbeans.QNameSetSpecification;
+import org.apache.xmlbeans.XmlBeans;
+import org.apache.xmlbeans.impl.common.SequencedHashMap;
 
 public class StscComplexTypeResolver
 {
@@ -289,7 +291,7 @@
         int particleCode = translateParticleCode(parseGroup);
 
         // used to ensure consistency (doesn't become part of the result)
-        Map elementModel = new LinkedHashMap();
+        Map elementModel = new SequencedHashMap();
 
         // build content model and anonymous types
         SchemaParticle contentModel = translateContentModel(sImpl, parseGroup, targetNamespace, chameleon, particleCode, anonymousTypes, elementModel, false, null);
@@ -393,7 +395,7 @@
         int particleCode = translateParticleCode(parseEg);
 
         // used to ensure consistency (doesn't become part of the result)
-        Map elementModel = new LinkedHashMap();
+        Map elementModel = new SequencedHashMap();
 
         // build content model and anonymous types
         SchemaParticle contentModel = translateContentModel(
@@ -1108,7 +1110,8 @@
 
         // emitDBG("Translating content model for " + outerType);
         // indentDBG();
-        assert(particleCode != 0);
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(particleCode != 0);
 
         boolean hasChildren = false;
         BigInteger minOccurs;
@@ -1241,7 +1244,8 @@
                     break;
 
                 default:
-                    assert(false);
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(false);
                     throw new IllegalStateException();
             }
         }
@@ -1343,7 +1347,8 @@
                 return part;
 
             default:
-                assert(false);
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(false);
                 throw new IllegalStateException();
         }
         
@@ -1408,7 +1413,7 @@
 
     static Map buildAttributePropertyModelByQName(SchemaAttributeModel attrModel, SchemaType owner)
     {
-        Map result = new LinkedHashMap();
+        Map result = new SequencedHashMap();
         SchemaLocalAttribute[] attruses = attrModel.getAttributes();
 
         for (int i = 0; i < attruses.length; i++)
@@ -1441,14 +1446,15 @@
                 model = Collections.EMPTY_MAP;
                 break;
             default:
-                assert(false);
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(false);
                 throw new IllegalStateException();
         }
 
         if (model == null)
         {
             // build model for children
-            model = new LinkedHashMap();
+            model = new SequencedHashMap();
             SchemaParticle[] children = part.getParticleChildren();
 
             for (int i = 0; i < children.length; i++)
@@ -1468,7 +1474,8 @@
                         continue;
                     }
                     // consistency verified in an earlier step
-                    assert(oProp.getType().equals(iProp.getType()));
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(oProp.getType().equals(iProp.getType()));
 
                     mergeProperties(oProp, iProp, asSequence);
                 }
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscImporter.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscImporter.java
index 62c38a3..124e3aa 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscImporter.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscImporter.java
@@ -30,8 +30,6 @@
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.Arrays;
-import java.net.URI;
-import java.net.URISyntaxException;
 import java.net.URL;
 import java.net.MalformedURLException;
 import java.io.IOException;
@@ -43,6 +41,7 @@
 import org.apache.xmlbeans.XmlOptions;
 import org.apache.xmlbeans.SchemaTypeLoader;
 import org.apache.xmlbeans.impl.common.XmlErrorContext;
+import org.apache.xmlbeans.impl.common.StringUtils;
 import org.xml.sax.EntityResolver;
 import org.xml.sax.InputSource;
 import org.xml.sax.SAXException;
@@ -142,49 +141,12 @@
 
         // looks like a URL?
         int colon = path.indexOf(':');
-        if (colon > 1 && path.substring(0, colon).matches("^\\w+$"))
+        if (colon > 1 && StringUtils.matches(path.substring(0, colon), "^\\w+$"))
             return path;
 
         return PROJECT_URL_PREFIX + "/" + path.replace('\\', '/');
     }
 
-    private static URI parseURI(String s)
-    {
-        if (s == null)
-            return null;
-
-        try
-        {
-            return new URI(s);
-        }
-        catch (URISyntaxException syntax)
-        {
-                return null;
-        }
-    }
-    
-    //workaround for Sun bug # 4723726
-    private static URI resolve(URI base, String child)
-    {
-        URI ruri = base.resolve(child);
-        
-        //fix up normalization bug
-        if ("file".equals(ruri.getScheme()) && ! child.equals(ruri))
-        {
-            if (base.getPath().startsWith("//") && !ruri.getPath().startsWith("//"))
-            {
-                String path = "///".concat(ruri.getPath());
-                try
-                {
-                    ruri = new URI("file", null, path, ruri.getQuery(), ruri.getFragment());
-                }
-                catch(URISyntaxException uris)
-                {}
-            }
-        }
-        return ruri;
-    }
-
     public static class DownloadTable
     {
         /**
@@ -280,10 +242,26 @@
             // no location URL provided?  Then nothing to do.
             if (locationURL == null)
                 return null;
-            
+
             // First resolve relative URLs with respect to base URL for doc
-            URI baseURI = parseURI(baseURLForDoc(referencedBy));
-            String absoluteURL = baseURI == null ? locationURL : resolve(baseURI, locationURL).toString();
+            URL baseURL = null;
+            try
+            {
+                baseURL = new URL(baseURLForDoc(referencedBy));
+            }
+            catch (MalformedURLException mue)
+            {}
+
+            String absoluteURL = locationURL;
+            if (baseURL != null)
+            {
+                try
+                {
+                    absoluteURL = new URL(baseURL, locationURL).toString();
+                }
+                catch (MalformedURLException e)
+                { }
+            }
 
             // probe 1: ns+url - perfect match
             if (absoluteURL != null && targetNamespace != null)
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscJavaizer.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscJavaizer.java
index 6387171..d518586 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscJavaizer.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscJavaizer.java
@@ -26,6 +26,7 @@
 import org.apache.xmlbeans.impl.common.NameUtil;
 import org.apache.xmlbeans.impl.config.InterfaceExtension;
 import org.apache.xmlbeans.impl.config.ExtensionHolder;
+import org.apache.xmlbeans.XmlBeans;
 
 import javax.xml.namespace.QName;
 import java.math.BigInteger;
@@ -148,11 +149,11 @@
     {
         if (sImpl.isJavaized())
             return;
-
+        
         SchemaTypeImpl baseType = (SchemaTypeImpl)sImpl.getBaseType();
         if (baseType != null)
             skipJavaizingType(baseType);
-
+        
         sImpl.startJavaizing();
         secondPassProcessType(sImpl);
         sImpl.finishJavaizing();
@@ -338,7 +339,8 @@
                         javaname = "Item"; break;
                     case SchemaType.ATOMIC:
                     default:
-                        assert(false) : "Weird type " + sImpl.toString();
+                        if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(false, "Weird type " + sImpl.toString());
                         javaname = "Base"; break;
                 }
             }
@@ -501,7 +503,8 @@
             else
             {
                 theName = baseProp.getJavaPropertyName();
-                assert(!usedNames.contains(theName));
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(!usedNames.contains(theName));
                 usedNames.add(theName);
             }
 
@@ -655,7 +658,8 @@
                 return SchemaProperty.JAVA_CALENDAR;
 
             default:
-                assert(false) : "unrecognized code " + sType.getPrimitiveType().getBuiltinTypeCode();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(false, "unrecognized code " + sType.getPrimitiveType().getBuiltinTypeCode());
                 throw new IllegalStateException("unrecognized code " + sType.getPrimitiveType().getBuiltinTypeCode() + " of " + sType.getPrimitiveType().getName());
         }
     }
@@ -924,8 +928,12 @@
         }
 
         SchemaField sElt = sType.getContainerField();
-        assert(sElt != null);
-        assert(sType.getOuterType() == null);
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(sElt != null);
+            XmlBeans.assertTrue(sType.getOuterType() == null);
+        }
         return sElt.getName();
     }
+
 }
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscResolver.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscResolver.java
index 5868d8b..cafd640 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscResolver.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscResolver.java
@@ -19,6 +19,7 @@
 import org.apache.xmlbeans.XmlObject;
 import org.apache.xmlbeans.SchemaParticle;
 import org.apache.xmlbeans.QNameSet;
+import org.apache.xmlbeans.XmlBeans;
 
 import java.math.BigInteger;
 
@@ -93,7 +94,8 @@
 
     public static boolean resolveSubstitutionGroup(SchemaTypeImpl sImpl)
     {
-        assert sImpl.isDocumentType();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(sImpl.isDocumentType());
 
         if (sImpl.isSGResolved())
             return true;
@@ -139,7 +141,8 @@
             substitutionGroup = StscState.get().findDocumentType(
                 substitutionGroup.getSubstitutionGroup(), substitutionGroup.getChameleonNamespace());
 
-            assert substitutionGroup != null : "Could not find document type for: " + substitutionGroup.getSubstitutionGroup();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(substitutionGroup != null, "Could not find document type for: " + substitutionGroup.getSubstitutionGroup());
 
             if (! resolveSubstitutionGroup(substitutionGroup) )
                 substitutionGroup = null; // cyclic dependency - no subst group
@@ -153,10 +156,11 @@
 
     public static void resolveDocumentType ( SchemaTypeImpl sImpl )
     {
-        assert sImpl.isResolving();
-        
-        assert sImpl.isDocumentType();
-        
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(sImpl.isResolving());
+            XmlBeans.assertTrue(sImpl.isDocumentType());
+        }
 
         // translate the global element associated with this document type
         // and construct a content model which allows just that element
@@ -216,10 +220,12 @@
     
     public static void resolveAttributeType ( SchemaTypeImpl sImpl )
     {
-        assert sImpl.isResolving();
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(sImpl.isResolving());
+            XmlBeans.assertTrue(sImpl.isAttributeType());
+        }
 
-        assert sImpl.isAttributeType();
-        
         List anonTypes = new ArrayList();
 
         SchemaGlobalAttributeImpl attribute =
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscSimpleTypeResolver.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscSimpleTypeResolver.java
index 0f6803b..c7d323c 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscSimpleTypeResolver.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscSimpleTypeResolver.java
@@ -33,6 +33,7 @@
 import org.apache.xmlbeans.XmlByte;
 import org.apache.xmlbeans.XmlShort;
 import org.apache.xmlbeans.XmlUnsignedByte;
+import org.apache.xmlbeans.XmlBeans;
 import org.w3.x2001.xmlSchema.*;
 
 public class StscSimpleTypeResolver
@@ -55,7 +56,8 @@
     {
         SimpleType parseSt = (SimpleType)sImpl.getParseObject();
         
-        assert sImpl.isSimpleType();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(sImpl.isSimpleType());
 
         // Verify: have list, union, or restriction, but not more than one
         int count =
@@ -224,7 +226,8 @@
                 sImpl.setListItemTypeRef(itemImpl.getRef());
                 break;
             default:
-                assert(false);
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(false);
                 sImpl.setListItemTypeRef(BuiltinSchemaTypeSystem.ST_ANY_SIMPLE.getRef());
         }
 
@@ -586,7 +589,8 @@
                 }
                 return false;
             default:
-                assert(false);
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(false);
                 return false;
         }
     }
@@ -604,7 +608,8 @@
             case SchemaType.FACET_MAX_EXCLUSIVE:
                 return SchemaType.FACET_MAX_INCLUSIVE;
             default:
-                assert(false);
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(false);
                 throw new IllegalStateException();
         }
     }
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscState.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscState.java
index 465e5f3..3bbd023 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscState.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscState.java
@@ -15,8 +15,7 @@
 
 package org.apache.xmlbeans.impl.schema;
 
-import org.apache.xmlbeans.impl.common.XmlErrorContext;
-import org.apache.xmlbeans.impl.common.QNameHelper;
+import org.apache.xmlbeans.impl.common.*;
 import org.apache.xmlbeans.impl.config.SchemaConfig;
 import org.apache.xmlbeans.impl.config.ExtensionHolder;
 import org.apache.xmlbeans.XmlObject;
@@ -33,10 +32,10 @@
 import org.apache.xmlbeans.impl.values.XmlStringImpl;
 import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException;
 import org.apache.xmlbeans.impl.util.HexBin;
+import org.apache.xmlbeans.impl.common.SequencedHashMap;
 
 import java.util.*;
-import java.net.URISyntaxException;
-import java.net.URI;
+import java.net.URL;
 import java.io.File;
 
 
@@ -62,21 +61,21 @@
 
     private SchemaTypeLoader _importingLoader;
 
-    private Map _redefinedGlobalTypes        = new LinkedHashMap();
-    private Map _redefinedModelGroups        = new LinkedHashMap();
-    private Map _redefinedAttributeGroups    = new LinkedHashMap();
+    private Map _redefinedGlobalTypes        = new SequencedHashMap();
+    private Map _redefinedModelGroups        = new SequencedHashMap();
+    private Map _redefinedAttributeGroups    = new SequencedHashMap();
         
-    private Map _globalTypes        = new LinkedHashMap();
-    private Map _globalElements     = new LinkedHashMap();
-    private Map _globalAttributes   = new LinkedHashMap();
-    private Map _modelGroups        = new LinkedHashMap();
-    private Map _attributeGroups    = new LinkedHashMap();
-    private Map _documentTypes      = new LinkedHashMap();
-    private Map _attributeTypes     = new LinkedHashMap();
-    private Map _typesByClassname   = new LinkedHashMap();
+    private Map _globalTypes        = new SequencedHashMap();
+    private Map _globalElements     = new SequencedHashMap();
+    private Map _globalAttributes   = new SequencedHashMap();
+    private Map _modelGroups        = new SequencedHashMap();
+    private Map _attributeGroups    = new SequencedHashMap();
+    private Map _documentTypes      = new SequencedHashMap();
+    private Map _attributeTypes     = new SequencedHashMap();
+    private Map _typesByClassname   = new SequencedHashMap();
     private Map _misspelledNames    = new HashMap();
     private Set _processingGroups   = new HashSet();
-    private Map _idConstraints      = new LinkedHashMap();
+    private Map _idConstraints      = new SequencedHashMap();
     private Set _namespaces         = new HashSet();
     private boolean _noUpa;
     private boolean _noPvr;
@@ -161,7 +160,7 @@
             XmlError.forLocation(
               message,
               XmlError.SEVERITY_ERROR,
-              location.toURI().toString(), 0, 0, 0);
+              IOUtil.fileToURL(location).toString(), 0, 0, 0);
         errorListener.add(err);
     }
 
@@ -243,8 +242,8 @@
 
         try
         {
-            URI uri = new URI(uriString);
-            return uri.getScheme().equalsIgnoreCase("file");
+            URL url = new URL(uriString);
+            return url.getProtocol().equalsIgnoreCase("file");
         }
         catch (Exception e)
         {
@@ -734,13 +733,15 @@
 
     void startProcessing(Object obj)
     {
-        assert(!_processingGroups.contains(obj));
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(!_processingGroups.contains(obj));
         _processingGroups.add(obj);
     }
 
     void finishProcessing(Object obj)
     {
-        assert(_processingGroups.contains(obj));
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(_processingGroups.contains(obj));
         _processingGroups.remove(obj);
     }
 
@@ -880,7 +881,8 @@
                 basicMessage = "Identity constraint '" + QNameHelper.pretty(itemName) + "' not found.";
                 break;
             default:
-                assert(false);
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(false);
                 basicMessage = "Definition " + QNameHelper.pretty(itemName) + " not found.";
                 break;
         }
@@ -984,7 +986,7 @@
     /**
      * The base URI to use for nice filenames when saving sources.
      */
-    public void setBaseUri(URI uri)
+    public void setBaseUri(String uri)
     {
         _baseURI = uri;
     }
@@ -1015,24 +1017,18 @@
         {
             // looks like a URL?
             int colon = uri.indexOf(':');
-            if (colon <= 1 || !uri.substring(0, colon).matches("^\\w+$"))
+            if (colon <= 1 || !StringUtils.matches(uri.substring(0, colon), "^\\w+$"))
                 uri = PROJECT_URL_PREFIX + "/" + uri.replace('\\', '/');
         }
 
         // now relativize against that...
         if (_baseURI != null)
         {
-            try
-            {
-                URI relative = _baseURI.relativize(new URI(uri));
-                if (!relative.isAbsolute())
-                    return relative.toString();
-                else
-                    uri = relative.toString();
-            }
-            catch (URISyntaxException e)
-            {
-            }
+            String relative = NetUtils.relativize(_baseURI, uri);
+            if (relative.charAt(0) != '/')
+                return relative;
+            else
+                uri = relative;
         }
         
         if (!forSavedFilename)
@@ -1075,6 +1071,6 @@
     }
 
     Map _sourceForUri = new HashMap();
-    URI _baseURI = URI.create(PROJECT_URL_PREFIX + "/");
+    String _baseURI = PROJECT_URL_PREFIX + "/";
     SchemaTypeLoader _s4sloader = XmlBeans.typeLoaderForClassLoader(SchemaDocument.class.getClassLoader());
 }
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscTranslator.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscTranslator.java
index c462f76..6e27651 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscTranslator.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/schema/StscTranslator.java
@@ -45,6 +45,7 @@
 import org.apache.xmlbeans.SchemaGlobalAttribute;
 import org.apache.xmlbeans.XmlAnySimpleType;
 import org.apache.xmlbeans.XmlInteger;
+import org.apache.xmlbeans.XmlBeans;
 
 import javax.xml.namespace.QName;
 
@@ -506,7 +507,8 @@
                 // recovery: ignore
             }
             
-            assert(xsdElt instanceof LocalElement);
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(xsdElt instanceof LocalElement);
             SchemaGlobalElement referenced = state.findGlobalElement(ref, chameleon ? targetNamespace : null);
             if (referenced == null)
             {
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/validator/ValidatingXMLInputStream.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/validator/ValidatingXMLInputStream.java
index 1a9ac3a..2e916c3 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/validator/ValidatingXMLInputStream.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/validator/ValidatingXMLInputStream.java
@@ -28,6 +28,7 @@
 import org.apache.xmlbeans.XmlError;
 import org.apache.xmlbeans.XmlOptions;
 import org.apache.xmlbeans.XMLStreamValidationException;
+import org.apache.xmlbeans.XmlBeans;
 import java.util.Map;
 import java.util.AbstractCollection;
 import java.util.Iterator;
@@ -334,7 +335,8 @@
     {
         public boolean add(Object o)
         {
-            assert ValidatingXMLInputStream.this._exception == null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(ValidatingXMLInputStream.this._exception == null);
             
             ValidatingXMLInputStream.this._exception = 
                 new XMLStreamValidationException( (XmlError)o );
@@ -356,7 +358,8 @@
     private void nextEvent ( int kind )
         throws XMLStreamException
     {
-        assert _exception == null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(_exception == null);
         
         _validator.nextEvent( kind, this );
 
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/validator/Validator.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/validator/Validator.java
index 7551784..1cd285f 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/validator/Validator.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/validator/Validator.java
@@ -52,6 +52,7 @@
 import org.apache.xmlbeans.SchemaParticle;
 import org.apache.xmlbeans.SchemaType;
 import org.apache.xmlbeans.SchemaTypeLoader;
+import org.apache.xmlbeans.XmlBeans;
 import org.apache.xmlbeans.XmlError;
 import org.apache.xmlbeans.XmlObject;
 import org.apache.xmlbeans.XmlOptions;
@@ -120,7 +121,8 @@
 
             if (_errorListener != null)
             {
-                assert event != null;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(event != null);
 
                 _errorListener.add(
                     XmlError.forCursor( msg, severity, event.getLocationAsCursor() ) );
@@ -178,9 +180,9 @@
         }
         else
         {
-            assert
-                kind == BEGIN || kind == ATTR ||
-                    kind == END || kind == TEXT || kind == ENDATTRS;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue( kind == BEGIN || kind == ATTR ||
+                    kind == END || kind == TEXT || kind == ENDATTRS);
 
             switch ( kind )
             {
@@ -213,7 +215,8 @@
 
             QName name = event.getName();
 
-            assert name != null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(name != null);
 
             state._isEmpty = false;
 
@@ -285,8 +288,8 @@
             }
             else
             {
-                assert
-                    currentParticle.getParticleType() == SchemaParticle.ELEMENT;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(currentParticle.getParticleType() == SchemaParticle.ELEMENT);
 
                 // If the current element particle name does not match the name
                 // of the event, then the current element is a substitute for
@@ -305,7 +308,8 @@
 
                     SchemaGlobalElement newField = _globalTypes.findElement(name);
 
-                    assert newField != null;
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(newField != null);
 
                     if (newField != null)
                     {
@@ -322,7 +326,8 @@
             elementType = elementField.getType();
         }
 
-        assert elementType != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(elementType != null);
 
         //
         // the no-type is always invalid (even if there is an xsi:type)
@@ -621,7 +626,8 @@
             if (wildcardProcess == SchemaAttributeModel.LAX)
                 return;
 
-            assert wildcardProcess == SchemaAttributeModel.STRICT;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(wildcardProcess == SchemaAttributeModel.STRICT);
 
             emitFieldError(
                 event,
@@ -838,7 +844,8 @@
 
         SchemaParticle currentParticle ( )
         {
-            assert _visitor != null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(_visitor != null);
             return _visitor.currentParticle();
         }
 
@@ -970,7 +977,8 @@
         if (!type.isSimpleType() &&
                 type.getContentType() != SchemaType.SIMPLE_CONTENT)
         {
-            assert false;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(false);
             // throw new RuntimeException( "Not a simple type" );
             return null; // should never happen
         }
@@ -1060,7 +1068,8 @@
         if (!type.isSimpleType() &&
                 type.getContentType() != SchemaType.SIMPLE_CONTENT)
         {
-            assert false;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(false);
             throw new RuntimeException( "Not a simple type" );
         }
 
@@ -1083,7 +1092,8 @@
     {
         // Now we should have only an atomic type to validate
 
-        assert type.getSimpleVariety() == SchemaType.ATOMIC;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(type.getSimpleVariety() == SchemaType.ATOMIC);
 
         // Record the current error state to see if any new errors are made
         int errorState = _errorState;
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/values/JavaDecimalHolder.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/values/JavaDecimalHolder.java
index 8ce09d1..b21f607 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/values/JavaDecimalHolder.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/values/JavaDecimalHolder.java
@@ -20,6 +20,7 @@
 
 import org.apache.xmlbeans.SchemaType;
 import org.apache.xmlbeans.XmlObject;
+import org.apache.xmlbeans.XmlBeans;
 import org.apache.xmlbeans.impl.common.ValidationContext;
 import org.apache.xmlbeans.impl.schema.BuiltinSchemaTypeSystem;
 
@@ -42,7 +43,7 @@
         try {
             set_BigDecimal(new BigDecimal(s));
         }
-        catch (NumberFormatException e)
+        catch (Exception e) //jdk 1.3 doesn't always check length
         {
             _voorVc.invalid("Invalid Decimal");
         }
@@ -156,7 +157,8 @@
      * This differs from BigDecimal.hashCode()
      */
     protected int decimalHashCode() {
-        assert _value.scale() > 0;
+        if (XmlBeans.ASSERTS)
+         XmlBeans.assertTrue(_value.scale() > 0);
 
         // Get decimal value as string, and strip off zeroes on the right
         String strValue = _value.toString();
@@ -164,7 +166,8 @@
         for (i = strValue.length() - 1 ; i >= 0 ; i --)
             if (strValue.charAt(i) != '0') break;
 
-        assert strValue.indexOf('.') < i;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(strValue.indexOf('.') < i);
 
         // Return the canonicalized string hashcode
         return strValue.substring(0, i + 1).hashCode();
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/values/JavaDecimalHolderEx.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/values/JavaDecimalHolderEx.java
index 3eeaaf9..ccd3848 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/values/JavaDecimalHolderEx.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/values/JavaDecimalHolderEx.java
@@ -42,7 +42,7 @@
         try {
             v = new BigDecimal(s);
         }
-        catch (NumberFormatException e)
+        catch (Exception e) //jdk 1.3 doesn't always check length
         {
             _voorVc.invalid("Invalid Decimal");
         }
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/values/JavaGDateHolderEx.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/values/JavaGDateHolderEx.java
index d78043c..608f165 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/values/JavaGDateHolderEx.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/values/JavaGDateHolderEx.java
@@ -20,6 +20,7 @@
 import org.apache.xmlbeans.GDateSpecification;
 import org.apache.xmlbeans.GDateBuilder;
 import org.apache.xmlbeans.SchemaType;
+import org.apache.xmlbeans.XmlBeans;
 import org.apache.xmlbeans.impl.common.ValidationContext;
 import org.apache.xmlbeans.impl.common.QNameHelper;
 
@@ -165,7 +166,8 @@
             case SchemaType.BTC_G_YEAR:
                 return _value.getYear();
             default:
-                assert(false);
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(false);
                 throw new IllegalStateException();
         }
     }
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/values/JavaQNameHolder.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/values/JavaQNameHolder.java
index a07932b..410a757 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/values/JavaQNameHolder.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/values/JavaQNameHolder.java
@@ -20,6 +20,7 @@
 import org.apache.xmlbeans.SchemaType;
 import org.apache.xmlbeans.XmlAnySimpleType;
 import org.apache.xmlbeans.XmlObject;
+import org.apache.xmlbeans.XmlBeans;
 import org.apache.xmlbeans.impl.common.ValidationContext;
 import org.apache.xmlbeans.impl.common.XMLChar;
 import org.apache.xmlbeans.impl.common.QNameHelper;
@@ -77,7 +78,8 @@
         
         String prefix = nsm.find_prefix_for_nsuri( namespace, null );
 
-        assert prefix != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(prefix != null);
         
         return prefix + ":" + localPart;
     }
@@ -151,7 +153,8 @@
     // BUGBUG - having prefix here may not work
     protected void set_QName(QName name)
     {
-        assert name != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(name != null);
         
         // Sync force of creation of namesapce mapping ..
         
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/values/NamespaceContext.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/values/NamespaceContext.java
index 75b5608..1bae693 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/values/NamespaceContext.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/values/NamespaceContext.java
@@ -19,6 +19,7 @@
 
 import org.apache.xmlbeans.XmlObject;
 import org.apache.xmlbeans.XmlCursor;
+import org.apache.xmlbeans.XmlBeans;
 
 import java.util.ArrayList;
 import java.util.Map;
@@ -137,7 +138,8 @@
                 return ((PrefixResolver)_obj).getNamespaceForPrefix(prefix);
                 
             default:
-                assert false : "Improperly initialized NamespaceContext.";
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(false, "Improperly initialized NamespaceContext.");
                 return null;
         }
     }
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/values/XmlComplexContentImpl.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/values/XmlComplexContentImpl.java
index 653a592..a5daaa0 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/values/XmlComplexContentImpl.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/values/XmlComplexContentImpl.java
@@ -47,7 +47,8 @@
 
     protected final void set_String(String v)
     {
-        assert _schemaType.getContentType() != SchemaType.SIMPLE_CONTENT;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(_schemaType.getContentType() != SchemaType.SIMPLE_CONTENT);
 
         if (_schemaType.getContentType() != SchemaType.MIXED_CONTENT &&
                 !_schemaType.isNoType())
@@ -61,9 +62,10 @@
     
     public void set_text(String str)
     {
-        assert
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(
             _schemaType.getContentType() == SchemaType.MIXED_CONTENT ||
-                _schemaType.isNoType();
+                _schemaType.isNoType());
     }
 
     protected void update_from_complex_content()
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/values/XmlObjectBase.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/values/XmlObjectBase.java
index 938db95..f3fe1d2 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/values/XmlObjectBase.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/values/XmlObjectBase.java
@@ -494,9 +494,12 @@
     }
 
     {
-        assert TypeStore.NILLABLE   == 1;
-        assert TypeStore.HASDEFAULT == 2;
-        assert TypeStore.FIXED      == 4;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(TypeStore.NILLABLE   == 1);
+            XmlBeans.assertTrue(TypeStore.HASDEFAULT == 2);
+            XmlBeans.assertTrue(TypeStore.FIXED      == 4);
+        }
     }
 
     private static final int FLAG_NILLABLE        = TypeStore.NILLABLE;
@@ -710,7 +713,8 @@
      */
     public final void invalidate_value()
     {
-        assert((_flags & FLAG_STORE) != 0);
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue((_flags & FLAG_STORE) != 0);
         _flags |= FLAG_VALUE_DATED;
     }
 
@@ -728,7 +732,8 @@
      */
     public final void invalidate_nilvalue()
     {
-        assert((_flags & FLAG_STORE) != 0);
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue((_flags & FLAG_STORE) != 0);
         _flags |= FLAG_VALUE_DATED | FLAG_NIL_DATED;
     }
 
@@ -741,7 +746,8 @@
      */
     public final void invalidate_element_order()
     {
-        assert((_flags & FLAG_STORE) != 0);
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue((_flags & FLAG_STORE) != 0);
         _flags |= FLAG_VALUE_DATED | FLAG_NIL_DATED | FLAG_ELEMENT_DATED;
     }
 
@@ -751,7 +757,8 @@
      */
     public final TypeStore get_store()
     {
-        assert((_flags & FLAG_STORE) != 0);
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue((_flags & FLAG_STORE) != 0);
         return (TypeStore)_textsource;
     }
 
@@ -767,8 +774,11 @@
      */
     public final String build_text(NamespaceManager nsm)
     {
-        assert((_flags & FLAG_STORE) != 0);
-        assert((_flags & FLAG_VALUE_DATED) == 0);
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue((_flags & FLAG_STORE) != 0);
+            XmlBeans.assertTrue((_flags & FLAG_VALUE_DATED) == 0);
+        }
         if ((_flags & (FLAG_NIL | FLAG_ISDEFAULT)) != 0)
             return "";
         return compute_text(
@@ -781,8 +791,11 @@
      */
     public boolean build_nil()
     {
-        assert((_flags & FLAG_STORE) != 0);
-        assert((_flags & FLAG_VALUE_DATED) == 0);
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue((_flags & FLAG_STORE) != 0);
+            XmlBeans.assertTrue((_flags & FLAG_VALUE_DATED) == 0);
+        }
         return (_flags & FLAG_NIL) != 0;
     }
 
@@ -806,7 +819,8 @@
      */
     public void disconnect_store()
     {
-        assert((_flags & FLAG_STORE) != 0);
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue((_flags & FLAG_STORE) != 0);
         _flags |= FLAGS_DATED | FLAG_ORPHANED;
         // do NOT null out _textsource, because we need it non-null for synchronization
     }
@@ -876,7 +890,8 @@
      */
     public String get_default_element_text(QName eltName)
     {
-        assert(_isComplexContent());
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(_isComplexContent());
         if (!_isComplexContent())
             throw new IllegalStateException();
 
@@ -892,7 +907,8 @@
      */
     public String get_default_attribute_text(QName attrName)
     {
-        assert(_isComplexType());
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(_isComplexType());
         if (!_isComplexType())
             throw new IllegalStateException();
 
@@ -1161,7 +1177,8 @@
             if ((_flags & FLAG_ORPHANED) != 0)
                 throw new XmlValueDisconnectedException();
 
-            assert((_flags & FLAG_STORE) != 0);
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue((_flags & FLAG_STORE) != 0);
 
             check_element_dated();
 
@@ -1619,7 +1636,8 @@
         {
             XmlAnySimpleType v = (XmlAnySimpleType)obj;
             SchemaType instanceType = ((SimpleValue)v).instanceType();
-            assert(instanceType != null) : "Nil case should have been handled already";
+            if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(instanceType != null, "Nil case should have been handled already");
 
             // handle lists
             if (instanceType.getSimpleVariety() == SchemaType.LIST)
@@ -1636,11 +1654,13 @@
             // handle atomic types
             synchronized (monitor())
             {
-                assert(instanceType.getSimpleVariety() == SchemaType.ATOMIC);
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(instanceType.getSimpleVariety() == SchemaType.ATOMIC);
                 switch (instanceType.getPrimitiveType().getBuiltinTypeCode())
                 {
                     default:
-                        assert(false) : "encountered nonprimitive type.";
+                        if (XmlBeans.ASSERTS)
+                            XmlBeans.assertTrue(false, "encountered nonprimitive type.");
                     // case SchemaType.BTC_ANY_SIMPLE:  This is handled below...
                     // but we eventually want to handle it with a treecopy, so
                     // eventually we should break here.
@@ -1729,7 +1749,8 @@
                             }
                             default:
                             {
-                                assert(false) : "invalid numeric bit count";
+                                if (XmlBeans.ASSERTS)
+                                    XmlBeans.assertTrue(false, "invalid numeric bit count");
                                 // fallthrough
                             }
                             case SchemaType.SIZE_BIG_DECIMAL:
@@ -1898,7 +1919,7 @@
     protected void set_long(long v)
         { set_BigInteger(BigInteger.valueOf(v)); }
     protected void set_char(char v)
-        { set_String(Character.toString(v)); }
+        { set_String(new String(new char[] {v})); }
     protected void set_float(float v)
         { set_BigDecimal(new BigDecimal(v)); }
     protected void set_double(double v)
@@ -1938,7 +1959,9 @@
 
     private final boolean comparable_value_spaces(SchemaType t1, SchemaType t2)
     {
-        assert(t1.getSimpleVariety() != SchemaType.UNION && t2.getSimpleVariety() != SchemaType.UNION);
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(t1.getSimpleVariety() != SchemaType.UNION
+                    && t2.getSimpleVariety() != SchemaType.UNION);
 
         if (!t1.isSimpleType() && !t2.isSimpleType())
             return (t1.getContentType() == t2.getContentType());
@@ -2376,9 +2399,13 @@
                 XmlOptions opts = new XmlOptions().setDocumentType(XmlBeans.typeForClass(_xbeanClass));
                 _impl = XmlBeans.getContextTypeLoader().parse(xmlText, null, opts);
             }
-            catch (Exception e)
+            catch(XmlException xe)
             {
-                throw (IOException)(new IOException(e.getMessage()).initCause(e));
+                throw new XmlRuntimeException(xe);
+            }
+            catch(ClassNotFoundException cnfe)
+            {
+                throw new XmlRuntimeException(cnfe);
             }
         }
 
@@ -2538,7 +2565,8 @@
             return obj;
 
         SchemaType instanceType = ((SimpleValue)obj).instanceType();
-        assert(instanceType != null) : "Nil case should have been handled above";
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(instanceType != null, "Nil case should have been handled above");
 
         // handle lists
         if (instanceType.getSimpleVariety() == SchemaType.LIST)
@@ -2584,7 +2612,8 @@
                         return base.getBigIntegerValue();
 
                     default:
-                        assert(false) : "invalid numeric bit count";
+                        if (XmlBeans.ASSERTS)
+                            XmlBeans.assertTrue(false, "invalid numeric bit count");
                         // fallthrough
                     case SchemaType.SIZE_BIG_DECIMAL:
                         return base.getBigDecimalValue();
@@ -2607,7 +2636,8 @@
                 return base.getCalendarValue();
 
             default:
-                assert(false) : "encountered nonprimitive type.";
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(false, "encountered nonprimitive type.");
                 // fallthrough
 
             // NB: for string enums we just do java.lang.String
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/values/XmlUnionImpl.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/values/XmlUnionImpl.java
index 3264808..3d8c917 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/values/XmlUnionImpl.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/values/XmlUnionImpl.java
@@ -30,6 +30,8 @@
 import org.apache.xmlbeans.GDateSpecification;
 import org.apache.xmlbeans.GDurationSpecification;
 import org.apache.xmlbeans.SimpleValue;
+import org.apache.xmlbeans.XmlBeans;
+import org.apache.xmlbeans.XmlRuntimeException;
 
 import org.apache.xmlbeans.impl.schema.SchemaTypeImpl;
 import org.apache.xmlbeans.impl.common.ValidationContext;
@@ -93,7 +95,8 @@
 
         // iterate through the types, trying to create a type
         SchemaType[] members = _schemaType.getUnionConstituentTypes();
-        assert(members != null);
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(members != null);
 
         boolean pushed = false;
         // boolean wasstrict = set_strict(true); // tell types to complain ferverently about errors
@@ -127,8 +130,8 @@
                 }
                 catch (Exception e)
                 {
-                    throw new RuntimeException("Troublesome union exception caused by unexpected " + e, e);
-                    // assert(false) : "Unexpected " + e;
+                    throw new XmlRuntimeException("Troublesome union exception caused by unexpected " + e, e);
+                    // if (XmlBeans.ASSERTS) XmlBeans.assertTrue(false, "Unexpected " + e);
                     // continue;
                 }
             }
@@ -337,7 +340,8 @@
     private static boolean logical_overlap(SchemaType type, int javacode)
     {
         // non-union types because it's being applied on irreducible union members!
-        assert(type.getSimpleVariety() != SchemaType.UNION);
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(type.getSimpleVariety() != SchemaType.UNION);
 
         if (javacode <= SchemaType.BTC_LAST_BUILTIN)
         {
@@ -418,7 +422,8 @@
             }
         }
 
-        assert(false) : "missing case";
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(false, "missing case");
         return false;
     }
 
@@ -429,7 +434,8 @@
     private void set_primitive(int typecode, Object val)
     {
         SchemaType[] members = _schemaType.getUnionConstituentTypes();
-        assert(members != null);
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(members != null);
 
         boolean pushed = false;
         if (has_store())
@@ -458,7 +464,8 @@
                     }
                     catch (Exception e)
                     {
-                        assert(false) : "Unexpected " + e;
+                        if (XmlBeans.ASSERTS)
+                            XmlBeans.assertTrue(false, "Unexpected " + e);
                         continue outer;
                     }
 
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/impl/values/XmlValueDisconnectedException.java b/v1/src/typeimpl/org/apache/xmlbeans/impl/values/XmlValueDisconnectedException.java
index cfa4b3e..7324558 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/impl/values/XmlValueDisconnectedException.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/impl/values/XmlValueDisconnectedException.java
@@ -15,7 +15,9 @@
 
 package org.apache.xmlbeans.impl.values;
 
-public class XmlValueDisconnectedException extends RuntimeException
+import org.apache.xmlbeans.XmlRuntimeException;
+
+public class XmlValueDisconnectedException extends XmlRuntimeException
 {
     XmlValueDisconnectedException ( )
     {
diff --git a/v1/src/typeimpl/org/apache/xmlbeans/soap/SOAPArrayType.java b/v1/src/typeimpl/org/apache/xmlbeans/soap/SOAPArrayType.java
index 3f683d7..50e08e8 100644
--- a/v1/src/typeimpl/org/apache/xmlbeans/soap/SOAPArrayType.java
+++ b/v1/src/typeimpl/org/apache/xmlbeans/soap/SOAPArrayType.java
@@ -25,6 +25,7 @@
 import org.apache.xmlbeans.impl.common.XmlWhitespace;
 import org.apache.xmlbeans.impl.common.QNameHelper;
 import org.apache.xmlbeans.impl.common.PrefixResolver;
+import org.apache.xmlbeans.impl.common.StringUtils;
 
 public final class SOAPArrayType
 {
@@ -154,7 +155,7 @@
             _type = name;
             _ranks = EMPTY_INT_ARRAY;
             dimensions = XmlWhitespace.collapse(dimensions, XmlWhitespace.WS_COLLAPSE);
-            String[] dimStrings = dimensions.split(" ");
+            String[] dimStrings = StringUtils.split(dimensions, ' ');
             for (int i = 0; i < dimStrings.length; i++)
             {
                 String dimString = dimStrings[i];
@@ -346,7 +347,7 @@
     {
         int [] ranks = EMPTY_INT_ARRAY;
         arraySize = XmlWhitespace.collapse(arraySize, XmlWhitespace.WS_COLLAPSE);
-        String[] dimStrings = arraySize.split(" ");
+        String[] dimStrings = StringUtils.split(arraySize, ' ');
         int[] dimensions = new int[dimStrings.length];
         for (int i = 0; i < dimStrings.length; i++)
         {
diff --git a/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/BaseSchemaResourceManager.java b/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/BaseSchemaResourceManager.java
index bf71d89..e580d52 100644
--- a/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/BaseSchemaResourceManager.java
+++ b/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/BaseSchemaResourceManager.java
@@ -17,7 +17,9 @@
 
 import org.apache.xmlbeans.impl.util.HexBin;
 import org.apache.xmlbeans.impl.common.IOUtil;
+import org.apache.xmlbeans.impl.common.NetUtils;
 import org.apache.xmlbeans.XmlOptions;
+import org.apache.xmlbeans.XmlRuntimeException;
 import org.apache.xml.xmlbeans.x2004.x02.xmlbean.xsdownload.DownloadedSchemasDocument;
 import org.apache.xml.xmlbeans.x2004.x02.xmlbean.xsdownload.DownloadedSchemasDocument.DownloadedSchemas;
 import org.apache.xml.xmlbeans.x2004.x02.xmlbean.xsdownload.DownloadedSchemaEntry;
@@ -31,10 +33,9 @@
 import java.util.Iterator;
 import java.util.Map;
 import java.util.HashMap;
-import java.net.URI;
-import java.net.URISyntaxException;
 import java.net.URL;
 import java.net.URLConnection;
+import java.net.MalformedURLException;
 import java.security.DigestInputStream;
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
@@ -72,7 +73,7 @@
             }
             catch (Exception e)
             {
-                throw (IllegalStateException)(new IllegalStateException("Problem reading xsdownload.xml: please fix or delete this file")).initCause(e);
+                throw new XmlRuntimeException("Problem reading xsdownload.xml: please fix or delete this file", e);
             }
         }
         if (_importsDoc == null)
@@ -85,7 +86,7 @@
             }
             catch (Exception e)
             {
-                throw (IllegalStateException)(new IllegalStateException()).initCause(e);
+                throw new XmlRuntimeException(e);
             }
         }
 
@@ -361,7 +362,7 @@
         }
         catch (NoSuchAlgorithmException e)
         {
-            throw (IllegalStateException)(new IllegalStateException().initCause(e));
+            throw new XmlRuntimeException(e);
         }
 
         DigestInputStream str = new DigestInputStream(input, sha);
@@ -504,9 +505,9 @@
         return null;
     }
 
-    private String uniqueFilenameForURI(String schemaLocation) throws IOException, URISyntaxException
+    private String uniqueFilenameForURI(String schemaLocation) throws IOException, MalformedURLException
     {
-        String localFilename = new URI( schemaLocation ).getRawPath();
+        String localFilename = NetUtils.decodePath(new URL(schemaLocation).getPath());
         int i = localFilename.lastIndexOf('/');
         if (i >= 0)
             localFilename = localFilename.substring(i + 1);
@@ -554,8 +555,8 @@
         {
             URL url = new URL( schemaLocation );
             URLConnection conn = url.openConnection();
-            conn.addRequestProperty("User-Agent", "Apache XMLBeans/1.0.3");
-            conn.addRequestProperty("Accept", "application/xml, text/xml, */*");
+            conn.setRequestProperty("User-Agent", "Apache XMLBeans/1.0.3");
+            conn.setRequestProperty("Accept", "application/xml, text/xml, */*");
             DigestInputStream input = digestInputStream(conn.getInputStream());
             IOUtil.copyCompletely(input, buffer);
             digest = HexBin.bytesToString(input.getMessageDigest().digest());
@@ -596,7 +597,7 @@
         {
             targetFilename = uniqueFilenameForURI(schemaLocation);
         }
-        catch (URISyntaxException e)
+        catch (MalformedURLException e)
         {
             warning("Invalid URI '" + schemaLocation + "':" + e.getMessage());
             return null;
diff --git a/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/CodeGenUtil.java b/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/CodeGenUtil.java
index 72fda88..eb67c4d 100644
--- a/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/CodeGenUtil.java
+++ b/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/CodeGenUtil.java
@@ -15,6 +15,9 @@
 
 package org.apache.xmlbeans.impl.tool;
 
+import org.apache.xmlbeans.XmlBeans;
+import org.apache.xmlbeans.impl.common.StringUtils;
+
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Iterator;
@@ -25,9 +28,9 @@
 import java.io.InputStreamReader;
 import java.io.FileFilter;
 import java.io.FileWriter;
+import java.net.URL;
+import java.net.MalformedURLException;
 import java.io.IOException;
-import java.net.URI;
-import java.net.URISyntaxException;
 
 public class CodeGenUtil
 {
@@ -36,26 +39,16 @@
     public static String DEFAULT_COMPILER = "javac";
     public static String DEFAULT_JAR = "jar";
 
-    //workaround for Sun bug # 4723726
-    public static URI resolve(URI base, URI child)
+    public static URL resolve(URL base, String child)
     {
-        URI ruri = base.resolve(child);
-        
-        //fix up normalization bug
-        if ("file".equals(ruri.getScheme()) && ! child.equals(ruri))
+        try
         {
-            if (base.getPath().startsWith("//") && !ruri.getPath().startsWith("//"))
-            {
-                String path = "///".concat(ruri.getPath());
-                try
-                {
-                    ruri = new URI("file", null, path, ruri.getQuery(), ruri.getFragment());
-                }
-                catch(URISyntaxException uris)
-                {}
-            }
+            return new URL(base, child);
         }
-        return ruri;
+        catch (MalformedURLException e)
+        {
+            return null;
+        }
     }
     
     static void addAllJavaFiles(List srcFiles, List args)
@@ -89,7 +82,7 @@
 
         // bizarre.  javac expects backslash escaping if we quote the classpath
         // bizarre also.  replaceAll expects replacement backslashes to be double escaped.
-        return "\"" + filename.replaceAll("\\\\", "\\\\\\\\") + "\"";
+        return "\"" + StringUtils.replaceAll(filename, "\\\\", "\\\\\\\\") + "\"";
     }
 
     static private String quoteNoEscapeFilename(String filename)
@@ -125,7 +118,8 @@
         List args = new ArrayList();
 
         File javac = findJavaTool(javacPath == null ? DEFAULT_COMPILER : javacPath);
-        assert (javac.exists()) : "compiler not found " + javac;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(javac.exists(), "compiler not found " + javac);
         args.add(javac.getAbsolutePath());
 
         if (outdir == null)
@@ -164,9 +158,6 @@
             args.add(quoteAndEscapeFilename(classPath.toString()));
         }
 
-        args.add("-source");
-        args.add("1.4");
-
         args.add(debug ? "-g" : "-g:none");
 
         if (verbose)
@@ -246,7 +237,6 @@
                 System.err.println("'javac' is required on the path.");
 
             System.err.println(e.toString());
-            System.err.println(e.getCause());
             e.printStackTrace(System.err);
             return false;
         }
@@ -260,7 +250,7 @@
     public static File[] systemClasspath()
     {
         List cp = new ArrayList();
-        String[] systemcp = System.getProperty("java.class.path").split(File.pathSeparator);
+        String[] systemcp = StringUtils.split(System.getProperty("java.class.path"), File.pathSeparatorChar);
         for (int i = 0; i < systemcp.length; i++)
         {
             cp.add(new File(systemcp[i]));
@@ -278,7 +268,8 @@
         List args = new ArrayList();
 
         File jar = findJavaTool(jarPath == null ? DEFAULT_JAR : jarPath);
-        assert (jar.exists()) : "jar not found " + jar;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(jar.exists(), "jar not found " + jar);
         args.add(jar.getAbsolutePath());
 
         args.add("cf" + (verbose ? "v" : ""));
diff --git a/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/CommandLine.java b/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/CommandLine.java
index 105c572..2633073 100644
--- a/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/CommandLine.java
+++ b/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/CommandLine.java
@@ -16,23 +16,23 @@
 package org.apache.xmlbeans.impl.tool;
 
 import org.apache.xmlbeans.impl.common.IOUtil;
+import org.apache.xmlbeans.impl.common.NetUtils;
+import org.apache.xmlbeans.impl.common.SequencedHashMap;
 
 import java.util.Map;
-import java.util.LinkedHashMap;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Collections;
 import java.util.Iterator;
 import java.util.Collection;
 import java.io.File;
-import java.io.FileFilter;
-import java.net.URI;
+import java.net.URL;
 
 public class CommandLine
 {
     public CommandLine(String[] args, Collection scheme)
     {
-        _options = new LinkedHashMap();
+        _options = new SequencedHashMap();
         ArrayList endargs = new ArrayList();
 
         for (int i = 0; i < args.length; i++)
@@ -125,10 +125,11 @@
                 }
                 else
                 {
-                    URI currUri = files[i].toURI();
+                    URL currUri = IOUtil.fileToURL(files[i]);
                     
                     // Give up on the basedir. There may be none
-                    if (_baseDir != null && _baseDir.toURI().relativize(currUri).equals(currUri))
+                    if (_baseDir != null && currUri.equals(
+                        NetUtils.relativize(IOUtil.fileToURL(_baseDir).getPath(), currUri.getPath())))
                     {
                         _baseDir = null;
                         noBaseDir = true;
diff --git a/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/FactorImports.java b/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/FactorImports.java
index 0409052..aceb3a3 100644
--- a/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/FactorImports.java
+++ b/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/FactorImports.java
@@ -33,11 +33,12 @@
 import java.util.HashMap;
 import java.io.File;
 import java.io.IOException;
-import java.net.URI;
-import java.net.URISyntaxException;
+import java.net.URL;
 
 import org.apache.xmlbeans.XmlException;
 import org.apache.xmlbeans.XmlOptions;
+import org.apache.xmlbeans.impl.common.NetUtils;
+import org.apache.xmlbeans.impl.common.IOUtil;
 
 import javax.xml.namespace.QName;
 
@@ -312,21 +313,23 @@
     
     private static File outputFileFor(File file, File baseDir, File outdir)
     {
-        URI base = baseDir.getAbsoluteFile().toURI();
-        URI abs = file.getAbsoluteFile().toURI();
-        URI rel = base.relativize(abs);
-        if (rel.isAbsolute())
+        baseDir = baseDir.getAbsoluteFile();
+        file = file.getAbsoluteFile();
+
+        String base = IOUtil.fileToURL(baseDir).getPath();
+        String abs = IOUtil.fileToURL(file).getPath();
+
+        String rel = NetUtils.relativize(base, abs);
+        if (rel.equals(abs))
         {
             System.out.println("Cannot relativize " + file);
             return null;
         }
-        
-        URI outbase = outdir.toURI();
-        URI out = CodeGenUtil.resolve(outbase, rel);
-        return new File(out);
+
+        return new File(outdir, rel);
     }
     
-    private static URI commonAncestor(URI first, URI second)
+    private static String commonAncestor(URL first, URL second)
     {
         String firstStr = first.toString();
         String secondStr = second.toString();
@@ -344,41 +347,37 @@
             i = firstStr.lastIndexOf('/', i);
         if (i < 0)
             return null;
-        try
-        {
-            return new URI(firstStr.substring(0, i));
-        }
-        catch (URISyntaxException e)
-        {
-            return null;
-        }
+
+        return firstStr.substring(0, i);
     }
     
     
     private static String relativeURIFor(File source, File target)
     {
-        URI base = source.getAbsoluteFile().toURI();
-        URI abs = target.getAbsoluteFile().toURI();
+        URL base = IOUtil.fileToURL(source.getAbsoluteFile());
+        URL abs = IOUtil.fileToURL(target.getAbsoluteFile());
         // find common substring...
-        URI commonBase = commonAncestor(base, abs);
+        String commonBase = commonAncestor(base, abs);
         if (commonBase == null)
             return abs.toString();
-        
-        URI baserel = commonBase.relativize(base);
-        URI targetrel = commonBase.relativize(abs);
-        if (baserel.isAbsolute() || targetrel.isAbsolute())
+
+        String baserel = NetUtils.relativize(commonBase, base.getPath());
+        String targetrel = NetUtils.relativize(commonBase, abs.getPath());
+
+        if (baserel.charAt(0) == '/' || targetrel.charAt(0) == '/')
             return abs.toString();
-        String prefix = "";
+
+        StringBuffer prefix = new StringBuffer();
         String sourceRel = baserel.toString();
         for (int i = 0; i < sourceRel.length();)
         {
             i = sourceRel.indexOf('/', i);
             if (i < 0)
                 break;
-            prefix += "../";
+            prefix.append("../");
             i += 1;
         }
-        return prefix + targetrel.toString();
+        return prefix.append(targetrel).toString();
     }
     
     private static File commonFileFor(String commonName, String namespace, int i, File outdir)
diff --git a/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaCodeGenerator.java b/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaCodeGenerator.java
index d26374a..d8be4fc 100644
--- a/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaCodeGenerator.java
+++ b/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaCodeGenerator.java
@@ -17,6 +17,8 @@
 
 import org.apache.xmlbeans.SchemaTypeSystem;
 import org.apache.xmlbeans.SchemaType;
+import org.apache.xmlbeans.XmlBeans;
+import org.apache.xmlbeans.XmlRuntimeException;
 import org.apache.xmlbeans.impl.common.XmlErrorWatcher;
 
 import java.io.*;
@@ -217,7 +219,7 @@
             }
             catch (Exception e)
             {
-                IllegalStateException e2 =  new IllegalStateException("Cannot load JaxbCodeGenerator: verify that xbean.jar is on the classpath");
+                XmlRuntimeException e2 =  new XmlRuntimeException("Cannot load JaxbCodeGenerator: verify that xbean.jar is on the classpath");
                 e2.initCause(e);
                 throw e2;
             }
@@ -232,13 +234,13 @@
         }
         catch (InvocationTargetException e)
         {
-            IllegalStateException e2 = new IllegalStateException(e.getMessage());
+            XmlRuntimeException e2 = new XmlRuntimeException(e.getMessage());
             e2.initCause(e);
             throw e2;
         }
         catch (IllegalAccessException e)
         {
-            IllegalStateException e2 = new IllegalStateException(e.getMessage());
+            XmlRuntimeException e2 = new XmlRuntimeException(e.getMessage());
             e2.initCause(e);
             throw e2;
         }
@@ -248,7 +250,8 @@
     {
         File newdir = (subdir == null) ? rootdir : new File(rootdir, subdir);
         boolean created = (newdir.exists() && newdir.isDirectory()) || newdir.mkdirs();
-        assert(created) : "Could not create " + newdir.getAbsolutePath();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(created, "Could not create " + newdir.getAbsolutePath());
         return newdir;
     }
 
@@ -270,7 +273,8 @@
             if (!tmpSrcDir.exists())
             {
                 boolean created = tmpSrcDir.mkdirs();
-                assert created : "Could not create " + tmpSrcDir.getAbsolutePath();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(created, "Could not create " + tmpSrcDir.getAbsolutePath());
                 break;
             }
         }
diff --git a/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaCompiler.java b/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaCompiler.java
index 33dc100..05c3245 100644
--- a/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaCompiler.java
+++ b/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaCompiler.java
@@ -23,6 +23,8 @@
 import org.apache.xmlbeans.impl.common.XmlErrorPrinter;
 import org.apache.xmlbeans.impl.common.XmlErrorWatcher;
 import org.apache.xmlbeans.impl.common.XmlErrorContext;
+import org.apache.xmlbeans.impl.common.IOUtil;
+import org.apache.xmlbeans.impl.common.StringUtils;
 import org.apache.xmlbeans.impl.values.XmlListImpl;
 import org.apache.xmlbeans.SchemaTypeSystem;
 import org.apache.xmlbeans.SchemaTypeLoader;
@@ -35,7 +37,7 @@
 
 import java.io.File;
 import java.util.*;
-import java.net.URI;
+import java.net.URL;
 
 import org.w3.x2001.xmlSchema.SchemaDocument;
 
@@ -201,7 +203,7 @@
         String cpString = cl.getOpt("cp");
         if (cpString != null)
         {
-            String[] cpparts = cpString.split(File.pathSeparator);
+            String[] cpparts = StringUtils.split(cpString, File.pathSeparatorChar);
             List cpList = new ArrayList();
             for (int i = 0; i < cpparts.length; i++)
                 cpList.add(new File(cpparts[i]));
@@ -229,9 +231,9 @@
             System.exit(1);
         }
         File baseDir = cl.getBaseDir();
-        URI baseURI = baseDir == null ? null : baseDir.toURI();
+        URL baseURL = baseDir == null ? null : IOUtil.fileToURL(baseDir);
 
-        XmlErrorPrinter err = new XmlErrorPrinter(verbose, baseURI);
+        XmlErrorPrinter err = new XmlErrorPrinter(verbose, baseURL);
 
         Parameters params = new Parameters();
         params.setBaseDir(baseDir);
@@ -703,9 +705,9 @@
 
         SchemaTypeLoader linkTo = SchemaTypeLoaderImpl.build(null, cpResourceLoader, null);
 
-        URI baseURI = null;
+        URL baseURL = null;
         if (baseDir != null)
-            baseURI = baseDir.toURI();
+            baseURL = IOUtil.fileToURL(baseDir);
 
         XmlOptions opts = new XmlOptions();
         if (download)
@@ -727,7 +729,7 @@
         params.setOptions(opts);
         params.setErrorListener(errorListener);
         params.setJavaize(true);
-        params.setBaseURI(baseURI);
+        params.setBaseURI(baseURL == null ? null : baseURL.toString());
         params.setSourcesToCopyMap(sourcesToCopyMap);
         return SchemaTypeSystemCompiler.compile(params);
     }
diff --git a/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaCopy.java b/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaCopy.java
index d78cbce..8f2a95f 100644
--- a/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaCopy.java
+++ b/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/SchemaCopy.java
@@ -21,12 +21,11 @@
 import org.apache.xmlbeans.impl.common.IOUtil;
 import org.apache.internal.xmlbeans.wsdlsubst.DefinitionsDocument;
 import org.apache.internal.xmlbeans.wsdlsubst.TImport;
+import org.apache.xmlbeans.impl.common.SequencedHashMap;
 
-import java.net.URI;
 import java.net.URL;
-import java.net.URISyntaxException;
+import java.net.MalformedURLException;
 import java.util.Map;
-import java.util.LinkedHashMap;
 import java.util.LinkedList;
 import java.util.Collections;
 import java.util.Iterator;
@@ -47,13 +46,12 @@
             return;
         }
 
-        URI source = null;
-        URI target = null;
+        URL source = null;
+        URL target = null;
 
         try
         {
-            source = new URI(args[0]);
-            source.toURL(); // to trigger exception
+            source = new URL(args[0]);
         }
         catch (Exception e)
         {
@@ -65,10 +63,10 @@
         {
             try
             {
-                URI dir = new File(".").getCanonicalFile().toURI();
+                URL dir = new File(".").getCanonicalFile().toURL();
                 String lastPart = source.getPath();
                 lastPart = lastPart.substring(lastPart.lastIndexOf('/') + 1);
-                target = CodeGenUtil.resolve(dir, URI.create(lastPart));
+                target = CodeGenUtil.resolve(dir, lastPart);
             }
             catch (Exception e)
             {
@@ -80,10 +78,8 @@
         {
             try
             {
-                target = new URI(args[1]);
-                if (!target.isAbsolute())
-                    target = null;
-                else if (!target.getScheme().equals("file"))
+                target = new URL(args[1]);
+                if (!target.getProtocol().equals("file"))
                     target = null;
             }
             catch (Exception e)
@@ -95,7 +91,7 @@
             {
                 try
                 {
-                    target = new File(target).getCanonicalFile().toURI();
+                    target = new File(args[1]).getCanonicalFile().toURL();
                 }
                 catch (Exception e)
                 {
@@ -113,8 +109,8 @@
     {
         for (Iterator i = uriMap.keySet().iterator(); i.hasNext(); )
         {
-            URI source = (URI)i.next();
-            URI target = (URI)uriMap.get(source);
+            URL source = (URL)i.next();
+            URL target = (URL)uriMap.get(source);
             try
             {
                 IOUtil.copyCompletely(source, target);
@@ -126,25 +122,25 @@
                 continue;
             }
             if (stdout)
-            System.out.println("Copied " + source + " -> " + target);
+                System.out.println("Copied " + source + " -> " + target);
         }
     }
 
 
     /**
-     * Copies the schema or wsdl at the source URI to the target URI, along
-     * with any relative references.  The target URI should be a file URI.
+     * Copies the schema or wsdl at the source URL to the target URL, along
+     * with any relative references.  The target URL should be a file URL.
      * If doCopy is false, the file copies are not actually done; the map
      * returned just describes the copies that would have been done.
      *
-     * @param source an arbitrary URI describing a source Schema or WSDL
-     * @param target a file URI describing a target filename
-     * @return a map of all the source/target URIs needed to copy
+     * @param source an arbitrary URL describing a source Schema or WSDL
+     * @param target a file URL describing a target filename
+     * @return a map of all the source/target URLs needed to copy
      * the file along with all its relative referents.
      */
-    public static Map findAllRelative(URI source, URI target)
+    public static Map findAllRelative(URL source, URL target)
     {
-        Map result = new LinkedHashMap();
+        Map result = new SequencedHashMap();
         result.put(source, target);
 
         LinkedList process = new LinkedList();
@@ -152,12 +148,12 @@
 
         while (!process.isEmpty())
         {
-            URI nextSource = (URI)process.removeFirst();
-            URI nextTarget = (URI)result.get(nextSource);
+            URL nextSource = (URL)process.removeFirst();
+            URL nextTarget = (URL)result.get(nextSource);
             Map nextResults = findRelativeInOne(nextSource, nextTarget);
             for (Iterator i = nextResults.keySet().iterator(); i.hasNext(); )
             {
-                URI newSource = (URI)i.next();
+                URL newSource = (URL)i.next();
                 if (result.containsKey(newSource))
                     continue;
                 result.put(newSource, nextResults.get(newSource));
@@ -173,16 +169,15 @@
                     "http://schemas.xmlsoap.org/wsdl/", "http://www.apache.org/internal/xmlbeans/wsdlsubst" 
             ));
 
-    private static Map findRelativeInOne(URI source, URI target)
+    private static Map findRelativeInOne(URL source, URL target)
     {
         try
         {
-            URL sourceURL = source.toURL();
-            XmlObject xobj = XmlObject.Factory.parse(sourceURL, loadOptions);
+            XmlObject xobj = XmlObject.Factory.parse(source, loadOptions);
             XmlCursor xcur = xobj.newCursor();
             xcur.toFirstChild();
 
-            Map result = new LinkedHashMap();
+            Map result = new SequencedHashMap();
 
             if (xobj instanceof SchemaDocument)
                 putMappingsFromSchema(result, source, target, ((SchemaDocument)xobj).getSchema());
@@ -197,26 +192,33 @@
         return Collections.EMPTY_MAP;
     }
 
-    private static void putNewMapping(Map result, URI origSource, URI origTarget, String literalURI)
+    private static void putNewMapping(Map result, URL origSource, URL origTarget, String literalURL)
     {
+        if (literalURL == null)
+            return;
+
+        URL url = null;
         try
         {
-            if (literalURI == null)
-                return;
-            URI newRelative = new URI(literalURI);
-            if (newRelative.isAbsolute())
-                return;
-            URI newSource = CodeGenUtil.resolve(origSource, newRelative);
-            URI newTarget = CodeGenUtil.resolve(origTarget, newRelative);
-            result.put(newSource, newTarget);
+            url = new URL(literalURL);
         }
-        catch (URISyntaxException e)
+        catch(MalformedURLException mue)
         {
-            // uri syntax problem? do nothing silently.
+            url = null;
         }
+
+        //if the string can be parsed into a URL, it's absolute
+        if (url != null)
+            return;
+
+        URL newSource = CodeGenUtil.resolve(origSource, literalURL);
+        URL newTarget = CodeGenUtil.resolve(origTarget, literalURL);
+
+        if (newSource != null && newTarget != null)
+            result.put(newSource, newTarget);
     }
 
-    private static void putMappingsFromSchema(Map result, URI source, URI target, SchemaDocument.Schema schema)
+    private static void putMappingsFromSchema(Map result, URL source, URL target, SchemaDocument.Schema schema)
     {
         ImportDocument.Import[] imports = schema.getImportArray();
         for (int i = 0; i < imports.length; i++)
@@ -227,7 +229,7 @@
             putNewMapping(result, source, target, includes[i].getSchemaLocation());
     }
 
-    private static void putMappingsFromWsdl(Map result, URI source, URI target, DefinitionsDocument.Definitions wdoc)
+    private static void putMappingsFromWsdl(Map result, URL source, URL target, DefinitionsDocument.Definitions wdoc)
     {
         XmlObject[] types = wdoc.getTypesArray();
         for (int i = 0; i < types.length; i++)
diff --git a/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/XMLBean.java b/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/XMLBean.java
index 90a5e07..814d7b1 100644
--- a/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/XMLBean.java
+++ b/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/XMLBean.java
@@ -29,7 +29,8 @@
 import java.io.StringWriter;
 import java.io.PrintWriter;
 import java.util.*;
-import java.net.URI;
+import java.net.URL;
+import java.net.MalformedURLException;
 
 import org.apache.xmlbeans.XmlError;
 
@@ -669,14 +670,14 @@
         this.memoryMaximumSize = memoryMaximumSize;
     }
 
-    private static URI uriFromFile(File f)
+    private URL urlFromFile(File f)
     {
         if (f == null)
             return null;
 
         try
         {
-            return f.getCanonicalFile().toURI();
+            return f.getCanonicalFile().toURL();
         }
         catch(java.io.IOException e)
         {
@@ -684,19 +685,27 @@
             // if the filename is "aux", "lpt1", etc. It's the caller's responsibility
             // to deal with those cases correctly, usually by calling FileSvc.invalidPathCheck()
             // MessageSvc.get().logException(e);
-            return f.getAbsoluteFile().toURI();
+            try
+            {
+                return f.getAbsoluteFile().toURL();
+            }
+            catch (MalformedURLException mue)
+            {
+                log(mue.toString(), Project.MSG_ERR);
+                return null;
+            }
         }
     }
 
     public class ErrorLogger extends AbstractCollection
     {
         private boolean _noisy;
-        private URI _baseURI;
+        private URL _baseURL;
 
         public ErrorLogger(boolean noisy)
         {
             _noisy = noisy;
-            _baseURI = uriFromFile(project.getBaseDir());
+            _baseURL = urlFromFile(project.getBaseDir());
         }
 
         public boolean add(Object o)
@@ -705,11 +714,11 @@
             {
                 XmlError err = (XmlError)o;
                 if (err.getSeverity() == XmlError.SEVERITY_ERROR)
-                    log(err.toString(_baseURI), Project.MSG_ERR);
+                    log(err.toString(_baseURL), Project.MSG_ERR);
                 else if (err.getSeverity() == XmlError.SEVERITY_WARNING)
-                    log(err.toString(_baseURI), Project.MSG_WARN);
+                    log(err.toString(_baseURL), Project.MSG_WARN);
                 else if (_noisy)
-                    log(err.toString(_baseURI), Project.MSG_INFO);
+                    log(err.toString(_baseURL), Project.MSG_INFO);
             }
             return false;
         }
diff --git a/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/XSTCTester.java b/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/XSTCTester.java
index 79dce9b..67802fa 100644
--- a/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/XSTCTester.java
+++ b/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/XSTCTester.java
@@ -19,6 +19,10 @@
 import org.apache.xmlbeans.XmlException;
 import org.apache.xmlbeans.XmlError;
 import org.apache.xmlbeans.XmlCalendar;
+import org.apache.xmlbeans.impl.regex.RegularExpression;
+import org.apache.xmlbeans.impl.regex.Match;
+import org.apache.xmlbeans.impl.common.StringUtils;
+import org.apache.xmlbeans.impl.common.IOUtil;
 import org.apache.xml.xmlbeans.x2004.x02.xmlbean.ltgfmt.TestsDocument;
 import org.apache.xml.xmlbeans.x2004.x02.xmlbean.ltgfmt.FileDesc;
 
@@ -31,27 +35,26 @@
 import java.util.Collections;
 import java.util.Iterator;
 import java.util.Date;
-import java.util.regex.Pattern;
-import java.net.URI;
+import java.net.URL;
 
 public class XSTCTester
 {
     public static void main(String[] args) throws IOException
     {
         long start = System.currentTimeMillis();
-        
+
         CommandLine cl = new CommandLine(args, Collections.EMPTY_SET);
         boolean showpass = (cl.getOpt("showpass") != null);
         File[] allFiles = cl.getFiles();
         Collection ltgFiles = new ArrayList();
         Harness harness = new XMLBeanXSTCHarness();
-        
+
         for (int i = 0; i < allFiles.length; i++)
         {
             if (allFiles[i].getName().indexOf("LTG") >= 0)
                 ltgFiles.add(allFiles[i]);
         }
-        
+
         File resultsFile = new File("out.html");
         PrintWriter writer = new PrintWriter(new FileWriter(resultsFile));
         writer.println("<html>");
@@ -124,17 +127,17 @@
         writer.println("<tr><td colspan=3>Summary: " + failures + " failures out of " + cases + " cases run.</td></tr>");
         writer.println("</table>");
         writer.close();
-        
+
         long finish = System.currentTimeMillis();
         System.out.println("Time run tests: " + ((double)(finish - start) / 1000.0) + " seconds" );
-        
+
         // Launch results
         if (System.getProperty("os.name").toLowerCase().indexOf("windows") >= 0)
             Runtime.getRuntime().exec("cmd /c start iexplore \"" + resultsFile.getAbsolutePath() + "\"");
         else
             System.out.println("Results output to " + resultsFile);
     }
-    
+
     public static class TestCase
     {
         private File ltgFile;
@@ -198,7 +201,7 @@
             return rvExpected;
         }
     }
-    
+
     public static class TestCaseResult
     {
         private TestCase testCase;
@@ -252,38 +255,38 @@
         {
             this.ivMessages.addAll(ivMessages);
         }
-        
+
         public void setCrash(boolean crash)
         {
             this.crash = crash;
         }
-        
+
         public boolean isCrash()
         {
             return crash;
         }
-        
+
         public boolean succeeded()
         {
             return !crash && (isIvActual() == testCase.isIvExpected()) && (isSvActual() == testCase.isSvExpected());
         }
     }
-    
+
     public static interface Harness
     {
         public void runTestCase(TestCaseResult result);
     }
-    
+
     public static String makeHTMLLink(File file, boolean value)
     {
         if (file == null)
             return "&nbsp;";
-        URI uri = file.getAbsoluteFile().toURI();
-        return "<a href=\"" + uri + "\" target=_blank>" + Boolean.toString(value) + "</a>";
+        URL uri = IOUtil.fileToURL(file);
+        return "<a href=\"" + uri + "\" target=_blank>" + value + "</a>";
     }
-    
-    private static final Pattern leadingSpace = Pattern.compile("^\\s+", Pattern.MULTILINE);
-    
+
+    private static final RegularExpression leadingSpace = new RegularExpression("^\\s+", "m");
+
     public static String makeHTMLDescription(TestCase testCase)
     {
         StringBuffer sb = new StringBuffer();
@@ -291,25 +294,38 @@
         if (testCase.getSchemaFile() == null)
             sb.append("about:No schema");
         else
-            sb.append(testCase.getSchemaFile().getAbsolutePath().replaceAll("\\\\", "\\\\\\\\"));
+            sb.append(StringUtils.replaceAll(testCase.getSchemaFile().getAbsolutePath(),
+                "\\\\", "\\\\\\\\"));
 
         sb.append("\", \"");
         if (testCase.getInstanceFile() == null)
             sb.append("about:No instance");
         else
-            sb.append(testCase.getInstanceFile().getAbsolutePath().replaceAll("\\\\", "\\\\\\\\"));
+            sb.append(StringUtils.replaceAll(testCase.getInstanceFile().getAbsolutePath(),
+                "\\\\", "\\\\\\\\"));
         sb.append("\")'><xmp>");
-        sb.append(leadingSpace.matcher(testCase.getDescription()).replaceAll("") + "(" + testCase.getId() + ")");
+
+        Match m = new Match();
+        String desc = testCase.getDescription();
+        if (leadingSpace.matches(desc, m))
+        {
+            StringBuffer sbDesc = new StringBuffer(desc);
+            StringUtils.replaceAll(m, sbDesc, "");
+            desc = new String(sbDesc);
+        }
+
+        sb.append(desc);
+        sb.append( "(").append(testCase.getId()).append(")");
         sb.append("</xmp></a>");
         return sb.toString();
     }
-    
+
     public static void summarizeResultAsHTMLTableRows(TestCaseResult result, PrintWriter out)
     {
         TestCase testCase = result.getTestCase();
         boolean sRight = testCase.getSchemaFile() == null || testCase.isSvExpected() == result.isSvActual();
         boolean iRight = testCase.getInstanceFile() == null || testCase.isIvExpected() == result.isIvActual();
-        
+
         out.println(result.isCrash() ? "<tr bgcolor=black color=white>" : "<tr>");
         out.println("<td valign=top>" + makeHTMLDescription(testCase) + "</td>");
         String sLinks;
@@ -317,7 +333,7 @@
             sLinks = makeHTMLLink(testCase.getSchemaFile(), result.isSvActual());
         else
             sLinks = makeHTMLLink(testCase.getSchemaFile(), result.isSvActual()) + "<br>" + makeHTMLLink(testCase.getResourceFile(), result.isSvActual());
-        
+
         out.println((sRight ? "<td valign=top>" : result.isSvActual() ? "<td bgcolor=orange valign=top>" : "<td bgcolor=red valign=top>") + sLinks + "</td>");
         out.println((iRight ? "<td valign=top>" : result.isIvActual() ? "<td bgcolor=orange valign=top>" : "<td bgcolor=red valign=top>") + makeHTMLLink(testCase.getInstanceFile(), result.isIvActual()) + "</td>");
         out.println("</tr>");
@@ -334,7 +350,7 @@
             out.println("</xmp></tr></td>");
         }
     }
-    
+
     public static TestCase[] parseLTGFile(File ltgFile, Collection outerErrors)
     {
         Collection errors = new ArrayList();
@@ -347,9 +363,9 @@
             TestsDocument doc = TestsDocument.Factory.parse(ltgFile, ltgOptions);
             if (!doc.validate(ltgOptions))
                 throw new Exception("Document " + ltgFile + " not valid.");
-            
+
             org.apache.xml.xmlbeans.x2004.x02.xmlbean.ltgfmt.TestCase[] testCases = doc.getTests().getTestArray();
-            
+
             Collection result = new ArrayList();
             for (int i = 0; i < testCases.length; i++)
             {
@@ -370,7 +386,7 @@
                         outerErrors.add(XmlError.forObject("Can't read file " + theFile, filedescs[j]).toString());
                         continue;
                     }
-                    
+
                     switch (filedescs[j].getRole().intValue())
                     {
                         case FileDesc.Role.INT_INSTANCE:
@@ -379,21 +395,21 @@
                             newCase.instanceFile = theFile;
                             newCase.ivExpected = filedescs[j].getValidity();
                             break;
-                            
+
                         case FileDesc.Role.INT_SCHEMA:
                             if (newCase.schemaFile != null)
                                 outerErrors.add(XmlError.forObject("More than one schema file speicifed - ignoring all but last", filedescs[j]).toString());
                             newCase.schemaFile = theFile;
                             newCase.svExpected = filedescs[j].getValidity();
                             break;
-                            
+
                         case FileDesc.Role.INT_RESOURCE:
                             if (newCase.resourceFile != null)
                                 outerErrors.add(XmlError.forObject("More than one resource file speicifed - ignoring all but last", filedescs[j]).toString());
                             newCase.resourceFile = theFile;
                             newCase.rvExpected = filedescs[j].getValidity();
                             break;
-                        
+
                         default:
                             throw new XmlException(XmlError.forObject("Unexpected file role", filedescs[j]));
                     }
@@ -411,5 +427,5 @@
             return null;
         }
     }
-    
+
 }
diff --git a/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/XsbDumper.java b/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/XsbDumper.java
index 0c8d5ca..7f2d5f5 100644
--- a/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/XsbDumper.java
+++ b/v1/src/xmlcomp/org/apache/xmlbeans/impl/tool/XsbDumper.java
@@ -33,6 +33,8 @@
 import org.apache.xmlbeans.XmlException;
 import org.apache.xmlbeans.XmlObject;
 import org.apache.xmlbeans.XmlOptions;
+import org.apache.xmlbeans.XmlBeans;
+import org.apache.xmlbeans.XmlRuntimeException;
 import javax.xml.namespace.QName;
 
 public class XsbDumper
@@ -123,7 +125,7 @@
     void flush() { System.out.flush(); }
     void emit(String str) { System.out.println(_indent + str); flush(); }
     void emit() { System.out.println(); flush(); }
-    void error(Exception e) { System.out.println(e.toString()); flush(); IllegalStateException e2 = new IllegalStateException( e.getMessage() ); e2.initCause( e ); throw e2; }
+    void error(Exception e) { System.out.println(e.toString()); flush(); XmlRuntimeException e2 = new XmlRuntimeException( e.getMessage(), e ); throw e2; }
     void error(String str) { System.out.println(str); flush(); IllegalStateException e2 = new IllegalStateException( str ); throw e2; }
     private String _indent;
     void indent() { _indent += "  "; }
@@ -1066,7 +1068,8 @@
         switch (btc)
         {
             default:
-                assert(false);
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(false);
             case 0:
                 value = "nil";
                 break;
@@ -1093,7 +1096,7 @@
                 {
                     value = new String(HexBin.encode(readByteArray()));
                     if (value.length() > 19)
-                        value = value.subSequence(0, 16) + "...";
+                        value = value.substring(0, 16) + "...";
                     break;
                 }
 
diff --git a/v1/src/xmlconfig/org/apache/xmlbeans/impl/config/InterfaceExtension.java b/v1/src/xmlconfig/org/apache/xmlbeans/impl/config/InterfaceExtension.java
index 2cf788c..894b0d8 100644
--- a/v1/src/xmlconfig/org/apache/xmlbeans/impl/config/InterfaceExtension.java
+++ b/v1/src/xmlconfig/org/apache/xmlbeans/impl/config/InterfaceExtension.java
@@ -20,6 +20,7 @@
 
 import org.apache.xml.xmlbeans.x2004.x02.xbean.config.Extensionconfig;
 import org.apache.xmlbeans.XmlObject;
+import org.apache.xmlbeans.XmlBeans;
 
 import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
@@ -100,7 +101,8 @@
 
     private boolean validateMethods(XmlObject loc)
     {
-        assert _delegateToClass != null : "Delegate to class handler expected.";
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(_delegateToClass != null, "Delegate to class handler expected.");
         boolean valid = true;
 
         _interfaceMethods = _interface.getMethods();
diff --git a/v1/src/xmlconfig/org/apache/xmlbeans/impl/config/PrePostExtension.java b/v1/src/xmlconfig/org/apache/xmlbeans/impl/config/PrePostExtension.java
index 6dc795e..7b8e10f 100644
--- a/v1/src/xmlconfig/org/apache/xmlbeans/impl/config/PrePostExtension.java
+++ b/v1/src/xmlconfig/org/apache/xmlbeans/impl/config/PrePostExtension.java
@@ -19,6 +19,7 @@
 package org.apache.xmlbeans.impl.config;
 
 import org.apache.xmlbeans.XmlObject;
+import org.apache.xmlbeans.XmlBeans;
 import org.apache.xml.xmlbeans.x2004.x02.xbean.config.Extensionconfig;
 
 import javax.xml.namespace.QName;
@@ -64,7 +65,8 @@
 
     private boolean lookAfterPreAndPost(XmlObject loc)
     {
-        assert _delegateToClass!=null : "Delegate to class handler expected.";
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(_delegateToClass != null, "Delegate to class handler expected.");
         boolean valid = true;
 
         try
diff --git a/v1/src/xmlconfig/org/apache/xmlbeans/impl/config/SchemaConfig.java b/v1/src/xmlconfig/org/apache/xmlbeans/impl/config/SchemaConfig.java
index dd3255a..0199018 100644
--- a/v1/src/xmlconfig/org/apache/xmlbeans/impl/config/SchemaConfig.java
+++ b/v1/src/xmlconfig/org/apache/xmlbeans/impl/config/SchemaConfig.java
@@ -22,11 +22,11 @@
 import org.apache.xmlbeans.XmlObject;
 import org.apache.xmlbeans.XmlError;
 import org.apache.xmlbeans.impl.schema.StscState;
+import org.apache.xmlbeans.impl.common.SequencedHashMap;
 
 import javax.xml.namespace.QName;
 import java.util.Collections;
 import java.util.Iterator;
-import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
 
@@ -54,10 +54,10 @@
     
     private SchemaConfig(Config[] configs)
     {
-        _packageMap = new LinkedHashMap();
-        _prefixMap = new LinkedHashMap();
-        _suffixMap = new LinkedHashMap();
-        _qnameMap = new LinkedHashMap();
+        _packageMap = new SequencedHashMap();
+        _prefixMap = new SequencedHashMap();
+        _suffixMap = new SequencedHashMap();
+        _qnameMap = new SequencedHashMap();
         _extensionHolder = new ExtensionHolder();
 
         for (int i = 0; i < configs.length; i++)
diff --git a/v1/src/xmlpublic/org/apache/xmlbeans/GDate.java b/v1/src/xmlpublic/org/apache/xmlbeans/GDate.java
index 57f9620..fd89dae 100644
--- a/v1/src/xmlpublic/org/apache/xmlbeans/GDate.java
+++ b/v1/src/xmlpublic/org/apache/xmlbeans/GDate.java
@@ -21,6 +21,7 @@
 import java.util.Date;
 import java.util.GregorianCalendar;
 import java.util.TimeZone;
+import java.util.SimpleTimeZone;
 
 /**
  * Represents an XML Schema-compatible Gregorian date.
@@ -40,7 +41,7 @@
 public final class GDate implements GDateSpecification, java.io.Serializable
 {
     private static final long serialVersionUID = 1L;
-    
+
     // for fast equality comparison, hashing, and serialization
     private transient String _canonicalString;
     private transient String _string;
@@ -56,15 +57,15 @@
     private int _tzsign;
     private int _tzh;
     private int _tzm;
-    
-    
+
+
     /* package */ static final BigDecimal _zero = BigDecimal.valueOf(0);
     /* package */ static final BigDecimal _one = BigDecimal.valueOf(1);
 
     /**
      * Constructs a GDate based on a lexical representation.
      */
-    public GDate(CharSequence string)
+    public GDate(String string)
     {
         // first trim XML whitespace
         int len = string.length();
@@ -247,7 +248,7 @@
                     }
                     try
                     {
-                        fs = new BigDecimal(string.subSequence(start, len).toString());
+                        fs = new BigDecimal(string.substring(start, len));
                     }
                     catch (Throwable e)
                     {
@@ -364,6 +365,15 @@
      */
     public GDate(Calendar calendar)
     {
+        XmlCalendar xCal = null;
+        boolean isXC = false;
+
+        if (calendar instanceof XmlCalendar)
+        {
+            isXC = true;
+            xCal = (XmlCalendar) calendar;
+        }
+
         // we must scrape the "isSet" information out before accessing anything
         boolean isSetYear = calendar.isSet(Calendar.YEAR);
         boolean isSetEra = calendar.isSet(Calendar.ERA);
@@ -380,9 +390,9 @@
 
         if (isSetYear)
         {
-            int y = calendar.get(Calendar.YEAR);
+            int y = isXC ? xCal.peek(Calendar.YEAR) : calendar.get(Calendar.YEAR);
             if (isSetEra && calendar instanceof GregorianCalendar)
-                if (calendar.get(Calendar.ERA) == GregorianCalendar.BC)
+                if ((isXC ? xCal.peek(Calendar.ERA) : calendar.get(Calendar.ERA)) == GregorianCalendar.BC)
                     y = 1 - y;
             _bits |= HAS_YEAR;
             _CY = y;
@@ -390,12 +400,12 @@
         if (isSetMonth)
         {
             _bits |= HAS_MONTH;
-            _M = calendar.get(Calendar.MONTH) + 1; // !!note
+            _M = (isXC ? xCal.peek(Calendar.MONTH) : calendar.get(Calendar.MONTH)) + 1; // !!note
         }
         if (isSetDay)
         {
             _bits |= HAS_DAY;
-            _D = calendar.get(Calendar.DAY_OF_MONTH);
+            _D = isXC ? xCal.peek(Calendar.DAY_OF_MONTH) : calendar.get(Calendar.DAY_OF_MONTH);
         }
         boolean gotTime = false;
 
@@ -406,30 +416,34 @@
 
         if (isSetHourOfDay)
         {
-            h = calendar.get(Calendar.HOUR_OF_DAY);
+            h = isXC ? xCal.peek(Calendar.HOUR_OF_DAY) : calendar.get(Calendar.HOUR_OF_DAY);
             gotTime = true;
         }
         else if (isSetHour && isSetAmPm)
         {
-            h = calendar.get(Calendar.HOUR) + calendar.get(Calendar.AM_PM) * 12;
+            if (isXC)
+                h = xCal.peek(Calendar.HOUR) + xCal.peek(Calendar.AM_PM) * 12;
+            else
+                h = calendar.get(Calendar.HOUR) + calendar.get(Calendar.AM_PM) * 12;
             gotTime = true;
         }
 
         if (isSetMinute)
         {
-            m = calendar.get(Calendar.MINUTE);
+            m = isXC ? xCal.peek(Calendar.MINUTE) : calendar.get(Calendar.MINUTE);
             gotTime = true;
         }
 
         if (isSetSecond)
         {
-            s = calendar.get(Calendar.SECOND);
+            s = isXC ? xCal.peek(Calendar.SECOND) : calendar.get(Calendar.SECOND);
             gotTime = true;
         }
 
         if (isSetMillis)
         {
-            fs = BigDecimal.valueOf(calendar.get(Calendar.MILLISECOND), 3);
+            fs = BigDecimal.valueOf(isXC ? xCal.peek(Calendar.MILLISECOND)
+                                         : calendar.get(Calendar.MILLISECOND), 3);
             gotTime = true;
         }
 
@@ -444,9 +458,11 @@
 
         if (isSetZone)
         {
-            int zoneOffsetInMilliseconds = calendar.get(Calendar.ZONE_OFFSET);
+            int zoneOffsetInMilliseconds = isXC ? xCal.peek(Calendar.ZONE_OFFSET)
+                                                : calendar.get(Calendar.ZONE_OFFSET);
             if (isSetDst)
-                zoneOffsetInMilliseconds += calendar.get(Calendar.DST_OFFSET);
+                zoneOffsetInMilliseconds += isXC ? xCal.peek(Calendar.DST_OFFSET)
+                                                 : calendar.get(Calendar.DST_OFFSET);
 
             _bits |= HAS_TIMEZONE;
             if (zoneOffsetInMilliseconds == 0)
@@ -537,7 +553,7 @@
         return (ch - '0');
     }
 
-    private static final int twoDigit(CharSequence str, int index)
+    private static final int twoDigit(String str, int index)
     {
         char ch1 = str.charAt(index);
         char ch2 = str.charAt(index + 1);
@@ -758,7 +774,7 @@
      * contained in this instance, or 0 if the
      * instance doesn't contain information corresponding to a
      * Schema type.
-     * <p> 
+     * <p>
      * Value will be equal to
      * {@link SchemaType#BTC_NOT_BUILTIN},
      * {@link SchemaType#BTC_G_YEAR},
@@ -899,7 +915,8 @@
 
     private static final int _padTwoAppend(char[] b, int i, int n)
     {
-        assert(n >= 0 && n < 100);
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(n >= 0 && n < 100);
         b[i] = _tensDigit[n];
         b[i + 1] = _onesDigit[n];
         return i + 2;
@@ -926,43 +943,45 @@
         b[i + 3] = _onesDigit[r];
         return i + 4;
     }
-    
+
     private static final TimeZone GMTZONE = TimeZone.getTimeZone("GMT");
+    private static final int ONE_MINUTE = 60 * 1000;
+    private static final int ONE_HOUR = 60 * ONE_MINUTE;
     private static final TimeZone[] MINUSZONE =
             {
-                TimeZone.getTimeZone("GMT-00:00"),
-                TimeZone.getTimeZone("GMT-01:00"),
-                TimeZone.getTimeZone("GMT-02:00"),
-                TimeZone.getTimeZone("GMT-03:00"),
-                TimeZone.getTimeZone("GMT-04:00"),
-                TimeZone.getTimeZone("GMT-05:00"),
-                TimeZone.getTimeZone("GMT-06:00"),
-                TimeZone.getTimeZone("GMT-07:00"),
-                TimeZone.getTimeZone("GMT-08:00"),
-                TimeZone.getTimeZone("GMT-09:00"),
-                TimeZone.getTimeZone("GMT-10:00"),
-                TimeZone.getTimeZone("GMT-11:00"),
-                TimeZone.getTimeZone("GMT-12:00"),
-                TimeZone.getTimeZone("GMT-13:00"),
-                TimeZone.getTimeZone("GMT-14:00"),
+                new SimpleTimeZone(0, "GMT-00:00"),
+                new SimpleTimeZone(-1 * ONE_HOUR, "GMT-01:00"),
+                new SimpleTimeZone(-2 * ONE_HOUR, "GMT-02:00"),
+                new SimpleTimeZone(-3 * ONE_HOUR, "GMT-03:00"),
+                new SimpleTimeZone(-4 * ONE_HOUR, "GMT-04:00"),
+                new SimpleTimeZone(-5 * ONE_HOUR, "GMT-05:00"),
+                new SimpleTimeZone(-6 * ONE_HOUR, "GMT-06:00"),
+                new SimpleTimeZone(-7 * ONE_HOUR, "GMT-07:00"),
+                new SimpleTimeZone(-8 * ONE_HOUR, "GMT-08:00"),
+                new SimpleTimeZone(-9 * ONE_HOUR, "GMT-09:00"),
+                new SimpleTimeZone(-10 * ONE_HOUR, "GMT-10:00"),
+                new SimpleTimeZone(-11 * ONE_HOUR, "GMT-11:00"),
+                new SimpleTimeZone(-12 * ONE_HOUR, "GMT-12:00"),
+                new SimpleTimeZone(-13 * ONE_HOUR, "GMT-13:00"),
+                new SimpleTimeZone(-14 * ONE_HOUR, "GMT-14:00")
             };
     private static final TimeZone[] PLUSZONE =
             {
-                TimeZone.getTimeZone("GMT+00:00"),
-                TimeZone.getTimeZone("GMT+01:00"),
-                TimeZone.getTimeZone("GMT+02:00"),
-                TimeZone.getTimeZone("GMT+03:00"),
-                TimeZone.getTimeZone("GMT+04:00"),
-                TimeZone.getTimeZone("GMT+05:00"),
-                TimeZone.getTimeZone("GMT+06:00"),
-                TimeZone.getTimeZone("GMT+07:00"),
-                TimeZone.getTimeZone("GMT+08:00"),
-                TimeZone.getTimeZone("GMT+09:00"),
-                TimeZone.getTimeZone("GMT+10:00"),
-                TimeZone.getTimeZone("GMT+11:00"),
-                TimeZone.getTimeZone("GMT+12:00"),
-                TimeZone.getTimeZone("GMT+13:00"),
-                TimeZone.getTimeZone("GMT+14:00"),
+                new SimpleTimeZone(0, "GMT+00:00"),
+                new SimpleTimeZone(1 * ONE_HOUR, "GMT+01:00"),
+                new SimpleTimeZone(2 * ONE_HOUR, "GMT+02:00"),
+                new SimpleTimeZone(3 * ONE_HOUR, "GMT+03:00"),
+                new SimpleTimeZone(4 * ONE_HOUR, "GMT+04:00"),
+                new SimpleTimeZone(5 * ONE_HOUR, "GMT+05:00"),
+                new SimpleTimeZone(6 * ONE_HOUR, "GMT+06:00"),
+                new SimpleTimeZone(7 * ONE_HOUR, "GMT+07:00"),
+                new SimpleTimeZone(8 * ONE_HOUR, "GMT+08:00"),
+                new SimpleTimeZone(9 * ONE_HOUR, "GMT+09:00"),
+                new SimpleTimeZone(10 * ONE_HOUR, "GMT+10:00"),
+                new SimpleTimeZone(11 * ONE_HOUR, "GMT+11:00"),
+                new SimpleTimeZone(12 * ONE_HOUR, "GMT+12:00"),
+                new SimpleTimeZone(13 * ONE_HOUR, "GMT+13:00"),
+                new SimpleTimeZone(14 * ONE_HOUR, "GMT+14:00")
             };
 
     /* package */ static final TimeZone timeZoneForGDate(GDateSpecification date)
@@ -974,18 +993,21 @@
             return GMTZONE;
         if (date.getTimeZoneMinute() == 0 && date.getTimeZoneHour() <= 14 && date.getTimeZoneHour() >= 0)
             return date.getTimeZoneSign() < 0 ? MINUSZONE[date.getTimeZoneHour()] : PLUSZONE[date.getTimeZoneHour()];
-        
+
+        int h = date.getTimeZoneHour(),
+            m = date.getTimeZoneMinute(),
+            offset = h * ONE_HOUR + m * ONE_MINUTE;
         char[] zb = new char[9];
         zb[0] = 'G';
         zb[1] = 'M';
         zb[2] = 'T';
         zb[3] = (date.getTimeZoneSign() < 0) ? '-' : '+';
-        GDate._padTwoAppend(zb, 4, date.getTimeZoneHour());
+        GDate._padTwoAppend(zb, 4, h);
         zb[6] = ':';
-        GDate._padTwoAppend(zb, 7, date.getTimeZoneMinute());
-        return TimeZone.getTimeZone(new String(zb));
+        GDate._padTwoAppend(zb, 7, m);
+        return new SimpleTimeZone(zb[3] == '+' ? offset : -offset, new String(zb));
     }
-    
+
     /* package */ static String formatGDate(GDateSpecification spec)
     {
         // We've used a char[] rather than a StringBuffer for a 4x speedup
diff --git a/v1/src/xmlpublic/org/apache/xmlbeans/GDateBuilder.java b/v1/src/xmlpublic/org/apache/xmlbeans/GDateBuilder.java
index f564c80..26ab608 100644
--- a/v1/src/xmlpublic/org/apache/xmlbeans/GDateBuilder.java
+++ b/v1/src/xmlpublic/org/apache/xmlbeans/GDateBuilder.java
@@ -119,7 +119,7 @@
      * union of the lexical spaces of all the schema
      * date/time types (except for duration).
      */
-    public GDateBuilder(CharSequence string)
+    public GDateBuilder(String string)
     {
         this(new GDate(string));
     }
@@ -808,7 +808,8 @@
             // In new month, day may need to be pegged before proceeding
             if (hasDay())
             {
-                assert(_D >= 1);
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(_D >= 1);
                 temp = _maxDayInMonthFor(_CY, _M);
                 if (_D > temp)
                     _D = temp;
@@ -933,7 +934,7 @@
     {
         // Default timezone
         TimeZone dtz = TimeZone.getDefault();
-        int offset = dtz.getOffset(date.getTime());
+        int offset = getOffset(dtz, date);
         int offsetsign = 1;
         if (offset < 0)
         {
@@ -1017,6 +1018,20 @@
         return dateForGDate(this);
     }
 
+
+    /* package */ static int getOffset(TimeZone tz, long time)
+    {
+        return getOffset(tz, new Date(time));
+    }
+
+    /* package */ static int getOffset(TimeZone tz, Date date)
+    {
+        if (tz.inDaylightTime(date))
+            return tz.getRawOffset() + (tz.useDaylightTime() ? 3600000 : 0);
+        
+        return tz.getRawOffset();
+    }
+
     /* package */ static int julianDateForGDate(GDateSpecification date)
     {
         if (!date.hasDate())
@@ -1050,7 +1065,7 @@
         else
         {
             TimeZone def = TimeZone.getDefault();
-            int offset = def.getOffset(to1970Ms);
+            int offset = getOffset(def, to1970Ms);
             to1970Ms -= offset;
         }
 
diff --git a/v1/src/xmlpublic/org/apache/xmlbeans/GDuration.java b/v1/src/xmlpublic/org/apache/xmlbeans/GDuration.java
index 2e2094d..9e7b87c 100644
--- a/v1/src/xmlpublic/org/apache/xmlbeans/GDuration.java
+++ b/v1/src/xmlpublic/org/apache/xmlbeans/GDuration.java
@@ -63,7 +63,7 @@
      * union of the lexical spaces of all the schema
      * date/time types (except for duration).
      */
-    public GDuration(CharSequence str)
+    public GDuration(String str)
     {
         // Form:        -PnYnMnDTnHnMnS
         // (where each n may be preceded by a - for us, and the whole may be -)
@@ -134,7 +134,7 @@
                 int i = start;
                 do i += 1;
                 while (i < len && GDate.isDigit(ch = str.charAt(i)));
-                _fs = new BigDecimal(str.subSequence(start, i).toString());
+                _fs = new BigDecimal(str.substring(start, i));
                 if (i >= len || ch != 'S')
                     throw new IllegalArgumentException("illegal duration");
                 start = i;
diff --git a/v1/src/xmlpublic/org/apache/xmlbeans/QNameCache.java b/v1/src/xmlpublic/org/apache/xmlbeans/QNameCache.java
index ad55f59..17c087c 100644
--- a/v1/src/xmlpublic/org/apache/xmlbeans/QNameCache.java
+++ b/v1/src/xmlpublic/org/apache/xmlbeans/QNameCache.java
@@ -37,8 +37,11 @@
      */ 
     public QNameCache(int initialCapacity, float loadFactor)
     {
-        assert initialCapacity > 0;
-        assert loadFactor > 0 && loadFactor < 1;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(initialCapacity > 0);
+            XmlBeans.assertTrue(loadFactor > 0 && loadFactor < 1);
+        }
 
         // Find a power of 2 >= initialCapacity
         int capacity = 16;
@@ -74,8 +77,9 @@
         /*
         return new QName(uri, localName);
         */
-        assert localName != null;
-        
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(localName != null);
+
         if (uri == null) uri = "";
 
         int index = hash(uri, localName) & hashmask;
diff --git a/v1/src/xmlpublic/org/apache/xmlbeans/QNameSet.java b/v1/src/xmlpublic/org/apache/xmlbeans/QNameSet.java
index 95fc533..808b648 100644
--- a/v1/src/xmlpublic/org/apache/xmlbeans/QNameSet.java
+++ b/v1/src/xmlpublic/org/apache/xmlbeans/QNameSet.java
@@ -437,7 +437,7 @@
             sb.append(prettyQName((QName)i.next()));
             sb.append(", ");
         }
-        int index = sb.lastIndexOf(", ");
+        int index = new String(sb).lastIndexOf(", ");
         if (index > 0)
             sb.setLength(index);
         sb.append(')');
diff --git a/v1/src/xmlpublic/org/apache/xmlbeans/QNameSetBuilder.java b/v1/src/xmlpublic/org/apache/xmlbeans/QNameSetBuilder.java
index 714ddf6..6189344 100644
--- a/v1/src/xmlpublic/org/apache/xmlbeans/QNameSetBuilder.java
+++ b/v1/src/xmlpublic/org/apache/xmlbeans/QNameSetBuilder.java
@@ -707,7 +707,7 @@
             sb.append(prettyQName((QName)i.next()));
             sb.append(", ");
         }
-        int index = sb.lastIndexOf(", ");
+        int index = new String(sb).lastIndexOf(", ");
         if (index > 0)
             sb.setLength(index);
         sb.append(')');
diff --git a/v1/src/xmlpublic/org/apache/xmlbeans/SchemaComponent.java b/v1/src/xmlpublic/org/apache/xmlbeans/SchemaComponent.java
index 8c544d3..258889a 100644
--- a/v1/src/xmlpublic/org/apache/xmlbeans/SchemaComponent.java
+++ b/v1/src/xmlpublic/org/apache/xmlbeans/SchemaComponent.java
@@ -79,7 +79,12 @@
             { _schemaComponent = schemaComponent; }
 
         protected Ref(SchemaTypeSystem schemaTypeSystem, String handle)
-            { assert(handle != null); _schemaTypeSystem = schemaTypeSystem; _handle = handle; }
+        {
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(handle != null);
+            _schemaTypeSystem = schemaTypeSystem;
+            _handle = handle;
+        }
 
         private SchemaComponent _schemaComponent;
         private SchemaTypeSystem _schemaTypeSystem;
diff --git a/v1/src/xmlpublic/org/apache/xmlbeans/XmlBeans.java b/v1/src/xmlpublic/org/apache/xmlbeans/XmlBeans.java
index d27f78a..4f0f388 100644
--- a/v1/src/xmlpublic/org/apache/xmlbeans/XmlBeans.java
+++ b/v1/src/xmlpublic/org/apache/xmlbeans/XmlBeans.java
@@ -40,6 +40,31 @@
         };
 
     /**
+     * By default, assertions are off.  This can be turned on by setting the
+     * system property "xmlbeans.enableassertions" or "xmlbeans.ea".
+     */
+    public static final boolean ASSERTS = _getAsserting();
+
+    private static boolean _getAsserting()
+    {
+        return    System.getProperty("xmlbeans.ea") != null
+               || System.getProperty("xmlbeans.esa") != null
+               || System.getProperty("xmlbeans.enableassertions") != null;
+    }
+
+    public static final void assertTrue(boolean test, String message)
+    {
+        if (ASSERTS && !test)
+            throw new RuntimeException(message == null ? "AssertionException, no message."
+                                                       : "AssertionException: ".concat(message));
+    }
+
+    public static final void assertTrue(boolean test)
+    {
+        assertTrue(test, null);
+    }
+
+    /**
      * Returns a thread local QNameCache
      */
     public static QNameCache getQNameCache ( )
@@ -72,8 +97,7 @@
 
     private static RuntimeException causedException(RuntimeException e, Throwable cause)
     {
-        e.initCause(cause);
-        return e;
+        return new XmlRuntimeException(e.toString(), cause);
     }
 
     private static XmlException wrappedException(Throwable e)
@@ -222,7 +246,7 @@
         }
         catch (InvocationTargetException e)
         {
-            throw causedException(new IllegalStateException(e.getMessage()), e.getCause());
+            throw causedException(new IllegalStateException(e.getMessage()), e.getTargetException());
         }
     }
 
@@ -242,7 +266,7 @@
         }
         catch (InvocationTargetException e)
         {
-            throw causedException(new IllegalStateException(e.getMessage()), e.getCause());
+            throw causedException(new IllegalStateException(e.getMessage()), e.getTargetException());
         }
     }
 
@@ -301,7 +325,7 @@
         }
         catch (InvocationTargetException e)
         {
-            throw wrappedException(e.getCause());
+            throw wrappedException(e.getTargetException());
         }
     }
     
@@ -351,7 +375,7 @@
         }
         catch (InvocationTargetException e)
         {
-            throw wrappedException(e.getCause());
+            throw wrappedException(e.getTargetException());
         }
     }
     
@@ -375,7 +399,7 @@
         }
         catch (InvocationTargetException e)
         {
-            throw causedException(new IllegalStateException(e.getMessage()), e.getCause());
+            throw causedException(new IllegalStateException(e.getMessage()), e.getTargetException());
         }
     }
 
@@ -435,7 +459,7 @@
         }
         catch (InvocationTargetException e)
         {
-            throw causedException(new IllegalStateException(e.getMessage()), e.getCause());
+            throw causedException(new IllegalStateException(e.getMessage()), e.getTargetException());
         }
     }
 
diff --git a/v1/src/xmlpublic/org/apache/xmlbeans/XmlCalendar.java b/v1/src/xmlpublic/org/apache/xmlbeans/XmlCalendar.java
index 392ce28..0fb21e9 100644
--- a/v1/src/xmlpublic/org/apache/xmlbeans/XmlCalendar.java
+++ b/v1/src/xmlpublic/org/apache/xmlbeans/XmlCalendar.java
@@ -228,11 +228,11 @@
     /**
      * Gets the value for a given time field.
      * 
-     * Unlike the GregorianCalendar implementation, the get() does not
+     * Unlike the GregorianCalendar.get(), peek() does not
      * force a complete of all fields.  If you wish to force a completion
      * of all the fields, call getTime() first.
      */
-    public int get(int field)
+    public int peek(int field)
     {
         if (!isSet(field) || isTimeSet)
             return super.get(field); // forces a complete
@@ -250,8 +250,8 @@
     }
     
     private static int defaultYear = Integer.MIN_VALUE;
-    private static final int DEFAULT_DEFAULT_YEAR = 0; 
-    
+    private static final int DEFAULT_DEFAULT_YEAR = 0;
+
     /**
      * Returns the default year that is used when no year is specified.
      */ 
@@ -286,12 +286,18 @@
     /**
      * Overrides GregorianCalendar.computeTime to apply a different
      * default year.  (It must be a leap year.)
-     */ 
+     */
     protected void computeTime()
     {
         boolean unsetYear = !isSet(YEAR);
+        boolean unsetEra = !isSet(ERA);
         if (unsetYear)
             set(YEAR, getDefaultYear());
+        if (internalGet(YEAR) == 0)
+        {
+            set(ERA, BC);
+            set(YEAR, 1);
+        }
         try
         {
             super.computeTime();
@@ -300,9 +306,29 @@
         {
             if (unsetYear)
                 clear(YEAR);
+            if (unsetEra)
+                clear(ERA);
         }
     }
-        
+
+    /**
+     * Overrides GregorianCalendar.computeFields to apply a different
+     * default year.  (It must be a leap year.)
+     */
+    protected void computeFields()
+    {
+        boolean unsetYear = !isSet(YEAR);
+        if (unsetYear)
+            set(YEAR, getDefaultYear());
+        if (internalGet(YEAR) == 0)
+        {
+            set(ERA, BC);
+            set(YEAR, 1);
+        }
+
+        super.computeFields();
+    }
+
     private static Date _beginningOfTime = new Date(Long.MIN_VALUE);
     
     /**
diff --git a/v1/src/xmlpublic/org/apache/xmlbeans/XmlError.java b/v1/src/xmlpublic/org/apache/xmlbeans/XmlError.java
index 0c2bb56..c25ec0c 100644
--- a/v1/src/xmlpublic/org/apache/xmlbeans/XmlError.java
+++ b/v1/src/xmlpublic/org/apache/xmlbeans/XmlError.java
@@ -15,9 +15,9 @@
 
 package org.apache.xmlbeans;
 
-import java.net.URI;
-import java.net.URISyntaxException;
 import java.io.File;
+import java.net.URL;
+import java.net.MalformedURLException;
 
 /**
  * Represents a message at a specific XML location.
@@ -238,46 +238,55 @@
     /**
      * Tries to produce a nicely formatted filename from the given string.
      */
-    protected static String formattedFileName(String rawString, URI base)
+    protected static String formattedFileName(String rawString, URL base)
     {
         if (rawString == null)
             return null;
 
-        URI uri = null;
+        URL url = null;
 
         try
         {
-            // if it looks like an absolute URI, treat it as such
-            uri = new URI(rawString);
-
-            // otherwise, treat it like a filename
-            if (!uri.isAbsolute())
-                uri = null;
+            // if it looks like a URL, treat it as such
+            url = new URL(rawString);
         }
-        catch (URISyntaxException e)
+        catch (MalformedURLException e)
         {
-            uri = null;
+            url = null;
         }
 
-        // looks like a filename; convert it to uri for relativization
-        if (uri == null)
-            uri = new File(rawString).toURI();
-
-        if (base != null)
-            uri = base.relativize(uri);
-
-        // filenames get their file: stripped off and their /'s turned into \'s (MSDOS)
-        if (uri.isAbsolute() ? uri.getScheme().compareToIgnoreCase("file") == 0 :
-            base != null && base.isAbsolute() && base.getScheme().compareToIgnoreCase("file") == 0)
+        // looks like a filename; convert it to url for relativization
+        if (url == null)
         {
             try
             {
-                return (new File(uri)).toString();
+                url = new File(rawString).toURL();
             }
-            catch (Exception e) {};
+            catch (MalformedURLException e)
+            {
+                url = null;
+            }
         }
 
-        return uri.toString();
+        String urlProtocol = url == null ? null : url.getProtocol();
+        String baseProtocol = base == null ? null : base.getProtocol();
+
+        String filepath = url == null ? rawString : url.getPath();
+
+        if (url != null && base != null
+            && urlProtocol.equals(baseProtocol))
+        {
+            //relativize
+            filepath = relativize(base.getPath(), filepath);
+        }
+
+        if ("file".equals(urlProtocol) || "file".equals(baseProtocol))
+        {
+            // filenames get their file: stripped off and their /'s turned into \'s (MSDOS)
+            filepath = new File(filepath).toString();
+        }
+
+        return filepath;
     }
 
     /**
@@ -365,10 +374,10 @@
 
     /**
      * Produces a standard string with the error message.  If a non-null
-     * URI is supplied, source names are relativized against the given
-     * URI.
+     * URL is supplied, source names are relativized against the given
+     * URL.
      */
-    public String toString ( URI base )
+    public String toString ( URL base )
     {
         // modified to carefully match the IDE's
         // workshop.workspace.ant.AntLogger regex
@@ -409,4 +418,60 @@
 
         return sb.toString();
     }
+
+    //copied from NetUtils
+    private static String relativize(String path, String absoluteResource) {
+        if (path == null || "".equals(path)) {
+            return absoluteResource;
+        }
+
+        if (path.charAt(path.length() - 1) != '/') {
+            path += "/";
+        }
+
+        if (absoluteResource.startsWith(path)) {
+            // resource is direct descendant
+            return absoluteResource.substring(path.length());
+        } else {
+            // resource is not direct descendant
+            int index = matchStrings(path, absoluteResource);
+            if (index > 0 && path.charAt(index-1) != '/') {
+                index = path.substring(0, index).lastIndexOf('/');
+                index++;
+            }
+            String pathDiff = path.substring(index);
+            String resource = absoluteResource.substring(index);
+            int levels = count(pathDiff, '/');
+            StringBuffer b = new StringBuffer();
+            for (int i = 0; i < levels; i++) {
+                b.append("../");
+            }
+            b.append(resource);
+            return b.toString();
+        }
+    }
+
+    //copied from StringUtils
+    private static int count(String str, char c) {
+        int index = 0;
+        char[] chars = str.toCharArray();
+        for (int i = 0; i < chars.length; i++) {
+            if (chars[i] == c) index++;
+        }
+        return index;
+    }
+
+    //copied from StringUtils
+    private static int matchStrings(String a, String b) {
+        int i;
+        char[] ca = a.toCharArray();
+        char[] cb = b.toCharArray();
+        int len = ( ca.length < cb.length ) ? ca.length : cb.length;
+
+        for (i = 0; i < len; i++) {
+            if (ca[i] != cb[i]) break;
+        }
+
+        return i;
+    }
 }
\ No newline at end of file
diff --git a/v1/src/xmlpublic/org/apache/xmlbeans/XmlException.java b/v1/src/xmlpublic/org/apache/xmlbeans/XmlException.java
index de34748..95ad009 100644
--- a/v1/src/xmlpublic/org/apache/xmlbeans/XmlException.java
+++ b/v1/src/xmlpublic/org/apache/xmlbeans/XmlException.java
@@ -19,6 +19,8 @@
 import java.util.Collections;
 import java.util.Collection;
 import java.util.ArrayList;
+import java.io.PrintWriter;
+import java.io.PrintStream;
 
 /**
  * A checked exception that can be thrown while processing,
@@ -31,7 +33,10 @@
 public class XmlException extends Exception
 {
     private static final long serialVersionUID = 1L;
-    
+
+    private Throwable _cause = null;
+    private String _detailMessage = null;
+
     /**
      * Constructs an XmlException from a message.
      */ 
@@ -40,13 +45,13 @@
     /**
      * Constructs an XmlException from a message and a cause.
      */ 
-    public XmlException ( String m, Throwable t ) { super( m, t ); }
-    
+    public XmlException ( String m, Throwable t ) { super( m ); _cause = t; }
+
     /**
      * Constructs an XmlException from a cause.
      */ 
-    public XmlException ( Throwable t           ) { super( t );    }
-    
+    public XmlException ( Throwable t           ) { super( ); _cause = t;   }
+
     /**
      * Constructs an XmlException from an {@link XmlError}.
      */ 
@@ -68,7 +73,7 @@
      */ 
     public XmlException ( String m, Throwable t, Collection errors )
     {
-        super( m, t );
+        this( m, t );
 
         if (errors != null)
             _errors = Collections.unmodifiableList( new ArrayList( errors ) );
@@ -79,7 +84,7 @@
      */ 
     public XmlException ( XmlRuntimeException xmlRuntimeException )
     {
-        super(
+        this(
             xmlRuntimeException.getMessage(), xmlRuntimeException.getCause() );
 
         Collection errors = xmlRuntimeException.getErrors();
@@ -107,5 +112,80 @@
         return _errors;
     }
 
+    public Throwable getCause()
+    {
+        return _cause;
+    }
+
+    public Throwable initCause(Throwable t)
+    {
+        if (_cause != this)
+            throw new IllegalStateException("Can't overwrite cause");
+        if (_cause == this)
+            throw new IllegalArgumentException("Self-causation not permitted");
+        _cause = t;
+
+        return this;
+    }
+
+
+    public String toString()
+    {
+        return getClass().getName() + ": " + getMessage();
+    }
+
+
+    public String getMessage()
+    {
+        if (_detailMessage == null)
+            _detailMessage = _cause != null ? _cause.toString() : super.getMessage();
+
+        return _detailMessage;
+    }
+
+
+    public String getLocalizedMessage()
+    {
+        return getMessage();
+    }
+
+
+    public void printStackTrace()
+    {
+        printStackTrace(System.err);
+    }
+
+
+    public void printStackTrace(PrintStream s)
+    {
+        synchronized (s)
+        {
+            super.printStackTrace(s);
+
+            Throwable ourCause = getCause();
+            if (ourCause != null)
+            {
+                s.println("Caused by: ");
+                ourCause.printStackTrace(s);
+            }
+        }
+    }
+
+
+    public void printStackTrace(PrintWriter p)
+    {
+        synchronized (p)
+        {
+            super.printStackTrace(p);
+
+            Throwable ourCause = getCause();
+            if (ourCause != null)
+            {
+                p.println("Caused by: ");
+                ourCause.printStackTrace(p);
+            }
+        }
+    }
+
     private List _errors;
 }
\ No newline at end of file
diff --git a/v1/src/xmlpublic/org/apache/xmlbeans/XmlRuntimeException.java b/v1/src/xmlpublic/org/apache/xmlbeans/XmlRuntimeException.java
index dcaf4cb..3266eaf 100644
--- a/v1/src/xmlpublic/org/apache/xmlbeans/XmlRuntimeException.java
+++ b/v1/src/xmlpublic/org/apache/xmlbeans/XmlRuntimeException.java
@@ -19,6 +19,8 @@
 import java.util.Collections;
 import java.util.Collection;
 import java.util.ArrayList;
+import java.io.PrintWriter;
+import java.io.PrintStream;
 
 /**
  * An unchecked XML exception.
@@ -30,7 +32,15 @@
 public class XmlRuntimeException extends RuntimeException
 {
     private static final long serialVersionUID = 1L;
-    
+
+    private Throwable _cause = null;
+    private String _detailMessage = null;
+
+    public XmlRuntimeException()
+    {
+        super();
+    }
+
     /**
      * Constructs an XmlRuntimeException from a message.
      */ 
@@ -39,19 +49,19 @@
     /**
      * Constructs an XmlRuntimeException from a message and a cause.
      */ 
-    public XmlRuntimeException ( String m, Throwable t ) { super( m, t ); }
-    
+    public XmlRuntimeException ( String m, Throwable t ) { super( m ); _cause = t; }
+
     /**
      * Constructs an XmlRuntimeException from a cause.
      */ 
-    public XmlRuntimeException ( Throwable t           ) { super( t );    }
-    
+    public XmlRuntimeException ( Throwable t           ) { super( ); _cause = t;   }
+
     /**
      * Constructs an XmlRuntimeException from a message, a cause, and a collection of XmlErrors.
      */ 
     public XmlRuntimeException ( String m, Throwable t, Collection errors )
     {
-        super( m, t );
+        this( m, t );
 
         if (errors != null)
             _errors = Collections.unmodifiableList( new ArrayList(errors) );
@@ -78,7 +88,7 @@
      */ 
     public XmlRuntimeException ( XmlException xmlException )
     {
-        super( xmlException.getMessage(), xmlException.getCause() );
+        this( xmlException.getMessage(), xmlException.getCause() );
 
         Collection errors = xmlException.getErrors();
 
@@ -105,5 +115,80 @@
         return _errors;
     }
 
+        public Throwable getCause()
+    {
+        return _cause;
+    }
+
+    public Throwable initCause(Throwable t)
+    {
+        if (_cause != this)
+            throw new IllegalStateException("Can't overwrite cause");
+        if (_cause == this)
+            throw new IllegalArgumentException("Self-causation not permitted");
+        _cause = t;
+
+        return this;
+    }
+
+
+    public String toString()
+    {
+        return getClass().getName() + ": " + getMessage();
+    }
+
+
+    public String getMessage()
+    {
+        if (_detailMessage == null)
+            _detailMessage = _cause != null ? _cause.toString() : super.getMessage();
+
+        return _detailMessage;
+    }
+
+
+    public String getLocalizedMessage()
+    {
+        return getMessage();
+    }
+
+
+    public void printStackTrace()
+    {
+        printStackTrace(System.err);
+    }
+
+
+    public void printStackTrace(PrintStream s)
+    {
+        synchronized (s)
+        {
+            super.printStackTrace(s);
+
+            Throwable ourCause = getCause();
+            if (ourCause != null)
+            {
+                s.println("Caused by: ");
+                ourCause.printStackTrace(s);
+            }
+        }
+    }
+
+
+    public void printStackTrace(PrintWriter p)
+    {
+        synchronized (p)
+        {
+            super.printStackTrace(p);
+
+            Throwable ourCause = getCause();
+            if (ourCause != null)
+            {
+                p.println("Caused by: ");
+                ourCause.printStackTrace(p);
+            }
+        }
+    }
+
     private List _errors;
 }
\ No newline at end of file
diff --git a/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Cursor.java b/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Cursor.java
index ca119c4..5a30606 100644
--- a/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Cursor.java
+++ b/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Cursor.java
@@ -28,6 +28,7 @@
 import org.apache.xmlbeans.impl.store.Splay.Procinst;
 import org.apache.xmlbeans.impl.store.Splay.Xmlns;
 import org.apache.xmlbeans.XmlCursor.ChangeStamp;
+import org.apache.xmlbeans.XmlBeans;
 import org.apache.xmlbeans.XmlCursor;
 import org.apache.xmlbeans.XmlObject;
 import org.apache.xmlbeans.XmlOptions;
@@ -53,8 +54,8 @@
 
 public final class Cursor implements XmlCursor, ChangeListener
 {
-    Cursor ( Root r, Splay s )        { assert s != null; _data = CursorData.getOne( r ); set( s ); }
-    Cursor ( Root r, Splay s, int p ) { assert s != null; _data = CursorData.getOne( r ); set( s, p ); }
+    Cursor ( Root r, Splay s )        { if (XmlBeans.ASSERTS) XmlBeans.assertTrue(s != null); _data = CursorData.getOne( r ); set( s ); }
+    Cursor ( Root r, Splay s, int p ) { if (XmlBeans.ASSERTS) XmlBeans.assertTrue(s != null); _data = CursorData.getOne( r ); set( s, p ); }
 
     //
     //
@@ -86,7 +87,8 @@
         
         int pa = s.getPosAfter();
 
-        assert p >= pa || s.isLeaf();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(p >= pa || s.isLeaf());
         
         return p >= pa ? s.getCchAfter() - p + pa : s.getPosLeafEnd() - p;
     }
@@ -155,10 +157,12 @@
     
             Type t = s.getType( r );
     
-            assert t != null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(t != null);
     
             XmlObject result = t.getXmlObject();
-            assert result != null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(result != null);
             return result;
         }
     }
@@ -265,8 +269,9 @@
             if (a.getRoot() != getRoot())
                 return false;
     
-            assert a.getSplay() != null;
-    
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(a.getSplay() != null);
+
             set( a );
     
             return true;
@@ -535,9 +540,12 @@
             }
             else
             {
-                assert p > 0;
-                assert !s.isRoot();
-                
+                if (XmlBeans.ASSERTS)
+                {
+                    XmlBeans.assertTrue(p > 0);
+                    XmlBeans.assertTrue(!s.isRoot());
+                }
+
                 if (p >= s.getPosAfter() && s.getCchAfter() > 0)
                 {
                     s = s.nextSplay();
@@ -545,9 +553,12 @@
                 }
                 else
                 {
-                    assert s.isLeaf();
-                    assert p < s.getPosAfter();
-    
+                    if (XmlBeans.ASSERTS)
+                    {
+                        XmlBeans.assertTrue(s.isLeaf());
+                        XmlBeans.assertTrue(p < s.getPosAfter());
+                    }
+
                     if (p != s.getPosLeafEnd())
                         p = s.getPosLeafEnd();
                     else if (s.getCchAfter() > 0)
@@ -580,7 +591,8 @@
                 {
                     Splay t = os.prevNonAttrSplay();
     
-                    assert t.isContainer();
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(t.isContainer());
     
                     //
                     // We're navigating to the content of a container.  Flush
@@ -597,7 +609,8 @@
                 }
                 else if (s.isAttr() && !os.isAttr() && os.getMaxPos() > 0)
                 {
-                    assert os.isContainer();
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(os.isContainer());
     
                     s = s.nextNonAttrSplay();
                 }
@@ -623,7 +636,8 @@
     
             if (p == 1 && s.isInvalid())
             {
-                assert s.isLeaf();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(s.isLeaf());
                 p += s.ensureContentValid();
             }
     
@@ -655,7 +669,8 @@
                 {
                     t = t.prevNonAttrSplay();
     
-                    assert t.isContainer();
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(t.isContainer());
     
                     if (t.isDoc())
                         t.ensureContentValid();
@@ -673,13 +688,15 @@
     
             if (s.isAttr())
             {
-                assert p == 0;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(p == 0);
     
                 Splay t = s.prevSplay();
     
                 if (!t.isAttr())
                 {
-                    assert t.isContainer();
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(t.isContainer());
     
                     set( t, 0 );
                     return currentTokenType();
@@ -700,21 +717,28 @@
             }
             else
             {
-                assert p > 0;
-                assert !s.isRoot();
-    
+                if (XmlBeans.ASSERTS)
+                {
+                    XmlBeans.assertTrue(p > 0);
+                    XmlBeans.assertTrue(!s.isRoot());
+                }
+
                 int posAfter = s.getPosAfter();
     
                 if (p >= posAfter)
                 {
-                    assert s.getCchAfter() > 0;
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(s.getCchAfter() > 0);
                     p = posAfter - 1;
                 }
                 else
                 {
-                    assert s.isValid();
-                    assert s.isLeaf();
-                    
+                    if (XmlBeans.ASSERTS)
+                    {
+                        XmlBeans.assertTrue(s.isValid());
+                        XmlBeans.assertTrue(s.isLeaf());
+                    }
+
                     p = p > 1 && p == posAfter - 1 ? 1 : 0;
                 }
             }
@@ -944,9 +968,12 @@
 
     void insert ( Splay sInsert, String value )
     {
-        assert !isDisposed();
-        assert Root.dv > 0 || sInsert.getRootSlow() == null;
-        assert sInsert.getCch() == 0;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(!isDisposed());
+            XmlBeans.assertTrue(Root.dv > 0 || sInsert.getRootSlow() == null);
+            XmlBeans.assertTrue(sInsert.getCch() == 0);
+        }
 
         if (value != null)
             sInsert.adjustCch( value.length() );
@@ -961,7 +988,8 @@
         else
             s.insert( getRoot(), p, sInsert, null, 0, 0, true );
 
-        assert validate();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(validate());
     }
 
     public String getTextValue ( )
@@ -1190,7 +1218,8 @@
         {
             checkDisposed();
     
-            assert !getSplay().isRoot() || getPos() == 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(!getSplay().isRoot() || getPos() == 0);
             return !getSplay().isRoot();
         }
     }
@@ -1286,7 +1315,8 @@
             if (cch < 0 || cch > maxCch)
                 cch = maxCch;
     
-            assert p + cch <= s.getEndPos();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(p + cch <= s.getEndPos());
     
             if (p + cch == s.getEndPos())
                 toNextToken();
@@ -1329,7 +1359,8 @@
             else
                 maxCch = p - s.getPosAfter();
     
-            assert pText <= sText.getEndPos();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(pText <= sText.getEndPos());
     
             if (maxCch == 0 || cch == 0)
                 return 0;
@@ -1512,7 +1543,8 @@
             }
             else
             {
-                assert p > 0;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(p > 0);
     
                 if (s.isContainer())
                 {
@@ -2039,7 +2071,8 @@
     
             String result = s.prefixForNamespace( getRoot(), ns, null, true);
 
-            assert result != null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(result != null);
 
             return result;
         }
@@ -2062,7 +2095,8 @@
     
             do
             {
-                assert c.isContainer();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(c.isContainer());
     
                 QName cName = c.getName();
                 
@@ -2263,7 +2297,8 @@
             Splay s = getSplay();
             int   p = getPos();
     
-            assert p < s.getEndPos();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(p < s.getEndPos());
     
             if (p > 0)
             {
@@ -2272,7 +2307,8 @@
     
                 int cchRemove = removeChars( getPostCch() );
     
-                assert cchRemove > 0;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(cchRemove > 0);
     
                 return true;
             }
@@ -2363,7 +2399,8 @@
                     rSrc, pSrc, getPostCch(), rDst, sDst, pDst, false ) > 0;
         }
                     
-        assert pSrc == 0;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(pSrc == 0);
             
         // Check for a movement of stuff into itself!  This case is basically
         // a no-op
@@ -2374,7 +2411,8 @@
             return false;
         }
             
-        assert pSrc == 0;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(pSrc == 0);
             
         sSrc.move( rSrc, cDst.getRoot(), cDst.getSplay(), cDst.getPos(), true );
             
@@ -2446,7 +2484,8 @@
         if (s.checkInsertionValidity( p, sDst, pDst, true ))
             return copyCharsImpl( getPostCch(), dst ) > 0;
             
-        assert p == 0;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(p == 0);
             
         // Need to make a splay copy before getting the text because the copy
         // will validate invalid contents/values
@@ -2499,7 +2538,8 @@
                 return false;
     
             TokenType tt = toFirstContentToken();
-            assert !tt.isNone();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(!tt.isNone());
     
             boolean removed = !isFinish();
             
@@ -2508,7 +2548,8 @@
                 while ( !isFinish() )
                 {
                     boolean b = removeXml();
-                    assert b;
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(b);
                 }
             }
             finally
@@ -2600,7 +2641,8 @@
             return false;
             
         TokenType tt = toFirstContentToken();
-        assert !tt.isNone();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(!tt.isNone());
                     
         boolean moved = !isFinish();
                     
@@ -2612,7 +2654,8 @@
             while ( !isFinish() )
             {
                 boolean b = moveXmlImpl( dst );
-                assert b;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(b);
             }
         }
         finally
@@ -2694,7 +2737,8 @@
         }
             
         TokenType tt = toFirstContentToken();
-        assert !tt.isNone();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(!tt.isNone());
                     
         boolean copied = !isFinish();
                     
@@ -2714,7 +2758,8 @@
                     break;
             
                 boolean b = copyXmlImpl( dst );
-                assert b;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(b);
             }
         }
         finally
@@ -2958,7 +3003,7 @@
             if (e instanceof RuntimeException)
                 throw (RuntimeException) e;
             
-            throw new RuntimeException( e.getMessage(), e );
+            throw new XmlRuntimeException( e.getMessage(), e );
         }
     }
     
@@ -3009,7 +3054,8 @@
                         break SWITCH;
 
                     case TokenType.INT_STARTDOC:
-                        assert false;
+                        if (XmlBeans.ASSERTS)
+                            XmlBeans.assertTrue(false);
                         break LOOP;
 
                 }
@@ -3135,7 +3181,8 @@
     
     private boolean validate ( )
     {
-        assert _data._goober.getRoot().validate();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(_data._goober.getRoot().validate());
         return true;
     }
 
@@ -3163,7 +3210,8 @@
         
         void add ( Root r, Splay s, int p )
         {
-            assert s.getRootSlow() == r;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(s.getRootSlow() == r);
             
             if (_cursors != null)
             {
@@ -3178,7 +3226,8 @@
             
             if (_splays == null)
             {
-                assert _count == 0;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(_count == 0);
                 _splays = new Splay [ 16 ];
                 _positions = new int [ 16 ];
             }
@@ -3202,7 +3251,8 @@
 
         void pop ( )
         {
-            assert size() > 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(size() > 0);
 
             if (_cursors != null)
             {
@@ -3253,7 +3303,8 @@
 
         boolean setCursor ( Cursor c, int i )
         {
-            assert i >= 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(i >= 0);
 
             while ( _pathEngine != null && currentSize() <= i )
             {
@@ -3266,12 +3317,14 @@
             
             if (_cursors != null)
             {
-                assert i < _cursors.size();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(i < _cursors.size());
                 c.set( (CursorGoober) _cursors.get( i ) );
             }
             else
             {
-                assert i < _count;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(i < _count);
                 c.set( _splays[ i ], _positions[ i ] );
             }
 
diff --git a/v1/src/xmlstore/org/apache/xmlbeans/impl/store/JaxenXBeansDelegate.java b/v1/src/xmlstore/org/apache/xmlbeans/impl/store/JaxenXBeansDelegate.java
index 85df54a..62accbb 100644
--- a/v1/src/xmlstore/org/apache/xmlbeans/impl/store/JaxenXBeansDelegate.java
+++ b/v1/src/xmlstore/org/apache/xmlbeans/impl/store/JaxenXBeansDelegate.java
@@ -15,6 +15,8 @@
 
 package org.apache.xmlbeans.impl.store;
 
+import org.apache.xmlbeans.XmlRuntimeException;
+
 import java.lang.reflect.Constructor;
 import java.util.List;
 
@@ -40,7 +42,7 @@
         }
         catch (Exception e)
         {
-            throw new RuntimeException(e);
+            throw new XmlRuntimeException(e);
         }
     }
 
@@ -80,7 +82,7 @@
             }
             catch ( Exception e )
             {
-                throw new RuntimeException( e );
+                throw new XmlRuntimeException( e );
             }
         }
     }
diff --git a/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Path.java b/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Path.java
index ac54b1a..3d37772 100644
--- a/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Path.java
+++ b/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Path.java
@@ -17,6 +17,7 @@
 
 import org.apache.xmlbeans.XmlCursor;
 import org.apache.xmlbeans.XmlObject;
+import org.apache.xmlbeans.XmlBeans;
 import org.apache.xmlbeans.XmlOptions;
 import org.apache.xmlbeans.XmlRuntimeException;
 import org.apache.xmlbeans.impl.common.XPath;
@@ -136,7 +137,8 @@
 
         synchronized ( _xbeanPathCache )
         {
-            assert (xqrl |= options.hasOption( _useXqrlForXpath )) || true;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue((xqrl |= options.hasOption( _useXqrlForXpath )) || true);
 
             if (!xqrl || options.hasOption( _useXbeanForXpath ))
             {
@@ -160,7 +162,8 @@
 
             if (path == null)
             {
-                assert ! options.hasOption( _useXbeanForXpath );
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(! options.hasOption( _useXbeanForXpath ));
 
                 path = (Path) _xqrlPathCache.get( pathExpr );
 
@@ -310,7 +313,8 @@
 
         static Path create ( String pathExpr, String currentNodeVar )
         {
-            assert !currentNodeVar.startsWith( "$" );
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(!currentNodeVar.startsWith( "$" ));
 
             try
             {
@@ -348,7 +352,7 @@
                 }
                 catch ( Throwable e )
                 {
-                    throw new RuntimeException( "Can't compile path", e );
+                    throw new XmlRuntimeException( "Can't compile path", e );
                 }
             }
 
@@ -364,7 +368,8 @@
         {
             XBeanPathEngine ( XPath xpath, Root r, Splay s )
             {
-                assert s.isContainer();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(s.isContainer());
 
                 _root = r;
                 _curr = _top = s;
@@ -493,7 +498,8 @@
 
         static Path create ( String pathExpr, String currentNodeVar )
         {
-            assert !currentNodeVar.startsWith( "$" ); // cezar review with ericvas
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(!currentNodeVar.startsWith( "$" )); // cezar review with ericvas
 
             JaxenXBeansDelegate.SelectPathInterface impl = JaxenXBeansDelegate.createInstance( pathExpr );
             if (impl == null)
diff --git a/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Root.java b/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Root.java
index 81a00f7..65d001d 100644
--- a/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Root.java
+++ b/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Root.java
@@ -85,7 +85,8 @@
     {
         super( ROOT );
 
-        assert stl != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(stl != null);
 
         _schemaTypeSystem = stl;
 
@@ -133,7 +134,8 @@
 
     public XmlCursor createCursor ( )
     {
-        assert validate();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(validate());
         return new Cursor( this, _doc );
     }
 
@@ -165,18 +167,22 @@
         if (!isEmpty())
             _doc.removeContent( this, true );
 
-        assert isEmpty();
-        assert validate();
-        assert _leftOnly;
-        assert getCchLeft() == 0;
-        assert _text.length() == 0;
-        assert getCdocBeginLeft() == 1;
-        assert _doc != null && _leftSplay == _doc;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(isEmpty());
+            XmlBeans.assertTrue(validate());
+            XmlBeans.assertTrue(_leftOnly);
+            XmlBeans.assertTrue(getCchLeft() == 0);
+            XmlBeans.assertTrue(_text.length() == 0);
+            XmlBeans.assertTrue(getCdocBeginLeft() == 1);
+            XmlBeans.assertTrue(_doc != null && _leftSplay == _doc);
+        }
     }
 
     void updateCch ( Splay s, int deltaCch )
     {
-        assert !s.isRoot();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(!s.isRoot());
 
         if (deltaCch != 0)
         {
@@ -217,8 +223,11 @@
     {
         // only one of (set or name) is not null
         // or both are null for a wildcard
-        assert ( name == null || set == null );
-        assert n >= 0;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue( name == null || set == null );
+            XmlBeans.assertTrue( n >= 0 );
+        }
 
         if (parent == null || parent.isLeaf())
             return null;
@@ -626,7 +635,7 @@
             }
             catch ( Exception e )
             {
-                throw new RuntimeException( e.getMessage(), e );
+                throw new XmlRuntimeException( e.getMessage(), e );
             }
         }
         
@@ -639,7 +648,7 @@
             }
             catch ( Exception e )
             {
-                throw new RuntimeException( e.getMessage(), e );
+                throw new XmlRuntimeException( e.getMessage(), e );
             }
         }
         
@@ -668,7 +677,7 @@
             }
             catch ( Throwable e )
             {
-                throw new RuntimeException( e.getMessage(), e );
+                throw new XmlRuntimeException( e.getMessage(), e );
             }
         }
 
@@ -702,7 +711,7 @@
                 }
                 catch ( Throwable e )
                 {
-                    throw new RuntimeException( e.getMessage(), e );
+                    throw new XmlRuntimeException( e.getMessage(), e );
                 }
             }
         }
@@ -730,7 +739,8 @@
             
             try
             {
-                assert r.disableStoreValidation();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue( r.disableStoreValidation() );
 
                 _xr.parse( inputSource );
 
@@ -776,7 +786,8 @@
             }
             finally
             {
-                assert r.enableStoreValidation();
+                if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( r.enableStoreValidation() );
             }
         }
 
@@ -1049,7 +1060,8 @@
         }
         catch ( IOException e )
         {
-            assert false: "StringReader should not throw IOException";
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue( false, "StringReader should not throw IOException" );
             throw new XmlException( e.getMessage(), e );
         }
         finally
@@ -1080,7 +1092,8 @@
         {
             super( null, null );
             
-            assert isEmpty();
+            if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( isEmpty() );
 
             _options = options;
             _type = type;
@@ -1141,7 +1154,8 @@
     {
         LoadContext ( Root root, XmlOptions options )
         {
-            assert root != null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue( root != null );
 
             _options = options = XmlOptions.maskNull( options );
 
@@ -1189,14 +1203,18 @@
 
         private int getCp ( Splay s )
         {
-            assert _root.isLeftOnly();
-            assert dv > 0 || s.getCpSlow() == s.getCchLeft();
+            if (XmlBeans.ASSERTS)
+            {
+                XmlBeans.assertTrue( _root.isLeftOnly());
+                XmlBeans.assertTrue( dv > 0 || s.getCpSlow() == s.getCchLeft());
+            }
             return s.getCchLeft();
         }
 
         private void adjustCch ( Splay s, int delta )
         {
-            assert _root.isLeftOnly();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue( _root.isLeftOnly());
 
             s.adjustCch( delta );
 
@@ -1205,15 +1223,17 @@
 
             for ( s = s.nextSplay() ; s != null ; s = s.nextSplay() )
             {
-                assert s.isAttr() || s.isRoot();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue( s.isAttr() || s.isRoot());
                 s.adjustCchLeft( delta );
             }
         }
 
         private void insert ( Splay s )
         {
-            assert !_finished;
-            assert s.getCch() == 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue( !_finished );
+                XmlBeans.assertTrue( s.getCch() == 0 );
 
             _root.insertSplay( s, _root._leftSplay );
 
@@ -1226,8 +1246,11 @@
 
         private void insert ( Splay s, char[] buf, int off, int cch )
         {
-            assert !_finished;
-            assert s.getCch() == 0;
+            if (XmlBeans.ASSERTS)
+            {
+                XmlBeans.assertTrue( !_finished );
+                XmlBeans.assertTrue( s.getCch() == 0 );
+            }
             insert( s );
             _root._text.insert( getCp( s ), buf, off, cch );
             adjustCch( s, cch );
@@ -1235,8 +1258,11 @@
 
         private void insert ( Splay s, String text )
         {
-            assert !_finished;
-            assert s.getCch() == 0;
+            if (XmlBeans.ASSERTS)
+            {
+                XmlBeans.assertTrue( !_finished );
+                XmlBeans.assertTrue( s.getCch() == 0 );
+            }
             insert( s );
             _root._text.insert( getCp( s ), text );
             adjustCch( s, text.length() );
@@ -1288,7 +1314,8 @@
             }
             catch ( XmlException e )
             {
-                assert false;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue( false );
             }
         }
 
@@ -1302,7 +1329,8 @@
             if (_frontier != _root._doc)
                 throw new XmlException( "Document not ended" );
 
-            assert _root._leftOnly;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue( _root._leftOnly );
 
             _finished = true;
 
@@ -1345,7 +1373,8 @@
                                 s );
 
                             // The above insert should not splay the tree
-                            assert _root.isLeftOnly();
+                            if (XmlBeans.ASSERTS)
+                                XmlBeans.assertTrue( _root.isLeftOnly());
                         }
                     }
                 }
@@ -1357,7 +1386,8 @@
 
             _root.invalidateVersion();
             
-            assert _root.isLeftOnly();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue( _root.isLeftOnly() );
         }
 
         private QName checkName ( String local, String uri )
@@ -1486,9 +1516,12 @@
             }
             else
             {
-                assert !_finished;
-                assert _frontier.isBegin();
-                assert !_frontier.isLeaf();
+                if (XmlBeans.ASSERTS)
+                {
+                    XmlBeans.assertTrue( !_finished );
+                    XmlBeans.assertTrue( _frontier.isBegin());
+                    XmlBeans.assertTrue( !_frontier.isLeaf());
+                }
 
                 if (_lastNonAttr == _frontier)
                 {
@@ -1578,7 +1611,8 @@
 
         int preText ( )
         {
-            assert !_finished;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue( !_finished);
 
             return getCp( _lastNonAttr ) + _lastNonAttr.getCch();
         }
@@ -1617,7 +1651,8 @@
 
         void text ( char[] buf, int off, int cch )
         {
-            assert !_finished;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue( !_finished );
 
             int start = off;
             int end = off + cch;
@@ -1646,7 +1681,8 @@
 
         void text ( String text )
         {
-            assert !_finished;
+            if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue( !_finished );
 
             int start = 0;
             int end = text.length();
@@ -1989,8 +2025,11 @@
 
         associateSourceName( options );
 
-        assert validate();
-        assert isLeftOnly();
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue( validate() );
+            XmlBeans.assertTrue( isLeftOnly() );
+        }
     }
 
     public static void dump ( XmlObject x )
@@ -2503,16 +2542,19 @@
 
     void insertSplay ( Splay s, Splay a )
     {
-        assert s != null;
-        assert !s.isRoot();
-        assert a != null;
-        assert Root.dv > 0 || validateSplayTree();
-        assert !a.isRoot();
-        assert Root.dv > 0 || a.getRootSlow() == this;
-        assert s._parentSplay == null;
-        assert s._rightSplay == null;
-        assert s._leftSplay != null || s.getCchLeft() == 0;
-        assert s._leftSplay != null || s.getCdocBeginLeft() == 0;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue( s != null );
+            XmlBeans.assertTrue( !s.isRoot() );
+            XmlBeans.assertTrue( a != null );
+            XmlBeans.assertTrue( Root.dv > 0 || validateSplayTree() );
+            XmlBeans.assertTrue( !a.isRoot() );
+            XmlBeans.assertTrue( Root.dv > 0 || a.getRootSlow() == this );
+            XmlBeans.assertTrue( s._parentSplay == null );
+            XmlBeans.assertTrue( s._rightSplay == null );
+            XmlBeans.assertTrue( s._leftSplay != null || s.getCchLeft() == 0 );
+            XmlBeans.assertTrue( s._leftSplay != null || s.getCdocBeginLeft() == 0 );
+        }
 
         int cch = s.getCch();
         int cbegin = s.getCdocBegin();
@@ -2529,11 +2571,13 @@
             s._leftSplay = _leftSplay;
             s._parentSplay = this;
 
-            assert s.getCchLeft() == 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue( s.getCchLeft() == 0 );
             s.adjustCchLeft(
                 _leftSplay.getCchLeft() + _leftSplay.getCch() );
 
-            assert s.getCdocBeginLeft() == 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue( s.getCdocBeginLeft() == 0 );
             s.adjustCdocBeginLeft(
                 _leftSplay.getCdocBeginLeft() + _leftSplay.getCdocBegin() );
 
@@ -2598,7 +2642,8 @@
             s.splay( this, this );
         }
 
-        assert validateSplayTree();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( validateSplayTree() );
     }
 
     /**
@@ -2609,9 +2654,12 @@
     
     void insertSingleSplaySansSplayInLeftOnlyTree ( Splay s, Splay a )
     {
-        assert _leftOnly;
-        assert s._rightSplay == null;
-        assert s._leftSplay == null;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue( _leftOnly );
+            XmlBeans.assertTrue( s._rightSplay == null );
+            XmlBeans.assertTrue( s._leftSplay == null );
+        }
 
         s._leftSplay = a;
         s._parentSplay = a._parentSplay;
@@ -2644,14 +2692,17 @@
 
     Splay removeSplays ( Splay first, Splay last )
     {
-        assert validateSplayTree();
-        assert first != last;;
-        assert !first.isRoot();
-        assert !first.isDoc();
-        assert Root.dv > 0 || first.getRootSlow() == this;
-        assert Root.dv > 0 || last.getRootSlow() == this;
-        assert Root.dv > 0 || first.compareSlow( last ) == -1;
-        assert !last.isRoot() || last == this;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue( validateSplayTree() );
+            XmlBeans.assertTrue( first != last );
+            XmlBeans.assertTrue( !first.isRoot() );
+            XmlBeans.assertTrue( !first.isDoc() );
+            XmlBeans.assertTrue( Root.dv > 0 || first.getRootSlow() == this );
+            XmlBeans.assertTrue( Root.dv > 0 || last.getRootSlow() == this );
+            XmlBeans.assertTrue( Root.dv > 0 || first.compareSlow( last ) == -1 );
+            XmlBeans.assertTrue( !last.isRoot() || last == this );
+        }
 
         Splay x = last.prevSplay();
 
@@ -2666,11 +2717,14 @@
         x.splay( this, last );
         first.splay( this, x );
 
-        assert this == last || this._leftSplay == last;
-        assert last._leftSplay == x;
-        assert x._leftSplay == first;
-        assert x._rightSplay == null;
-        assert first._leftSplay != null;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue( this == last || this._leftSplay == last );
+            XmlBeans.assertTrue( last._leftSplay == x );
+            XmlBeans.assertTrue( x._leftSplay == first );
+            XmlBeans.assertTrue( x._rightSplay == null );
+            XmlBeans.assertTrue( first._leftSplay != null );
+        }
 
         int firstCchLeft = first.getCchLeft();
         int firstCbeginLeft = first.getCdocBeginLeft();
@@ -2693,11 +2747,14 @@
         first.adjustCchLeft( - firstCchLeft );
         first.adjustCdocBeginLeft( - firstCbeginLeft );
 
-        assert first.getCchLeft() == 0;
-        assert first.getCdocBeginLeft() == 0;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue( first.getCchLeft() == 0 );
+            XmlBeans.assertTrue( first.getCdocBeginLeft() == 0 );
 
-        assert x.getCchLeft() + deltaCchLeft + x.getCch() == 0;
-        assert x.getCdocBeginLeft() + deltaCbeginLeft + x.getCdocBegin() == 0;
+            XmlBeans.assertTrue( x.getCchLeft() + deltaCchLeft + x.getCch() == 0 );
+            XmlBeans.assertTrue( x.getCdocBeginLeft() + deltaCbeginLeft + x.getCdocBegin() == 0 );
+        }
 
         first._leftSplay._parentSplay = last;
         last._leftSplay = first._leftSplay;
@@ -2706,7 +2763,8 @@
         first._leftSplay = null;
         first._parentSplay = null;
 
-        assert validateSplayTree();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( validateSplayTree() );
 
         return x;
     }
@@ -2795,7 +2853,8 @@
             {
                 s = validateContent( s );
 
-                assert s.isEnd(): "Missing END, splay: " + s.getDebugId();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue( s.isEnd(), "Missing END, splay: " + s.getDebugId() );
 
                 s = s.nextSplay();
             }
@@ -2812,7 +2871,8 @@
 
         s = validateContent( s );
 
-        assert s.isRoot(): "Expected root";
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( s.isRoot(), "Expected root" );
 
         return true;
     }
@@ -2828,8 +2888,11 @@
     {
         if (g instanceof Type)
         {
-            assert g.getKind() == TYPE;
-            assert s.isTypeable();
+            if (XmlBeans.ASSERTS)
+            {
+                XmlBeans.assertTrue( g.getKind() == TYPE );
+                XmlBeans.assertTrue( s.isTypeable() );
+            }
 
             context._numSplayTypes++;
 
@@ -2843,20 +2906,27 @@
         }
         else
         {
-            assert g.getKind() != TYPE;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue( g.getKind() != TYPE );
         }
 
-        assert g.getSplay() == s;
-        assert g.getRoot() == this;
-        assert g.getPos() >= 0;
-        assert g.getPos() <= s.getMaxPos();
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue( g.getSplay() == s );
+            XmlBeans.assertTrue( g.getRoot() == this );
+            XmlBeans.assertTrue( g.getPos() >= 0 );
+            XmlBeans.assertTrue( g.getPos() <= s.getMaxPos() );
+            }
     }
 
     private boolean doValidate ( )
     {
-        assert validateDoc();
-        assert validateSplayTree();
-        assert getCchLeft() == _text.length();
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue( validateDoc() );
+            XmlBeans.assertTrue( validateSplayTree() );
+            XmlBeans.assertTrue( getCchLeft() == _text.length() );
+        }
 
         validateChangeListenerState();
 
@@ -2876,51 +2946,67 @@
         {
             if (s.isRoot())
             {
-                assert s.getCchAfter() == 0;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue( s.getCchAfter() == 0 );
             }
             else if (s.isBegin())
             {
                 Begin b = (Begin) s;
 
-                assert b.getName() != null;
+                if (XmlBeans.ASSERTS)
+                {
+                    XmlBeans.assertTrue( b.getName() != null );
 
-                assert
-                    b.getFinish() == null ||
-                        b.getFinish().getContainer() == b;
+                    XmlBeans.assertTrue(
+                        b.getFinish() == null ||
+                            b.getFinish().getContainer() == b );
+                }
 
                 if (b.isLeaf())
                 {
-                    assert b.getFinish() == null;
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue( b.getFinish() == null );
                 }
                 else
                 {
-                    assert b.getFinish() != null;
-                    assert b.getFinish().getContainer() == b;
-                    assert b.getCchValue() == 0;
+                    if (XmlBeans.ASSERTS)
+                    {
+                        XmlBeans.assertTrue( b.getFinish() != null );
+                        XmlBeans.assertTrue( b.getFinish().getContainer() == b );
+                        XmlBeans.assertTrue( b.getCchValue() == 0 );
+                    }
                 }
             }
             else if (s.isAttr())
             {
-                assert s.getName() != null;
-                assert s.getCchAfter() == 0;
+                if (XmlBeans.ASSERTS)
+                {
+                    XmlBeans.assertTrue( s.getName() != null );
+                    XmlBeans.assertTrue( s.getCchAfter() == 0 );
+                }
             }
 
             if (s.isProcinst())
             {
-                assert s.getName().getNamespaceURI() != null;
-                assert s.getName().getNamespaceURI().length() == 0;
+                if (XmlBeans.ASSERTS)
+                {
+                    XmlBeans.assertTrue( s.getName().getNamespaceURI() != null );
+                    XmlBeans.assertTrue( s.getName().getNamespaceURI().length() == 0 );
+                }
             }
 
             if (s.isContainer())
             {
-                assert s.getContainer() == recentContainer;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue( s.getContainer() == recentContainer );
 
                 if (!s.isLeaf())
                     recentContainer = (Container) s;
             }
             else if (s.isFinish())
             {
-                assert s.getContainer() == recentContainer;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue( s.getContainer() == recentContainer );
                 recentContainer = recentContainer.getContainer();
             }
 
@@ -2934,36 +3020,50 @@
 
             if (isInvalid())
             {
-                assert s.isTypeable();
-                assert s.peekType() != null;
+                if (XmlBeans.ASSERTS)
+                {
+                    XmlBeans.assertTrue( s.isTypeable() );
+                    XmlBeans.assertTrue( s.peekType() != null );
+                }
 
-                assert context._numSplayTypes == 1;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue( context._numSplayTypes == 1 );
 
                 if (s.isDoc())
                 {
-                    assert s.getCchAfter() == 0;
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue( s.getCchAfter() == 0 );
                     Splay n = s.nextNonAttrSplay();
 
-                    assert n.isRoot();
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue( n.isRoot() );
                 }
                 else if (s.isBegin())
                 {
-                    assert s.isLeaf();
-                    assert s.getCchValue() == 0;
+                    if (XmlBeans.ASSERTS)
+                    {
+                        XmlBeans.assertTrue( s.isLeaf() );
+                        XmlBeans.assertTrue( s.getCchValue() == 0 );
+                    }
                 }
                 else if (s.isAttr())
                 {
-                    assert s.getCchValue() == 0;
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue( s.getCchValue() == 0 );
                 }
             }
             else
             {
-                assert context._numSplayTypes <= 1;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue( context._numSplayTypes <= 1 );
             }
         }
 
-        assert context._cInvalidatableTypes == _cInvalidatableTypes;
-        assert context._cElemOrderSensitiveTypes ==_cElemOrderSensitiveTypes;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue( context._cInvalidatableTypes == _cInvalidatableTypes );
+            XmlBeans.assertTrue( context._cElemOrderSensitiveTypes ==_cElemOrderSensitiveTypes );
+        }
 
         // TODO: Validate indices
 
@@ -3036,9 +3136,12 @@
 
         ValidateStats stats = new ValidateStats();
 
-        assert _parentSplay == null;
-        assert _rightSplay  == null;
-        assert _doc._leftSplay == null;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue( _parentSplay == null );
+            XmlBeans.assertTrue( _rightSplay  == null );
+            XmlBeans.assertTrue( _doc._leftSplay == null );
+        }
 
         Splay s = this;
 
@@ -3050,7 +3153,8 @@
                 s = s._leftSplay;
         }
 
-        assert s == _doc;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( s == _doc );
 
         loop:
         for ( ; ; )
@@ -3100,8 +3204,11 @@
                     }
                     else
                     {
-                        assert p._leftSplay == s;
-                        assert p._rightSplay != null;
+                        if (XmlBeans.ASSERTS)
+                        {
+                            XmlBeans.assertTrue( p._leftSplay == s );
+                            XmlBeans.assertTrue( p._rightSplay != null );
+                        }
 
                         s = p._rightSplay;
 
@@ -3116,22 +3223,26 @@
 
         for ( s = _doc ; s != null ; s = s.nextSplay() )
         {
-            assert !_leftOnly || s._rightSplay == null: "" + s.getDebugId();
-            assert s._leftSplay  == null || s._leftSplay ._parentSplay == s;
-            assert s._rightSplay == null || s._rightSplay._parentSplay == s;
-
-            if (s._leftSplay == null)
+            if (XmlBeans.ASSERTS)
             {
-                assert s.getCchLeft() == 0;
-                assert s.getCdocBeginLeft() == 0;
+                XmlBeans.assertTrue( !_leftOnly || s._rightSplay == null, Integer.toString(s.getDebugId()) );
+                XmlBeans.assertTrue( s._leftSplay  == null || s._leftSplay ._parentSplay == s );
+                XmlBeans.assertTrue( s._rightSplay == null || s._rightSplay._parentSplay == s );
             }
-            else
-            {
-                assert
-                    s.getCchLeft() == stats.getCch( s._leftSplay ):
-                        "" + s.getDebugId();
 
-                assert s.getCdocBeginLeft() == stats.getCbegin( s._leftSplay );
+            if (XmlBeans.ASSERTS)
+            {
+                if (s._leftSplay == null)
+                {
+                    XmlBeans.assertTrue( s.getCchLeft() == 0 );
+                    XmlBeans.assertTrue( s.getCdocBeginLeft() == 0 );
+                }
+                else
+                {
+                    XmlBeans.assertTrue(s.getCchLeft() == stats.getCch( s._leftSplay ),
+                       Integer.toString(s.getDebugId()) );
+                    XmlBeans.assertTrue( s.getCdocBeginLeft() == stats.getCbegin( s._leftSplay ) );
+                }
             }
         }
 
@@ -3160,36 +3271,43 @@
 
     void invalidateVersion ( )
     {
-        assert _changeClients == null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( _changeClients == null );
 
         __version++;
 
-        assert (_debugChangeVersion = __version) == 0 || true;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( (_debugChangeVersion = __version) == 0 || true );
     }
 
     // Use this *only* if you know what you are doing!
     void restoreVersion ( long oldVersion )
     {
-        assert __version >= oldVersion;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( __version >= oldVersion );
         __version = oldVersion;
-        assert (_debugChangeVersion = __version) == 0 || true;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( (_debugChangeVersion = __version) == 0 || true );
     }
 
     boolean validateChangeStarted ( )
     {
-        assert _changeClients == null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( _changeClients == null );
         return _changeClients == null;
     }
 
     boolean validateChangeListenerState ( )
     {
-        assert _debugChangeVersion == __version;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( _debugChangeVersion == __version );
         return true;
     }
 
     void registerForChange ( ChangeListener listener )
     {
-        assert validateChangeListenerState();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( validateChangeListenerState() );
 
         // See if this listener is the first one on the list.  Easy but not
         // totally complete  optimization
@@ -3206,11 +3324,13 @@
 
     void startChange ( )
     {
-        assert validateChangeListenerState();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( validateChangeListenerState() );
 
         long currentVersion = 0;
 
-        assert (currentVersion = __version) == 0 || true;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( (currentVersion = __version) == 0 || true );
 
         while ( _changeClients != null )
         {
@@ -3218,7 +3338,8 @@
             _changeClients = _changeClients._next;
         }
 
-        assert currentVersion == __version;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( currentVersion == __version );
     }
 
     //
@@ -3277,7 +3398,8 @@
 
         int distance ( Splay parent, QName name, QNameSet set, int n )
         {
-            assert n >= 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue( n >= 0 );
 
             if (_version != Root.this.getVersion())
                 return Integer.MAX_VALUE - 1;
@@ -3290,7 +3412,8 @@
 
         Begin fetch ( Splay parent, QName name, QNameSet set, int n )
         {
-            assert n >= 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue( n >= 0 );
 
             if (_version != Root.this.getVersion() || _parent != parent ||
                   ! cacheSame(name, set) || n == 0)
diff --git a/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Saver.java b/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Saver.java
index 9867b48..05e9106 100644
--- a/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Saver.java
+++ b/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Saver.java
@@ -22,11 +22,14 @@
 import org.apache.xmlbeans.impl.common.XmlEventBase;
 import org.apache.xmlbeans.impl.common.XmlNameImpl;
 import org.apache.xmlbeans.impl.common.QNameHelper;
+import org.apache.xmlbeans.impl.common.SequencedHashMap;
 import org.apache.xmlbeans.impl.store.Splay.Container;
 import org.apache.xmlbeans.impl.store.Splay.Xmlns;
 import org.apache.xmlbeans.impl.values.NamespaceManager;
 import org.apache.xmlbeans.XmlCursor;
 import org.apache.xmlbeans.XmlOptions;
+import org.apache.xmlbeans.XmlBeans;
+import org.apache.xmlbeans.XmlRuntimeException;
 import java.io.InputStream;
 import java.io.IOException;
 import java.io.OutputStream;
@@ -36,7 +39,6 @@
 import java.io.Writer;
 import java.util.ArrayList;
 import java.util.HashMap;
-import java.util.LinkedHashMap;
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.Map;
@@ -75,28 +77,38 @@
     //
     //
     //
-    
-    private final Object monitor()
+
+    /*  javac error (JDK 1.3.1):
+        "monitor() is inherited from org.apache.xmlbeans.impl.store.Saver.XmlInputStreamSaver.XmlEventImpl
+        and hides method in outer class org.apache.xmlbeans.impl.store.Saver.  An explicit 'this'
+        qualifier must be used to select the desired instance."
+
+        To minimize the number of changes, this method was renamed to avoid javac confusion.
+    */
+    private final Object saverMonitor()
     {
         return _root;
     }
 
     Saver ( Root r, Splay s, int p, XmlOptions options )
     {
-        assert Root.dv > 0 || s.getRootSlow() == r;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(Root.dv > 0 || s.getRootSlow() == r);
 
-        // Input s and p must be normalized already
-        assert p < s.getEndPos();
+            // Input s and p must be normalized already
+            XmlBeans.assertTrue(p < s.getEndPos());
+        }
 
         _root = r;
         _top = _splay = s;
         _pos = p;
         _version = r.getVersion();
         _sb = new StringBuffer();
-        _attrs = new LinkedHashMap();
+        _attrs = new SequencedHashMap();
         _attrNames = new HashSet();
         _firstPush = true;
-        
+
 
         // Initialize the state of the namespaces
         _namespaceStack = new ArrayList();
@@ -104,17 +116,17 @@
         _prefixMap = new HashMap();
 
         // Stops the synthesis of this namspace and make for better
-        // roundtripping 
+        // roundtripping
         addMapping( "xml", Splay._xml1998Uri );
 
         // Check for implicit namespaces
-        
+
         options = XmlOptions.maskNull( options );
 
         if (options.hasOption( XmlOptions.SAVE_IMPLICIT_NAMESPACES ))
         {
             Map m = (Map) options.get( XmlOptions.SAVE_IMPLICIT_NAMESPACES );
-            
+
             for ( Iterator i = m.keySet().iterator() ; i.hasNext() ; )
             {
                 String prefix = (String) i.next();
@@ -124,9 +136,9 @@
 
         if (options.hasOption( XmlOptions.SAVE_SUGGESTED_PREFIXES ))
             _suggestedPrefixes = (Map) options.get( XmlOptions.SAVE_SUGGESTED_PREFIXES);
-        
+
         // If the default prefix has not been mapped, do so now
-        
+
         if (getNamespaceForPrefix( "" ) == null)
         {
             _initialDefaultUri = new String( "" );
@@ -164,7 +176,7 @@
             if (!saver._synthNamespaces.isEmpty())
                 _preComputedNamespaces = saver._synthNamespaces;
         }
-        
+
         _useDefaultNamespace =
             options.hasOption( XmlOptions.SAVE_USE_DEFAULT_NAMESPACE );
 
@@ -180,14 +192,14 @@
             _fragment = Splay._xmlFragment;
 
         // Outer overrides inner
-        
+
         _inner =
             options.hasOption( XmlOptions.SAVE_INNER ) &&
                 !options.hasOption( XmlOptions.SAVE_OUTER );
-        
+
         if (_inner && !_top.isDoc())
             _synthElem = _fragment;
-        
+
         else if (options.hasOption( XmlOptions.SAVE_SYNTHETIC_DOCUMENT_ELEMENT ))
         {
             _fragment = _synthElem =
@@ -196,17 +208,31 @@
             if (_synthElem == null)
                 throw new IllegalArgumentException( "Null synthetic element" );
         }
-        
+
         _preProcess = true;
     }
 
-    protected final void checkVersion ( )
+    /*  javac error (JDK 1.3.1):
+        "checkVersion() is inherited from org.apache.xmlbeans.impl.store.Saver.XmlInputStreamSaver.XmlEventImpl
+        and hides method in outer class org.apache.xmlbeans.impl.store.Saver.  An explicit 'this'
+        qualifier must be used to select the desired instance."
+
+        To minimize the number of changes, this method was renamed to avoid javac confusion.
+    */
+    protected final void checkSaverVersion ( )
     {
         if (_version != _root.getVersion())
             throw new ConcurrentModificationException( "Document changed during save" );
     }
 
-    protected final Root getRoot ( ) { return _root; }
+    /*  javac error (JDK 1.3.1):
+        "getRoot() is inherited from org.apache.xmlbeans.impl.store.Saver.XmlInputStreamSaver.XmlEventImpl
+        and hides method in outer class org.apache.xmlbeans.impl.store.Saver.  An explicit 'this'
+        qualifier must be used to select the desired instance."
+
+        To minimize the number of changes, this method was renamed to avoid javac confusion.
+    */
+    protected final Root getSaverRoot ( ) { return _root; }
     protected final Map  getUriMap ( ) { return _uriMap; }
     protected final Map  getPrefixMap ( ) { return _prefixMap; }
 
@@ -221,7 +247,7 @@
 
     protected abstract void emitDocType(
         String doctypeName, String publicID, String systemID );
-    
+
     protected abstract void emitComment ( Splay s );
     protected abstract void emitTextAfter ( Splay s, int p, int cch );
     protected abstract void emitEnd ( Splay s, QName name );
@@ -229,7 +255,7 @@
     protected abstract void emitContainer ( Container c, QName name );
 
     // Called when a synthetic prefix is created.
-    
+
     protected void syntheticNamespace (
         String prefix, String uri, boolean considerCreatingDefault ) { }
 
@@ -253,16 +279,20 @@
 
     final String text ( )
     {
-        assert _text != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(_text != null);
         
         return _text.toString();
     }
 
     final boolean noText ( )
     {
-        assert _text != null || _sb.length() == 0;
-        assert _text == null || _text == _sb;
-        
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(_text != null || _sb.length() == 0);
+            XmlBeans.assertTrue(_text == null || _text == _sb);
+        }
+
         return _text == null;
     }
 
@@ -299,9 +329,9 @@
 
     protected final boolean process ( )
     {
-        synchronized (monitor())
+        synchronized (saverMonitor())
         {
-            checkVersion();
+            checkSaverVersion();
     
             if (_preProcess)
             {
@@ -319,7 +349,8 @@
                 if ((p == 0 && s.isFinish()) ||
                       (s.isLeaf() && p == s.getPosLeafEnd()))
                 {
-                    assert _splay == null;
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(_splay == null);
                     processTextFragment( null, 0, 0 );
                     return true;
                 }
@@ -328,9 +359,11 @@
     
                 if (p > 0)
                 {
-                    assert !s.isLeaf() || p != s.getPosLeafEnd();
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(!s.isLeaf() || p != s.getPosLeafEnd());
                     processTextFragment( s, p, s.getPostCch( p ) );
-                    assert _splay == null;
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(_splay == null);
                     return true;
                 }
     
@@ -372,7 +405,8 @@
                     return true;
                 }
     
-                assert s.isContainer();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(s.isContainer());
     
                 _splay = s;
                 _endSplay = s.isContainer() ? s.getFinishSplay() : s;
@@ -394,7 +428,8 @@
     
             if (_postProcess)
             {
-                assert _splay != null;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(_splay != null);
     
                 boolean emitted = false;
     
@@ -408,21 +443,26 @@
     
                     if (_skipContainerFinish)
                     {
-                        assert s.isBegin() && !s.isLeaf() && s.getCchAfter() ==0;
-                        assert _splay.isFinish();
-    
+                        if (XmlBeans.ASSERTS)
+                        {
+                            XmlBeans.assertTrue(s.isBegin() && !s.isLeaf() && s.getCchAfter() == 0);
+                            XmlBeans.assertTrue(_splay.isFinish());
+                        }
+
                         _splay = _splay == _endSplay ? null : _splay.nextSplay();
                     }
     
                     if (_skipContainerFinish || s.isLeaf())
                     {
-                        assert !_postPop;
+                        if (XmlBeans.ASSERTS)
+                            XmlBeans.assertTrue(!_postPop);
                         _postPop = true;
                     }
     
                     if (!s.isDoc())
                     {
-                        assert noText();
+                        if (XmlBeans.ASSERTS)
+                            XmlBeans.assertTrue(noText());
     
                         int cchAfter = s.getCchAfter();
     
@@ -432,7 +472,7 @@
     
                             if (cchAfter > 0)
                             {
-                                Root r = getRoot();
+                                Root r = getSaverRoot();
     
                                 r._text.fetch(
                                     _text,
@@ -505,7 +545,7 @@
             if (_splay == null)
                 return false;
     
-            if (_version != getRoot().getVersion())
+            if (_version != getSaverRoot().getVersion())
                 throw new IllegalStateException( "Document changed" );
     
             _skipContainerFinish = false;
@@ -541,7 +581,8 @@
             case Splay.ATTR :
             default :
             {
-                assert false: "Unexpected splay kind " + _splay.getKind();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(false, "Unexpected splay kind " + _splay.getKind());
                 return false;
             }
             }
@@ -554,7 +595,8 @@
 
     private final void processContainer ( Container c )
     {
-        assert c.isDoc() || c.isBegin();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(c.isDoc() || c.isBegin());
 
         QName name =
             _synthElem != null && c == _top
@@ -616,7 +658,8 @@
         if (name != null)
             ensureMapping( nameUri, null, !ensureDefaultEmpty, false );
 
-        assert noText();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(noText());
 
         if (c.isInvalid())
         {
@@ -652,7 +695,7 @@
         {
             if (_text == null)
             {
-                Root r = getRoot();
+                Root r = getSaverRoot();
 
                 r._text.fetch(
                     _text = _sb,
@@ -688,13 +731,14 @@
         if (_wantFragTest && name == null)
         {
             if ((_text != null && !Splay.isWhiteSpace( _text )) ||
-                  !c.isAfterWhiteSpace( getRoot() ))
+                  !c.isAfterWhiteSpace( getSaverRoot() ))
             {
                 _needsFrag = true;
             }
             else
             {
-                assert !c.isLeaf();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(!c.isLeaf());
                 
                 Splay s = c.nextSplay();
 
@@ -720,7 +764,7 @@
                             s = s.getFinishSplay();
                         }
 
-                        if (!s.isAfterWhiteSpace( getRoot() ))
+                        if (!s.isAfterWhiteSpace( getSaverRoot() ))
                         {
                             _needsFrag = true;
                             break;
@@ -757,7 +801,8 @@
         {
             // See if I need to gen a fragment for the document
 
-            assert name != null || (c.isDoc() && _synthElem == null);
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(name != null || (c.isDoc() && _synthElem == null));
 
             if (name == null)
             {
@@ -801,7 +846,8 @@
 
         emitEnd( _splay, name );
 
-        assert !_postPop;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(!_postPop);
 
         _postPop = true;
     }
@@ -855,13 +901,15 @@
 
     private final void processAttrFragment ( Splay s )
     {
-        assert s.isNormalAttr();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(s.isNormalAttr());
 
         pushFragmentMappings( s );
 
         ensureMapping( s.getUri(), null, false, true );
 
-        assert noText();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(noText());
 
         if (s.isInvalid())
         {
@@ -933,19 +981,22 @@
 
     String mappingPrefix ( )
     {
-        assert hasMapping();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(hasMapping());
         return (String) _namespaceStack.get( _currentMapping + 6 );
     }
 
     String mappingUri ( )
     {
-        assert hasMapping();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(hasMapping());
         return (String) _namespaceStack.get( _currentMapping + 7 );
     }
 
     String mappingPrevPrefixUri ( )
     {
-        assert hasMapping();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(hasMapping());
         return (String) _namespaceStack.get( _currentMapping + 5 );
     }
 
@@ -996,7 +1047,8 @@
             String defaultUri = (String) _prefixMap.get( "" );
 
             // I map the default to "" at the very beginning
-            assert defaultUri != null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(defaultUri != null);
 
             if (defaultUri.length() > 0)
                 addMapping( "", "" );
@@ -1048,8 +1100,11 @@
 
     private final void addMapping ( String prefix, String uri )
     {
-        assert uri != null;
-        assert prefix != null;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(uri != null);
+            XmlBeans.assertTrue(prefix != null);
+        }
 
         // If the prefix being mapped here is already mapped to a uri,
         // that uri will either go out of scope or be mapped to another
@@ -1091,7 +1146,8 @@
                     i -= 8;
                 }
 
-                assert i > 0;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(i > 0);
             }
         }
 
@@ -1172,7 +1228,8 @@
 
     protected final String getUriMapping ( String uri )
     {
-        assert _uriMap.get( uri ) != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(_uriMap.get( uri ) != null);
         return (String) _uriMap.get( uri );
     }
 
@@ -1203,8 +1260,11 @@
         String uri, String candidatePrefix,
         boolean considerCreatingDefault, boolean mustHavePrefix )
     {
-        assert uri != null;
-        assert candidatePrefix == null || candidatePrefix.length() > 0;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(uri != null);
+            XmlBeans.assertTrue(candidatePrefix == null || candidatePrefix.length() > 0);
+        }
 
         // Can be called for no-namespaced things
 
@@ -1250,7 +1310,8 @@
             }
         }
 
-        assert candidatePrefix != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(candidatePrefix != null);
 
         syntheticNamespace( candidatePrefix, uri, considerCreatingDefault );
 
@@ -1261,8 +1322,11 @@
 
     public final String find_prefix_for_nsuri ( String uri, String prefix )
     {
-        assert uri != null;
-        assert prefix == null || prefix.length() > 0;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(uri != null);
+            XmlBeans.assertTrue(prefix == null || prefix.length() > 0);
+        }
 
         boolean emptyUri = uri.length() == 0;
         
@@ -1291,7 +1355,7 @@
     
     static final class SynthNamespaceSaver extends Saver
     {
-        LinkedHashMap _synthNamespaces = new LinkedHashMap();
+        Map _synthNamespaces = new SequencedHashMap();
         
         SynthNamespaceSaver ( Root r, Splay s, int p, XmlOptions options )
         {
@@ -1360,7 +1424,7 @@
                         emit( '>' );
 
                         if (_text == null)
-                            emit( getRoot().getCp( c ), cch );
+                            emit( getSaverRoot().getCp( c ), cch );
                         else
                             emit( _text );
 
@@ -1374,7 +1438,8 @@
                 }
                 else
                 {
-                    assert !c.isLeaf();
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(!c.isLeaf());
 
                     if (c.getCchAfter() == 0 && c.nextNonAttrSplay().isEnd())
                     {
@@ -1387,13 +1452,14 @@
             }
             else
             {
-                assert c.isDoc();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(c.isDoc());
 
                 if (name != null)
                     emitContainerHelper( c, name, null, null, true );
 
                 if (_text == null)
-                    emit( getRoot().getCp( c ), c.getCch() );
+                    emit( getSaverRoot().getCp( c ), c.getCch() );
                 else
                     emit( _text );
 
@@ -1403,7 +1469,8 @@
 
         private void emitAttrHelper ( Splay s, String invalidValue )
         {
-            assert s.isNormalAttr();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(s.isNormalAttr());
             
             emit( ' ' );
             emitName( s.getName() );
@@ -1412,7 +1479,7 @@
             if (invalidValue != null)
                 emit( invalidValue );
             else
-                emit( getRoot().getCp( s ), s.getCch() );
+                emit( getSaverRoot().getCp( s ), s.getCch() );
 
             entitizeAttrValue();
 
@@ -1433,7 +1500,8 @@
             Splay extraAttr, StringBuffer extraAttrText,
             boolean close )
         {
-            assert name != null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(name != null);
 
             emit( '<' );
             emitName( name );
@@ -1466,7 +1534,7 @@
 
         protected void emitText ( Splay s, int p, int cch )
         {
-            emit( s.getCpForPos( getRoot(), p ), cch );
+            emit( s.getCpForPos( getSaverRoot(), p ), cch );
             entitizeContent();
         }
 
@@ -1537,8 +1605,11 @@
 
         protected void emitXmlns ( String prefix, String uri )
         {
-            assert prefix != null;
-            assert uri != null;
+            if (XmlBeans.ASSERTS)
+            {
+                XmlBeans.assertTrue(prefix != null);
+                XmlBeans.assertTrue(uri != null);
+            }
 
             emit( "xmlns" );
 
@@ -1590,7 +1661,8 @@
         protected void emitDocType(
             String doctypeName, String publicID, String systemID )
         {
-            assert doctypeName != null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(doctypeName != null);
             
             emit( "<!DOCTYPE " );
             emit( doctypeName );
@@ -1613,16 +1685,18 @@
         
         protected void emitComment ( Splay s )
         {
-            assert s.isComment();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(s.isComment());
             emit( "<!--" );
-            emit( getRoot().getCp( s ), s.getCchValue() );
+            emit( getSaverRoot().getCp( s ), s.getCchValue() );
             entitizeComment();
             emit( "-->" );
         }
 
         protected void emitProcinst ( Splay s )
         {
-            assert s.isProcinst();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(s.isProcinst());
             emit( "<?" );
             // TODO - encoding issues here?
             emit( s.getLocal() );
@@ -1630,7 +1704,7 @@
             if (s.getCchValue() > 0)
             {
                 emit( " " );
-                emit( getRoot().getCp( s ), s.getCchValue() );
+                emit( getSaverRoot().getCp( s ), s.getCchValue() );
                 entitizeProcinst();
             }
 
@@ -1658,7 +1732,8 @@
                 if (!process())
                     break;
 
-            assert available == getAvailable();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(available == getAvailable());
 
             if (available == 0)
                 return 0;
@@ -1668,11 +1743,13 @@
 
         private void emitName ( QName name )
         {
-            assert name != null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(name != null);
 
             String uri = name.getNamespaceURI();
 
-            assert uri != null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(uri != null);
 
             if (uri.length() != 0)
             {
@@ -1685,14 +1762,16 @@
                 }
             }
 
-            assert name.getLocalPart().length() > 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(name.getLocalPart().length() > 0);
 
             emit( name.getLocalPart() );
         }
 
         private boolean preEmit ( int cch )
         {
-            assert cch >= 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(cch >= 0);
             
             _lastEmitCch = cch;
 
@@ -1702,7 +1781,8 @@
             if (_free < cch)
                 resize( cch, -1 );
 
-            assert cch <= _free;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(cch <= _free);
 
             int used = getAvailable();
 
@@ -1712,8 +1792,11 @@
             
             if (used == 0)
             {
-                assert _in == _out;
-                assert _free == _buf.length;
+                if (XmlBeans.ASSERTS)
+                {
+                    XmlBeans.assertTrue(_in == _out);
+                    XmlBeans.assertTrue(_free == _buf.length);
+                }
                 _in = _out = 0;
             }
 
@@ -1721,7 +1804,8 @@
 
             _free -= cch;
             
-            assert _free >= 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(_free >= 0);
 
             return false;
         }
@@ -1773,8 +1857,8 @@
         private void emit ( int cp, int cch )
         {
             emit(
-                getRoot()._text._buf,
-                getRoot()._text.unObscure( cp, cch ),
+                getSaverRoot()._text._buf,
+                getSaverRoot()._text.unObscure( cp, cch ),
                 cch );
         }
 
@@ -1789,7 +1873,8 @@
 
         private void emit ( char[] buf, int off, int cch )
         {
-            assert cch >= 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(cch >= 0);
 
             if (preEmit( cch ))
                 return;
@@ -2023,7 +2108,8 @@
 
         private int replace ( int i, String replacement )
         {
-            assert replacement.length() > 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(replacement.length() > 0);
 
             int dCch = replacement.length() - 1;
 
@@ -2033,15 +2119,18 @@
                 return i + 1;
             }
 
-            assert _free >= 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(_free >= 0);
 
             if (dCch > _free)
                 i = resize( dCch, i );
             
-            assert _free >= 0;
-
-            assert _free >= dCch;
-            assert getAvailable() > 0;
+            if (XmlBeans.ASSERTS)
+            {
+                XmlBeans.assertTrue(_free >= 0);
+                XmlBeans.assertTrue(_free >= dCch);
+                XmlBeans.assertTrue(getAvailable() > 0);
+            }
 
             if (_out > _in && i >= _out)
             {
@@ -2051,7 +2140,8 @@
             }
             else
             {
-                assert i < _in;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(i < _in);
                 System.arraycopy( _buf, i, _buf, i + dCch, _in - i );
                 _in += dCch;
             }
@@ -2060,7 +2150,8 @@
 
             _free -= dCch;
             
-            assert _free >= 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(_free >= 0);
 
             return i + dCch + 1;
         }
@@ -2076,9 +2167,12 @@
 
         private int resize ( int cch, int i )
         {
-            assert _free >= 0;
-            assert cch > 0;
-            assert cch > _free;
+            if (XmlBeans.ASSERTS)
+            {
+                XmlBeans.assertTrue(_free >= 0);
+                XmlBeans.assertTrue(cch > 0);
+                XmlBeans.assertTrue(cch > _free);
+            }
 
             int newLen = _buf == null ? _initialBufSize : _buf.length * 2;
             int used = getAvailable();
@@ -2092,13 +2186,15 @@
             {
                 if (_in > _out)
                 {
-                    assert i == -1 || (i >= _out && i < _in);
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(i == -1 || (i >= _out && i < _in));
                     System.arraycopy( _buf, _out, newBuf, 0, used );
                     i -= _out;
                 }
                 else
                 {
-                    assert i == -1 || (i >= _out || i < _in);
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(i == -1 || (i >= _out || i < _in));
                     System.arraycopy( _buf, _out, newBuf, 0, used - _in );
                     System.arraycopy( _buf, 0, newBuf, used - _in, _in );
                     i = i >= _out ? i - _out : i + _out;
@@ -2111,13 +2207,17 @@
             else
             {
                 _free += newBuf.length;
-                assert _in == 0 && _out == 0;
-                assert i == -1;
+                if (XmlBeans.ASSERTS)
+                {
+                    XmlBeans.assertTrue(_in == 0 && _out == 0);
+                    XmlBeans.assertTrue(i == -1);
+                }
             }
 
             _buf = newBuf;
 
-            assert _free >= 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(_free >= 0);
 
             return i;
         }
@@ -2127,7 +2227,8 @@
             if (ensure( 1 ) == 0)
                 return -1;
 
-            assert getAvailable() > 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(getAvailable() > 0);
 
             int ch = _buf[ _out ];
 
@@ -2174,7 +2275,8 @@
             _out = (_out + len) % _buf.length;
             _free += len;
 
-            assert _free >= 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(_free >= 0);
 
             return len;
         }
@@ -2193,7 +2295,8 @@
             {
                 // I don't want to deal with the circular cases
 
-                assert _out == 0;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(_out == 0);
 
                 try
                 {
@@ -2202,12 +2305,13 @@
                 }
                 catch ( IOException e )
                 {
-                    throw new RuntimeException( e );
+                    throw new XmlRuntimeException( e );
                 }
 
                 _free += charsAvailable;
                 
-                assert _free >= 0;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(_free >= 0);
                 
                 _in = 0;
             }
@@ -2228,7 +2332,8 @@
             while ( process() )
                 ;
 
-            assert _out == 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(_out == 0);
 
             int available = getAvailable();
 
@@ -2332,7 +2437,7 @@
             }
             catch ( UnsupportedEncodingException e )
             {
-                throw new RuntimeException( e );
+                throw new XmlRuntimeException( e );
             }
 
             _textSaver = new TextSaver( r, s, p, options, encoding );
@@ -2381,7 +2486,8 @@
                 if (InputStreamSaver.this.ensure( 1 ) == 0)
                     return -1;
 
-                assert getAvailable() > 0;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(getAvailable() > 0);
 
                 int bite = _buf[ _out ];
 
@@ -2443,7 +2549,8 @@
                 if (_free == 0)
                     resize( 1 );
 
-                assert _free > 0;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(_free > 0);
 
                 _buf[ _in ] = (byte) bite;
 
@@ -2453,7 +2560,8 @@
 
             public void write ( byte[] buf, int off, int cbyte )
             {
-                assert cbyte >= 0;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(cbyte >= 0);
 
                 if (cbyte == 0)
                     return;
@@ -2463,8 +2571,11 @@
 
                 if (_in == _out)
                 {
-                    assert getAvailable() == 0;
-                    assert _free == _buf.length - getAvailable();
+                    if (XmlBeans.ASSERTS)
+                    {
+                        XmlBeans.assertTrue(getAvailable() == 0);
+                        XmlBeans.assertTrue(_free == _buf.length - getAvailable());
+                    }
                     _in = _out = 0;
                 }
 
@@ -2490,7 +2601,8 @@
 
             void resize ( int cbyte )
             {
-                assert cbyte > _free;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(cbyte > _free);
 
                 int newLen = _buf == null ? _initialBufSize : _buf.length * 2;
                 int used = getAvailable();
@@ -2522,7 +2634,8 @@
                 else
                 {
                     _free += newBuf.length;
-                    assert _in == 0 && _out == 0;
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(_in == 0 && _out == 0);
                 }
 
                 _buf = newBuf;
@@ -2570,11 +2683,13 @@
 
         private void enqueue ( XmlEventImpl e )
         {
-            assert e._next == null;
+            if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(e._next == null);
 
             if (_in == null)
             {
-                assert _out == null;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(_out == null);
                 _out = _in = e;
             }
             else
@@ -2595,8 +2710,9 @@
 
         protected void emitText ( Splay s, int p, int cch )
         {
-            assert cch > 0;
-            enqueue( new CharacterDataImpl( getRoot(), s, p, null ) );
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(cch > 0);
+            enqueue( new CharacterDataImpl( getSaverRoot(), s, p, null ) );
         }
 
         protected void emitTextFragment ( Splay s, int p, int cch )
@@ -2621,12 +2737,12 @@
             if (_text == null)
                 emitText( s, p, cch );
             else
-                enqueue( new CharacterDataImpl( getRoot(), s, -1, text() ) );
+                enqueue( new CharacterDataImpl( getSaverRoot(), s, -1, text() ) );
         }
 
         protected void emitEndPrefixMappings ( )
         {
-            Root r = getRoot();
+            Root r = getSaverRoot();
 
             for ( iterateMappings() ; hasMapping() ; nextMapping() )
             {
@@ -2645,7 +2761,7 @@
 
         protected void emitEnd ( Splay s, QName name )
         {
-            Root r = getRoot();
+            Root r = getSaverRoot();
 
             if (s.isRoot())
                 enqueue( new EndDocumentImpl( r, s ) );
@@ -2653,7 +2769,8 @@
                 enqueue( new EndElementImpl( r, s, name, getUriMap() ) );
             else
             {
-                assert s.isLeaf();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(s.isLeaf());
                 enqueue( new EndElementImpl( r, s, name, getUriMap() ) );
             }
 
@@ -2677,12 +2794,12 @@
         
         protected void emitComment ( Splay s )
         {
-            enqueue( new CommentImpl( getRoot(), s ) );
+            enqueue( new CommentImpl( getSaverRoot(), s ) );
         }
 
         protected void emitProcinst ( Splay s )
         {
-            enqueue( new ProcessingInstructionImpl( getRoot(), s ) );
+            enqueue( new ProcessingInstructionImpl( getSaverRoot(), s ) );
         }
 
         protected void emitAttrFragment ( Splay s )
@@ -2692,7 +2809,7 @@
 
         protected void emitContainer ( Container c, QName name )
         {
-            Root r = getRoot();
+            Root r = getSaverRoot();
 
             for ( iterateMappings() ; hasMapping() ; nextMapping() )
             {
@@ -2712,7 +2829,8 @@
 
             if (c.isDoc())
             {
-                assert c.isDoc();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(c.isDoc());
 
                 if (_text != null)
                 {
@@ -2750,14 +2868,17 @@
             if (uri.length() == 0)
                 uri = null;
 
-            assert n.getLocalPart().length() > 0;
+            if (XmlBeans.ASSERTS)
+            {
+                XmlBeans.assertTrue(n.getLocalPart().length() > 0);
 
-            // The following assert may fire if someone computes a name
-            // of an element/attr too late (after other events have been
-            // enqueued and the uri map has been updated.  I check later
-            // to make sure we don't crash, however.
+                // The following assert may fire if someone computes a name
+                // of an element/attr too late (after other events have been
+                // enqueued and the uri map has been updated.  I check later
+                // to make sure we don't crash, however.
 
-            assert uri == null || uriMap.containsKey( uri ) : "Problem uri " + uri;
+                XmlBeans.assertTrue(uri == null || uriMap.containsKey( uri ), "Problem uri " + uri);
+            }
 
             String prefix = null;
 
@@ -3200,7 +3321,7 @@
                         prefix = "xmlns";
                     }
 
-                    _name = new XmlNameImpl( null, local, prefix );
+                    this._name = new XmlNameImpl( null, local, prefix );
                 }
 
                 public String getValue ( )
@@ -3221,10 +3342,11 @@
                     Root r, Splay s, String value, Map uriMap )
                 {
                     super( r );
-                    assert s.isNormalAttr();
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(s.isNormalAttr());
                     _splay = s;
                     _value = value;
-                    _name = computeName( s.getName(), uriMap );
+                    this._name = computeName( s.getName(), uriMap );
                 }
 
                 public String getValue ( )
@@ -3233,7 +3355,7 @@
                     {
                         checkVersion();
     
-                        return _value != null ? _value : _splay.getText( _root );
+                        return _value != null ? _value : _splay.getText( this._root );
                     }
                 }
 
@@ -3351,7 +3473,8 @@
             {
                 super( XMLEvent.CHARACTER_DATA, r, s );
 
-                assert p > 0 || (charData != null && charData.length() > 0);
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(p > 0 || (charData != null && charData.length() > 0));
 
                 _pos = p;
                 _charData = charData;
@@ -3396,7 +3519,8 @@
             {
                 super( XMLEvent.END_ELEMENT, r, s );
 
-                assert s.isLeaf() || s.isEnd();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(s.isLeaf() || s.isEnd());
 
                 if (name == null)
                 {
@@ -3445,7 +3569,8 @@
             CommentImpl ( Root r, Splay s )
             {
                 super( XMLEvent.COMMENT, r, s );
-                assert s.isComment();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(s.isComment());
             }
 
             public String getContent ( )
@@ -3476,7 +3601,8 @@
             ProcessingInstructionImpl ( Root r, Splay s )
             {
                 super( XMLEvent.PROCESSING_INSTRUCTION, r, s );
-                assert s.isProcinst();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(s.isProcinst());
             }
 
             public String getTarget ( )
@@ -3538,7 +3664,8 @@
 
             _wantDupAttrs = true;
 
-            assert p == 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(p == 0);
 
             _startSplay = s;
             _vEventSink = vEventSink;
@@ -3571,7 +3698,8 @@
         {
             if (_text == null)
             {
-                assert cch > 0;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(cch > 0);
                 emitEvent( ValidatorListener.TEXT, s, p, null, s, p );
             }
             else
@@ -3617,10 +3745,13 @@
 
         protected void emitContainer ( Container c, QName name )
         {
-            assert _xsiNoLoc == null;
-            assert _xsiLoc == null;
-            assert _xsiType == null;
-            assert _xsiNil == null;
+            if (XmlBeans.ASSERTS)
+            {
+                XmlBeans.assertTrue(_xsiNoLoc == null);
+                XmlBeans.assertTrue(_xsiLoc == null);
+                XmlBeans.assertTrue(_xsiType == null);
+                XmlBeans.assertTrue(_xsiNil == null);
+            }
 
             for ( Splay s = c.nextSplay() ; s.isAttr() ; s = s.nextSplay() )
             {
@@ -3681,7 +3812,8 @@
 
             if (c.isDoc())
             {
-                assert c.isDoc();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(c.isDoc());
 
                 if (_text != null)
                 {
@@ -3736,15 +3868,18 @@
 
             boolean hasText = text != null || sText != null;
 
-            assert
-                !hasText ||
-                    (kind == ValidatorListener.ATTR ||
-                        kind == ValidatorListener.TEXT);
+            if (XmlBeans.ASSERTS)
+            {
+                XmlBeans.assertTrue(
+                    !hasText ||
+                        (kind == ValidatorListener.ATTR ||
+                            kind == ValidatorListener.TEXT));
 
-            assert kind != ValidatorListener.ATTR || hasText;
-            assert kind != ValidatorListener.TEXT || hasText;
+                XmlBeans.assertTrue(kind != ValidatorListener.ATTR || hasText);
+                XmlBeans.assertTrue(kind != ValidatorListener.TEXT || hasText);
 
-            assert kind != ValidatorListener.ATTR || name != null;
+                XmlBeans.assertTrue(kind != ValidatorListener.ATTR || name != null);
+            }
 
             _name = name;
             _sText = sText;
@@ -3765,8 +3900,8 @@
 
         public XmlCursor getLocationAsCursor ( )
         {
-            checkVersion();
-            return new Cursor( getRoot(), _sLoc, _pLoc );
+            checkSaverVersion();
+            return new Cursor( getSaverRoot(), _sLoc, _pLoc );
         }
 
         public boolean getXsiType ( Chars chars )
@@ -3818,11 +3953,12 @@
         private void setChars (
             Chars chars, int wsr, String string, Splay sText, int pText )
         {
-            assert string != null || sText != null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(string != null || sText != null);
 
-            checkVersion();
+            checkSaverVersion();
 
-            Root r = getRoot();
+            Root r = getSaverRoot();
 
             chars.buffer = null;
             chars.string = null;
@@ -3851,7 +3987,8 @@
             }
             else
             {
-                assert pText == sText.getPosAfter();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(pText == sText.getPosAfter());
 
                 boolean moreText = false;
 
@@ -4092,7 +4229,8 @@
             }
             else
             {
-                assert c.isDoc();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(c.isDoc());
 
                 if (name != null)
                     emitContainerHelper( c, name, null, null );
@@ -4106,7 +4244,8 @@
 
         private void emitAttrHelper ( Splay s, String value )
         {
-            assert s.isNormalAttr();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(s.isNormalAttr());
             
             String local = s.getLocal();
             String uri = s.getUri();
@@ -4115,7 +4254,7 @@
                 s.getUri(), s.getLocal(),
                 getPrefixedName( s.getName() ),
                 "CDATA",
-                value == null ? s.getText( getRoot() ) : value );
+                value == null ? s.getText( getSaverRoot() ) : value );
         }
 
         private void addNamespaceAttr ( String prefix, String uri )
@@ -4148,7 +4287,8 @@
             Container c, QName name,
             Splay extraAttr, StringBuffer extraAttrText )
         {
-            assert name != null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(name != null);
             
             _attributes.clear();
 
@@ -4188,7 +4328,7 @@
         
         private void emitCharacters ( Splay s, int p, int cch )
         {
-            emitCharacters( s.getCpForPos( getRoot(), p ), cch );
+            emitCharacters( s.getCpForPos( getSaverRoot(), p ), cch );
         }
         
         private void emitCharacters ( int cp, int cch )
@@ -4197,7 +4337,7 @@
                 return;
 
             emitCharacters(
-                getRoot()._text._buf, getRoot()._text.unObscure( cp, cch ),
+                getSaverRoot()._text._buf, getSaverRoot()._text.unObscure( cp, cch ),
                 cch );
         }
         
@@ -4330,14 +4470,14 @@
         {
             if (_lexicalhandler != null)
             {
-                int cp = getRoot().getCp( s );
+                int cp = getSaverRoot().getCp( s );
                 int cch = s.getCchValue();
 
                 try
                 {
                     _lexicalhandler.comment(
-                        getRoot()._text._buf,
-                        getRoot()._text.unObscure( cp, cch ),
+                        getSaverRoot()._text._buf,
+                        getSaverRoot()._text.unObscure( cp, cch ),
                         cch );
                 }
                 catch ( SAXException e )
@@ -4352,7 +4492,7 @@
             try
             {
                 _contentHandler.processingInstruction(
-                    s.getLocal(), s.getText( getRoot() ) );
+                    s.getLocal(), s.getText( getSaverRoot() ) );
             }
             catch ( SAXException e )
             {
@@ -4425,7 +4565,7 @@
                 }
                 catch ( ParserConfigurationException e )
                 {
-                    throw new RuntimeException( e.getMessage(), e );
+                    throw new XmlRuntimeException( e.getMessage(), e );
                 }
             }
         };
@@ -4466,7 +4606,7 @@
 
         protected void emitContainer ( Container c, QName name )
         {
-            Root r = getRoot();
+            Root r = getSaverRoot();
 
             if (c.isDoc())
             {
@@ -4503,7 +4643,8 @@
             }
             else
             {
-                assert c.isBegin();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(c.isBegin());
 
                 String qname = c.getLocal();
 
@@ -4587,9 +4728,10 @@
 
         protected void emitTextAfter ( Splay s, int p, int cch )
         {
-            assert cch > 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(cch > 0);
 
-            Root r = getRoot();
+            Root r = getSaverRoot();
 
             String text = null;
 
@@ -4612,7 +4754,7 @@
                 
         protected void emitComment ( Splay s )
         {
-            Root r = getRoot();
+            Root r = getSaverRoot();
 
             _currentNode.insertBefore(
                 _doc.createComment(
@@ -4622,7 +4764,7 @@
 
         protected void emitProcinst ( Splay s )
         {
-            Root r = getRoot();
+            Root r = getSaverRoot();
 
             _currentNode.insertBefore(
                 _doc.createProcessingInstruction(
@@ -4652,7 +4794,7 @@
             
             if (s != null)
             {
-                Root r = getRoot();
+                Root r = getSaverRoot();
 
                 _currentNode.insertBefore(
                     _doc.createTextNode(
@@ -4667,7 +4809,7 @@
 
         protected void emitCommentFragment ( Splay s )
         {
-            Root r = getRoot();
+            Root r = getSaverRoot();
 
             _currentNode.insertBefore(
                 _doc.createComment(
@@ -4677,7 +4819,7 @@
 
         protected void emitProcinstFragment ( Splay s )
         {
-            Root r = getRoot();
+            Root r = getSaverRoot();
 
             _currentNode.insertBefore(
                 _doc.createProcessingInstruction(
@@ -4698,7 +4840,7 @@
     protected StringBuffer  _text;
     protected StringBuffer  _sb;
     protected boolean       _skipContainerFinish;
-    protected LinkedHashMap _attrs;
+    protected SequencedHashMap     _attrs;
     
     private HashSet _attrNames;
 
@@ -4736,7 +4878,7 @@
     private boolean   _firstPush;
     private String    _initialDefaultUri;
     
-    private HashMap _preComputedNamespaces;
+    private Map     _preComputedNamespaces;
     private String  _filterProcinst;
     private Map     _suggestedPrefixes;
 
diff --git a/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Splay.java b/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Splay.java
index 0cb9d78..e38b4e9 100644
--- a/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Splay.java
+++ b/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Splay.java
@@ -23,6 +23,8 @@
 import org.apache.xmlbeans.XmlCursor.XmlBookmark;
 import org.apache.xmlbeans.XmlCursor.XmlMark;
 import org.apache.xmlbeans.XmlCursor;
+import org.apache.xmlbeans.XmlBeans;
+
 import java.lang.ref.Reference;
 import java.lang.ref.WeakReference;
 import java.util.HashMap;
@@ -97,55 +99,64 @@
 
     final void toggleIsLeaf ( )
     {
-        assert isBegin();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(isBegin());
         _bits ^= 0x8;
     }
 
     final boolean isValid ( )
     {
-        assert ((_bits & 0x10) == 0) || isTypeable();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(((_bits & 0x10) == 0) || isTypeable());
         return (_bits & 0x10) == 0;
     }
 
     final boolean isInvalid ( )
     {
-        assert ((_bits & 0x10) == 0) || isTypeable();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(((_bits & 0x10) == 0) || isTypeable());
         return (_bits & 0x10) != 0;
     }
 
     final void toggleIsInvalid ( )
     {
-        assert isTypeable();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(isTypeable());
         _bits ^= 0x10;
     }
 
     final void adjustCch ( int delta )
     {
         _cch += delta;
-        assert _cch >= 0;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(_cch >= 0);
     }
 
     final void adjustCchAfter ( int delta )
     {
         _cchAfter += delta;
-        assert _cchAfter >= 0;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(_cchAfter >= 0);
     }
 
     final void adjustCchLeft ( int delta )
     {
         _cchLeft += delta;
-        assert _cchLeft >= 0;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(_cchLeft >= 0);
     }
 
     final void adjustCdocBeginLeft ( int d )
     {
         _bits += d * 32;
-        assert getCdocBeginLeft() >= 0;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(getCdocBeginLeft() >= 0);
     }
 
     final Splay getFinishSplay ( )
     {
-        assert isContainer();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(isContainer());
         return isLeaf() ? this : ((Container) this).getFinish();
     }
 
@@ -156,7 +167,8 @@
 
     final int getPosLeafEnd ( )
     {
-        assert isLeaf();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(isLeaf());
         return 1 + getCchValue();
     }
 
@@ -175,7 +187,8 @@
 
     final int getPostCch ( int p )
     {
-        assert p >= 0 && p <= getEndPos();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(p >= 0 && p <= getEndPos());
 
         return
             isLeaf() && p <= getPosLeafEnd()
@@ -254,7 +267,8 @@
         case END      : return getCchAfter();
 
         default :
-            assert false: "Unexpected splay kind " +getKind();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(false, "Unexpected splay kind " + getKind());
             return 0;
         }
     }
@@ -315,7 +329,8 @@
 
     final void setName ( Root r, QName newName )
     {
-        assert isBegin() || isAttr() || isProcinst();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(isBegin() || isAttr() || isProcinst());
 
         // BUGBUG - deal with xsi:nil here too
 
@@ -329,7 +344,8 @@
 
             if (!isProcinst() && !isXmlns())
             {
-                assert isAttr() || isBegin();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(isAttr() || isBegin());
 
                 if (isBegin())
                     disconnectTypes( r );
@@ -353,7 +369,8 @@
 
     final int ensureContentValid ( )
     {
-        assert isContainer();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(isContainer());
 
         if (isValid())
             return 0;
@@ -370,7 +387,8 @@
 
     final void ensureValueValid ( )
     {
-        assert isNormalAttr();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(isNormalAttr());
 
         if (isInvalid())
         {
@@ -386,7 +404,8 @@
 
     final TokenType getTokenType ( int p )
     {
-        assert p >= 0 && p <= getMaxPos();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(p >= 0 && p <= getMaxPos());
 
         // No need to revalidate text value here because there can be no pos
         // which could exists when this splay is invalid which could be on
@@ -406,7 +425,8 @@
             if (p == 0)
                 return TokenType.START;
 
-            assert isLeaf();
+            if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(isLeaf());
 
             return p == getPosLeafEnd() ? TokenType.END : TokenType.TEXT;
 
@@ -417,7 +437,8 @@
         case END      : return TokenType.END;
 
         default :
-            assert false: "Unexpected splay kind " + getKind();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(false, "Unexpected splay kind " + getKind());
             return null;
         }
     }
@@ -430,19 +451,25 @@
 
     final void foliate ( Root r )
     {
-        assert isBegin();
-        assert !isLeaf();
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(isBegin());
+            XmlBeans.assertTrue(!isLeaf());
+        }
 
         Begin b = (Begin) this;
         Splay e = b.getFinish();
 
-        assert b.nextNonAttrSplay() == e;
-        assert b._end == e;
-        assert e.isEnd();
-        assert !b.isLeaf();
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(b.nextNonAttrSplay() == e);
+            XmlBeans.assertTrue(b._end == e);
+            XmlBeans.assertTrue(e.isEnd());
+            XmlBeans.assertTrue(!b.isLeaf());
 
-        // Caller must initiate change
-        assert r.validateChangeStarted();
+            // Caller must initiate change
+            XmlBeans.assertTrue(r.validateChangeStarted());
+        }
 
         int cchBefore = getCch();
 
@@ -460,7 +487,8 @@
         {
             nextGoober = e.nextGoober( g );
 
-            assert g.getPos() == 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(g.getPos() == 0);
             g.set( this, cchBefore + 1 );
         }
 
@@ -479,13 +507,16 @@
 
     final void defoliate ( Root r )
     {
-        assert isLeaf();
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue( isLeaf() );
 
-        // Caller must initiate change
-        assert r.validateChangeStarted();
+            // Caller must initiate change
+            XmlBeans.assertTrue( r.validateChangeStarted() );
 
-        // Caller must ensure leaf is valid
-        assert isValid();
+            // Caller must ensure leaf is valid
+            XmlBeans.assertTrue( isValid() );
+        }
 
         Begin b = (Begin) this;
 
@@ -533,7 +564,8 @@
                 g.set( b._end, gp - posLeafEnd );
         }
 
-        assert validate();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( validate() );
     }
 
     /**
@@ -543,12 +575,15 @@
 
     private final void removeTextAfter ( Root r )
     {
-        assert r != null;
-        assert Root.dv > 0 || getRootSlow() == r;
-        assert !isRoot() && !isAttr();
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue( r != null );
+            XmlBeans.assertTrue( Root.dv > 0 || getRootSlow() == r );
+            XmlBeans.assertTrue( !isRoot() && !isAttr() );
 
-        // Caller must initiate change
-        assert r.validateChangeStarted();
+            // Caller must initiate change
+            XmlBeans.assertTrue( r.validateChangeStarted() );
+        }
 
         int cchTextAfter = getCchAfter();
 
@@ -580,7 +615,8 @@
             }
         }
 
-        assert validate();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(validate());
     }
 
     /**
@@ -591,11 +627,14 @@
 
     private final int saveTextAfter ( Root r )
     {
-        assert r != null;
-        assert Root.dv > 0 || getRootSlow() == r;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(r != null);
+            XmlBeans.assertTrue(Root.dv > 0 || getRootSlow() == r);
 
-        // Caller must initiate change
-        assert r.validateChangeStarted();
+            // Caller must initiate change
+            XmlBeans.assertTrue(r.validateChangeStarted());
+        }
 
         Splay endText = this;
 
@@ -607,7 +646,8 @@
         if (cchEndText == 0)
             return 0;
 
-        assert !isRoot() && !isDoc() && !isAttr();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(!isRoot() && !isDoc() && !isAttr());
 
         Splay getsText = prevNonAttrSplay();
         int getsTextLastPos = getsText.getEndPos();
@@ -621,7 +661,8 @@
         r.updateCch( getsText, cchEndText );
         r.updateCch( endText, - cchEndText );
 
-        assert cpGetsText <= cpEndText;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(cpGetsText <= cpEndText);
 
         if (cpGetsText != cpEndText)
         {
@@ -642,7 +683,8 @@
                 g.set( getsText, getsTextLastPos + gp - posEndText );
         }
 
-        assert validate();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(validate());
 
         return cchEndText;
     }
@@ -655,18 +697,21 @@
     final void move (
         Root r, Root rDst, Splay sDst, int pDst, boolean invalidate )
     {
-        assert r != null;
-        assert Root.dv > 0 || getRootSlow() == r;
-        assert !isDoc() && !isFinish();
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(r != null);
+            XmlBeans.assertTrue(Root.dv > 0 || getRootSlow() == r);
+            XmlBeans.assertTrue(!isDoc() && !isFinish());
 
-        assert rDst == null || (r != rDst || !sDst.between( r, pDst, this ) );
-        assert rDst == null || sDst != null;
-        assert rDst == null || Root.dv > 0 || sDst.getRootSlow() == rDst;
-        assert rDst == null || pDst >= 0 && pDst < sDst.getEndPos();
+            XmlBeans.assertTrue(rDst == null || (r != rDst || !sDst.between( r, pDst, this ) ));
+            XmlBeans.assertTrue(rDst == null || sDst != null);
+            XmlBeans.assertTrue(rDst == null || Root.dv > 0 || sDst.getRootSlow() == rDst);
+            XmlBeans.assertTrue(rDst == null || pDst >= 0 && pDst < sDst.getEndPos());
 
-        assert
-            rDst == null ||
-                (true || checkInsertionValidity( 0, sDst, pDst, false ));
+            XmlBeans.assertTrue(
+                rDst == null ||
+                    (true || checkInsertionValidity( 0, sDst, pDst, false )));
+        }
 
         r.startChange();
 
@@ -720,7 +765,8 @@
             }
         }
 
-        assert sDst != this;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(sDst != this);
 
         // Compute the splay, up to which, I will remove
 
@@ -743,7 +789,8 @@
 
             if (s.isInvalid())
             {
-                assert s.isLeaf() || s.isNormalAttr();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(s.isLeaf() || s.isNormalAttr());
 
                 if (s.isNormalAttr())
                     s.ensureValueValid();
@@ -815,8 +862,11 @@
             }
         }
 
-        assert r.validate();
-        assert rDst == null || rDst.validate();
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(r.validate());
+            XmlBeans.assertTrue(rDst == null || rDst.validate());
+        }
     }
 
     /**
@@ -845,10 +895,13 @@
     final boolean checkInsertionValidity (
         int p, Splay sDst, int pDst, boolean endOk )
     {
-        assert p >= 0;
-        assert p < getEndPos();
-        assert pDst >= 0;
-        assert pDst < sDst.getEndPos();
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(p >= 0);
+            XmlBeans.assertTrue(p < getEndPos());
+            XmlBeans.assertTrue(pDst >= 0);
+            XmlBeans.assertTrue(pDst < sDst.getEndPos());
+        }
 
         boolean srcChars = false;
 
@@ -930,41 +983,47 @@
     {
 // BUGBUG - what is a new xsitype attr is inserted? -- must disconnect types
 
-        assert p < getEndPos();
-        assert cchTxt >= 0;
-        assert rootInsert != null;
-        assert rootInsert._parentSplay == null;
-        assert rootInsert.getCchLeft() + rootInsert.getCch() == cchTxt;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(p < getEndPos());
+            XmlBeans.assertTrue(cchTxt >= 0);
+            XmlBeans.assertTrue(rootInsert != null);
+            XmlBeans.assertTrue(rootInsert._parentSplay == null);
+            XmlBeans.assertTrue(rootInsert.getCchLeft() + rootInsert.getCch() == cchTxt);
 
-        // We are inserting a tree here.  Get the first splay in the tree
-        // It must either be at the root or just to the left of the root.
-        // This is the "classic" dog leg pattern I use to pass splay trees.
+            // We are inserting a tree here.  Get the first splay in the tree
+            // It must either be at the root or just to the left of the root.
+            // This is the "classic" dog leg pattern I use to pass splay trees.
 
-        assert
-            rootInsert._leftSplay == null ||
-                rootInsert._leftSplay._leftSplay == null;
+            XmlBeans.assertTrue(
+                rootInsert._leftSplay == null ||
+                    rootInsert._leftSplay._leftSplay == null);
+        }
 
         r.startChange();
 
         Splay sInsert =
             rootInsert._leftSplay == null ? rootInsert : rootInsert._leftSplay;
 
-        assert !sInsert.isDoc() && !sInsert.isFinish();
-        assert Root.dv > 0 || getRootSlow() == r;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(!sInsert.isDoc() && !sInsert.isFinish());
+            XmlBeans.assertTrue(Root.dv > 0 || getRootSlow() == r);
 
-        // When this member is called, we better be able to do the insert.
+            // When this member is called, we better be able to do the insert.
 
-        assert true || sInsert.checkInsertionValidity( 0, this, p, false );
+            XmlBeans.assertTrue(true || sInsert.checkInsertionValidity( 0, this, p, false ));
 
-        // If there is a fragment, there better be text in it
+            // If there is a fragment, there better be text in it
 
-        assert !sInsert.isFragment() || sInsert.getCch() > 0;
-
+            XmlBeans.assertTrue(!sInsert.isFragment() || sInsert.getCch() > 0);
+        }
         //
 
         Splay s = this;
 
-        assert Root.dv > 0 || sInsert.getRootSlow() == null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(Root.dv > 0 || sInsert.getRootSlow() == null);
 
         Splay sOrig = null;
         int   pOrig = 0;
@@ -980,8 +1039,11 @@
             {
                 if (s.isInvalid())
                 {
-                    assert ple == 1;
-                    assert p == 1;
+                    if (XmlBeans.ASSERTS)
+                    {
+                        XmlBeans.assertTrue(ple == 1);
+                        XmlBeans.assertTrue(p == 1);
+                    }
 
                     int cchValid = s.ensureContentValid();
 
@@ -989,11 +1051,13 @@
                     ple += cchValid;
                 }
 
-                assert s.getFinishSplay() == s;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(s.getFinishSplay() == s);
 
                 defoliate( r );
 
-                assert s.getFinishSplay() != s;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(s.getFinishSplay() != s);
 
                 if (p == ple)
                 {
@@ -1010,7 +1074,8 @@
             // after all pre-exisitng attrs.  This these cases, p == 1 on
             // the begin.  In this case, there is no need to move text later.
 
-            assert !sInsert.isAttr() || (p == 1 && s.isContainer());
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(!sInsert.isAttr() || (p == 1 && s.isContainer()));
 
             sOrig = s;
             pOrig = p;
@@ -1020,8 +1085,11 @@
             p = 0;
         }
 
-        assert p == 0;
-        assert !s.isDoc();
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue( p == 0);
+            XmlBeans.assertTrue(!s.isDoc());
+        }
 
         // Get the container receiving all of this
 
@@ -1044,7 +1112,8 @@
 
                 Begin b = (Begin) t;
 
-                assert b._container == null;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(b._container == null);
 
                 b._container = c;
 
@@ -1052,7 +1121,8 @@
             }
             else if (t.isFragment())
             {
-                assert insertingFragment == null;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(insertingFragment == null);
                 insertingFragment = t;
             }
 
@@ -1106,8 +1176,11 @@
         if (sOrig != null && !sInsert.isAttr())
         {
             int cchMoved = sOrig.moveChars( r, pOrig, -1, r, s, 0, true );
-            assert cchMoved > 0;
-            assert cchMoved == cchBypassed;
+            if (XmlBeans.ASSERTS)
+            {
+                XmlBeans.assertTrue(cchMoved > 0);
+                XmlBeans.assertTrue(cchMoved == cchBypassed);
+            }
         }
 
         // build a leaf if possible
@@ -1117,7 +1190,8 @@
 
         r.invalidateVersion();
 
-        assert r.validate();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(r.validate());
     }
 
     /**
@@ -1131,9 +1205,12 @@
         Root r, Splay sSrc, Root rSrc,
         boolean preserveType, boolean preserveNamespaces )
     {
-        assert !isFinish() && !sSrc.isFinish();
-        assert Root.dv > 0 || getRootSlow() == r;
-        assert Root.dv > 0 || sSrc.getRootSlow() == rSrc;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(!isFinish() && !sSrc.isFinish());
+            XmlBeans.assertTrue(Root.dv > 0 || getRootSlow() == r);
+            XmlBeans.assertTrue(Root.dv > 0 || sSrc.getRootSlow() == rSrc);
+        }
 
         // If the src and dst are the same splay, then there is nothing to do
 
@@ -1159,7 +1236,8 @@
         {
             // No need to startChange() here, fcns I call will do it for me
 
-            assert isContainer();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(isContainer());
 
             // Make copy of source
 
@@ -1187,8 +1265,11 @@
 
             removeContent( r, true );
 
-            assert isLeaf() || getFinishSplay() == nextSplay();
-            assert getCchValue() == 0;
+            if (XmlBeans.ASSERTS)
+            {
+                XmlBeans.assertTrue(isLeaf() || getFinishSplay() == nextSplay());
+                XmlBeans.assertTrue(getCchValue() == 0);
+            }
 
             Splay copy = copyContext.getTree();
 
@@ -1261,7 +1342,8 @@
 
         void copySplay ( Splay s, boolean copyTextAfter )
         {
-            assert !s.isDoc() && !s.isRoot();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(!s.isDoc() && !s.isRoot());
 
             Splay t;
 
@@ -1313,7 +1395,8 @@
                 throw new IllegalStateException();
             }
 
-            assert s.isValid();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(s.isValid());
 
             int cch = s.getCchValue();
 
@@ -1336,7 +1419,8 @@
 
         void copyFragment ( int cch )
         {
-            assert cch > 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(cch > 0);
 
             Splay s = new Fragment();
 
@@ -1348,7 +1432,8 @@
 
         Splay getTree ( )
         {
-            assert _frontier == null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(_frontier == null);
 
             if (_last == null)
                 return null;
@@ -1448,7 +1533,8 @@
 
     final CopyContext copySplayContents ( Root r )
     {
-        assert !isFinish() && !isXmlns();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(!isFinish() && !isXmlns());
 
         if (isContainer())
             ensureContentValid();
@@ -1514,7 +1600,8 @@
         }
         else
         {
-            assert isNormalAttr() || isComment() || isProcinst();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(isNormalAttr() || isComment() || isProcinst());
 
             int cchValue = getCchValue();
 
@@ -1540,7 +1627,8 @@
 
     final Splay copySplay ( )
     {
-        assert !isDoc() && !isFinish();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(!isDoc() && !isFinish());
 
         // Compute splay to stop at (does not get copied).  Also compute
         // a splay, to be copied, which should not have it's text after copied.
@@ -1574,7 +1662,8 @@
 
     final void removeAttributes ( Root r )
     {
-        assert isContainer();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(isContainer());
 
         for ( ; ; )
         {
@@ -1594,7 +1683,8 @@
 
     final void removeContent ( Root r, boolean removeAttrs )
     {
-        assert Root.dv > 0 || getRootSlow() == r;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(Root.dv > 0 || getRootSlow() == r);
 
         r.startChange();
 
@@ -1634,7 +1724,8 @@
         {
             if (isXmlns())
             {
-                assert false: "Unexpected kind for removeContent";
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(false, "Unexpected kind for removeContent");
             }
 
             // Fall through
@@ -1666,16 +1757,19 @@
         }
 
         default :
-            assert false: "Unexpected kind for removeContent";
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(false, "Unexpected kind for removeContent");
         }
 
-        assert isDoc() || (isBegin() && !isLeaf());
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(isDoc() || (isBegin() && !isLeaf()));
 
         Splay s = nextNonAttrSplay();
 
         if (s.isRoot())
         {
-            assert isDoc();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(isDoc());
         }
         else
         {
@@ -1687,7 +1781,8 @@
             Splay next;
             for ( s = nextNonAttrSplay() ; !s.isFinish() ; s = next )
             {
-                assert !s.isAttr();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(!s.isAttr());
 
                 if (s.isLeaf())
                     next = s.nextNonAttrSplay();
@@ -1704,7 +1799,8 @@
             // removes could have suuffled text to after this.
             //
 
-            assert !isLeaf();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(!isLeaf());
 
             if (getCchAfter() > 0)
                 removeTextAfter( r );
@@ -1742,13 +1838,15 @@
         if (r._leftSplay == r._doc && r._doc._rightSplay == null)
             r._leftOnly = true;
 
-        assert validate();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(validate());
     }
 
     final int copyChars (
         Root r, int p, int cch, Root rDst, Splay sDst, int pDst )
     {
-        assert pDst > 0 && pDst <= sDst.getEndPos();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(pDst > 0 && pDst <= sDst.getEndPos());
 
         int postCch = getPostCch( p );
 
@@ -1758,7 +1856,8 @@
         if (cch < 0 || cch > postCch)
             cch = postCch;
 
-        assert cch > 0;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(cch > 0);
 
 // TODO - uses string to avoid problems with source and dest from same buffer
 //        rewrite to not create string object
@@ -1797,7 +1896,8 @@
         r.startChange();
         rDst.startChange();
 
-        assert cch > 0;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(cch > 0);
 
         // I don't have to check the invalidity of the source because the
         // only invalid text I would have to deal with is that in a leaf, and
@@ -1833,7 +1933,8 @@
         if (sDst == this && pDst >= p && pDst <= p + cch)
             return cch;
 
-        assert pDst > 0;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(pDst > 0);
 
         Container cDst = sDst.getContainer( pDst );
         Container c = getContainer( p );
@@ -1859,7 +1960,8 @@
                 g.set( gp + cch );
         }
 
-        assert sDst != this || pDst < p || pDst > p + cch;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(sDst != this || pDst < p || pDst > p + cch);
 
         if (sDst == this)
         {
@@ -1921,7 +2023,8 @@
     {
         int maxPos = getMaxPos();
 
-        assert p > 0 && p <= maxPos;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(p > 0 && p <= maxPos);
 
         if (p == 0)
             return 0;
@@ -1963,7 +2066,8 @@
                             g.set( p );
                         else
                         {
-                            assert k == ANNOTATION;
+                            if (XmlBeans.ASSERTS)
+                                XmlBeans.assertTrue(k == ANNOTATION);
                             g.disconnect( r );
                         }
                     }
@@ -1979,11 +2083,13 @@
 
         int posAfter = getPosAfter();
 
-        assert p >= posAfter;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(p >= posAfter);
 
         int maxCch = maxPos - p + 1;
 
-        assert maxCch >= 0;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(maxCch >= 0);
 
         if (cch < 0 || cch > maxCch)
             cch = maxCch;
@@ -2020,7 +2126,8 @@
 
         r.invalidateVersion();
 
-        assert validate();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(validate());
 
         return cch;
     }
@@ -2031,7 +2138,8 @@
 
     final void insertChars ( int p, Root r, Object txt, int off, int cch )
     {
-        assert p > 0 && p <= getEndPos();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(p > 0 && p <= getEndPos());
 
         if (cch == 0)
             return;
@@ -2062,7 +2170,8 @@
 
         r.invalidateVersion();
 
-        assert validate();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(validate());
     }
 
     private static final int START_STATE = 0;
@@ -2072,12 +2181,16 @@
     public final int scrubText(
         Text text, int ws, int cp, int cch, StringBuffer sb, int state )
     {
-        assert text != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(text != null);
 
         if (text._buf == null)
         {
-            assert cch == 0;
-            assert cp == 0;
+            if (XmlBeans.ASSERTS)
+            {
+                XmlBeans.assertTrue(cch == 0);
+                XmlBeans.assertTrue(cp == 0);
+            }
             return state;
         }
 
@@ -2094,7 +2207,8 @@
         case TypeStore.WS_REPLACE     :            replace = true; break;
         case TypeStore.WS_COLLAPSE    : collapse = replace = true; break;
 
-		default : assert false: "Unknown white space rule " +ws;
+		default : if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(false, "Unknown white space rule " + ws);
         }
 
         if (!replace && !collapse)
@@ -2293,7 +2407,8 @@
 
     Splay getAttr ( QName name )
     {
-        assert name != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(name != null);
 
         if (!isContainer())
             return null;
@@ -2309,7 +2424,8 @@
 
     void setXsiNil ( Root r, boolean nil )
     {
-        assert isContainer();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(isContainer());
 
         if (getXsiNil( r ) == nil)
             return;
@@ -2319,7 +2435,8 @@
 
     boolean getXsiNil ( Root r )
     {
-        assert isContainer();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(isContainer());
 
         Splay s;
 
@@ -2339,7 +2456,8 @@
 
     QName getXsiTypeName ( Root r )
     {
-        assert isContainer();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(isContainer());
 
         Splay s;
 
@@ -2352,7 +2470,8 @@
         if (!s.isAttr())
             return null;
 
-        assert s.isXsiType();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(s.isXsiType());
 
         String value = s.getText( r, TypeStore.WS_COLLAPSE );
 
@@ -2384,7 +2503,8 @@
 
     void setXsiType ( Root r, QName typeName )
     {
-        assert isContainer();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(isContainer());
 
         if (typeName == null)
         {
@@ -2398,7 +2518,8 @@
 
         String prefix = prefixForNamespace( r, ns, null, true);
 
-        assert prefix != null : "Cannot establish prefix for " + ns;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(prefix != null, "Cannot establish prefix for ".concat(ns));
 
         if (prefix.length() > 0)
             value = prefix + ":" + value;
@@ -2422,9 +2543,12 @@
 
     void setAttr ( Root r, QName attrName, String value )
     {
-        assert isContainer();
-        assert attrName != null;
-        assert value != null;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(isContainer());
+            XmlBeans.assertTrue(attrName != null);
+            XmlBeans.assertTrue(value != null);
+        }
 
         boolean set = false;
 
@@ -2482,7 +2606,8 @@
         case DOC :
         case BEGIN :
         {
-            assert !isBegin() || isLeaf();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(!isBegin() || isLeaf());
             insertChars( 1, r, txt, off, cch );
             break;
         }
@@ -2490,7 +2615,8 @@
         {
             if (isXmlns())
             {
-                assert false: "Unexpected kind for setText";
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(false, "Unexpected kind for setText");
             }
 // TODO - if setting text of xsi:type or xsi:nil must do stuff
 // TODO - if setting text of xsi:type or xsi:nil must do stuff
@@ -2504,7 +2630,8 @@
         {
             r.startChange();
 
-            assert getCchValue() == 0;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(getCchValue() == 0);
 
             r._text.insert( r.getCp( this ), txt, off, cch );
             r.updateCch( this, cch );
@@ -2522,10 +2649,12 @@
             break;
         }
         default :
-            assert false: "Unexpected kind for setText";
+            if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(false, "Unexpected kind for setText");
         }
 
-        assert validate();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(validate());
     }
 
     final Map lookupAllPrefixMappings ( )
@@ -2608,7 +2737,8 @@
      */
     final String getPrefix ( Root r )
     {
-        assert isBegin() || isAttr();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(isBegin() || isAttr());
 
         if (isXmlns())
             return "xmlns";
@@ -2660,7 +2790,8 @@
         if ("xmlns".equals(prefix))
             return _xmlnsUri;
 
-        assert isContainer();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(isContainer());
 
         // find an xmlns decl
         for ( Container c = (Container) this ; c != null ; c = c.getContainer())
@@ -2722,7 +2853,8 @@
         if (_xmlnsUri.equals( ns ))
             return "xmlns";
 
-        assert isContainer();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(isContainer());
 
         Container c;
         Splay s;
@@ -2796,7 +2928,8 @@
         // the ordinary not-a-no-namespace case
         //
 
-        assert ns != null && ns.length() > 0;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(ns != null && ns.length() > 0);
 
         //
         // look for an existing prefix for the requested URI
@@ -2924,8 +3057,11 @@
 
     final Container getContainer ( int p )
     {
-        assert p >= 0 && p <= getEndPos();
-        assert p > 0 || !isDoc();
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(p >= 0 && p <= getEndPos());
+            XmlBeans.assertTrue(p > 0 || !isDoc());
+        }
 
         if (p == 0)
             return getContainer();
@@ -2956,8 +3092,11 @@
 
     Container findContainer ( )
     {
-        assert !isContainer();
-        assert !isFinish();
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(!isContainer());
+            XmlBeans.assertTrue(!isFinish());
+        }
 
         Splay s = nextSplay();
 
@@ -2969,13 +3108,15 @@
 
     final void invalidateText ( )
     {
-        assert isValid();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(isValid());
 
         Type t = peekType();
 
         if (t != null)
         {
-            assert isTypeable();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(isTypeable());
 
             t.invalidateText();
         }
@@ -2983,7 +3124,8 @@
 
     final void invalidateNil ( )
     {
-        assert isTypeable();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(isTypeable());
 
         if (!isAttr())
         {
@@ -3001,7 +3143,8 @@
     
     protected final void disconnectTypes ( Root r, boolean disconnectDoc )
     {
-        assert isTypeable();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(isTypeable());
 
         Splay last = isAttr() ? this : getFinishSplay();
 
@@ -3067,8 +3210,11 @@
     
     final void setType ( Root r, SchemaType sType, boolean complain )
     {
-        assert isTypeable();
-        assert sType != null;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(isTypeable());
+            XmlBeans.assertTrue(sType != null);
+        }
 
         //
         // Is the current type already this type?
@@ -3087,11 +3233,13 @@
         {
             disconnectTypes( r, true );
 
-            assert peekType() == null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(peekType() == null);
 
             new Type( r, sType, this );
 
-            assert validate();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(validate());
 
             return;
         }
@@ -3103,7 +3251,8 @@
 
         Type parentType = getContainer().getType( r );
 
-        assert parentType != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(parentType != null);
 
         //
         // You can set the attribute type, as long as it is the natural
@@ -3121,7 +3270,8 @@
             return;
         }
 
-        assert isBegin();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(isBegin());
 
         //
         // Now, for interior types, I have to deal with xsi:type and
@@ -3137,7 +3287,8 @@
 
             disconnectTypes( r );
 
-            assert validate();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(validate());
 
             return;
         }
@@ -3173,7 +3324,8 @@
 
         disconnectTypes( r );
 
-        assert validate();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(validate());
     }
 
     /**
@@ -3183,7 +3335,8 @@
 
     final Type peekType ( )
     {
-        assert isTypeable();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(isTypeable());
 
         Type type = null;
 
@@ -3194,7 +3347,8 @@
                     return (Type) g;
         }
 
-        assert type != null || isValid();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(type != null || isValid());
 
         return type;
     }
@@ -3206,7 +3360,8 @@
 
     final Type getType ( Root r )
     {
-        assert isTypeable();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(isTypeable());
 
         Type type = peekType();
 
@@ -3214,7 +3369,8 @@
         {
             Type parentType = getContainer().getType( r );
 
-            assert parentType != null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(parentType != null);
 
             // Defensive
             if (parentType == null)
@@ -3230,12 +3386,14 @@
             }
             else
             {
-                assert isNormalAttr();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(isNormalAttr());
 
                 newUser = parentType.create_attribute_user( getName() );
             }
 
-            assert newUser != null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(newUser != null);
 
             // Defensive
             if (newUser == null)
@@ -3244,7 +3402,8 @@
             type = new Type( r, newUser, this );
         }
 
-        assert type != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(type != null);
 
         return type;
     }
@@ -3255,8 +3414,11 @@
 
     final boolean between ( Root r, int pThis, Splay sRange )
     {
-        assert Root.dv > 0 || getRootSlow() == r;
-        assert Root.dv > 0 || getRootSlow() == sRange.getRootSlow();
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(Root.dv > 0 || getRootSlow() == r);
+            XmlBeans.assertTrue(Root.dv > 0 || getRootSlow() == sRange.getRootSlow());
+        }
 
         if (sRange.isDoc())
             return true;
@@ -3267,7 +3429,8 @@
         Splay sEnd;
         int   pEnd;
 
-        assert !sRange.isDoc();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(!sRange.isDoc());
 
         if (sRange.isLeaf())
         {
@@ -3296,10 +3459,13 @@
     {
         Splay sThis = this;
 
-        assert Root.dv > 0 || sThis.getRootSlow() == r;
-        assert Root.dv > 0 || sThat.getRootSlow() == r;
-        assert pThis >= 0 && pThis <= sThis.getEndPos();
-        assert pThat >= 0 && pThat <= sThat.getEndPos();
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(Root.dv > 0 || sThis.getRootSlow() == r);
+            XmlBeans.assertTrue(Root.dv > 0 || sThat.getRootSlow() == r);
+            XmlBeans.assertTrue(pThis >= 0 && pThis <= sThis.getEndPos());
+            XmlBeans.assertTrue(pThat >= 0 && pThat <= sThat.getEndPos());
+        }
 
         // Normalize positions
 
@@ -3341,8 +3507,11 @@
             }
         }
 
-        assert pThis < sThis.getEndPos();
-        assert pThat < sThat.getEndPos();
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(pThis < sThis.getEndPos());
+            XmlBeans.assertTrue(pThat < sThat.getEndPos());
+        }
 
         if (sThis == sThat)
             return pThis < pThat ? -1 : pThis > pThat ? 1 : 0;
@@ -3361,7 +3530,8 @@
         }
         else if (sThat.isAttr())
         {
-            assert !sThis.isAttr();
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(!sThis.isAttr());
 
             if (sThat.prevNonAttrSplay() != sThis)
                 return compare( r, sThat );
@@ -3418,7 +3588,8 @@
         sThis.splay( r, r );
         sThat.splay( r, sThis );
 
-        assert sThis._leftSplay == sThat || sThis._rightSplay == sThat;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(sThis._leftSplay == sThat || sThis._rightSplay == sThat);
 
         return sThis._leftSplay == sThat ? 1 : -1;
     }
@@ -3481,12 +3652,14 @@
 
     final void rotateRight ( )
     {
-        assert _parentSplay._leftSplay == this;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(_parentSplay._leftSplay == this);
 
         Splay p = _parentSplay;
         Splay g = p._parentSplay;
 
-        assert p != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(p != null);
 
         p._leftSplay = _rightSplay;
 
@@ -3511,12 +3684,14 @@
 
     final void rotateLeft ( )
     {
-        assert _parentSplay._rightSplay == this;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(_parentSplay._rightSplay == this);
 
         Splay p = _parentSplay;
         Splay g = p._parentSplay;
 
-        assert p != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(p != null);
 
         p._rightSplay = _leftSplay;
 
@@ -3551,22 +3726,27 @@
 
     final void splay ( Root r, Splay pStop )
     {
-        assert pStop != null;
-        assert this != pStop;
-        assert Root.dv > 0 || r == null || getRootSlow() == r;
-        assert Root.dv > 0 || r == null || pStop.getRootSlow() == r;
-        assert r == null || r.validateSplayTree();
-        assert !isRoot();
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(pStop != null);
+            XmlBeans.assertTrue(this != pStop);
+            XmlBeans.assertTrue(Root.dv > 0 || r == null || getRootSlow() == r);
+            XmlBeans.assertTrue(Root.dv > 0 || r == null || pStop.getRootSlow() == r);
+            XmlBeans.assertTrue(r == null || r.validateSplayTree());
+            XmlBeans.assertTrue(!isRoot());
+        }
 
         boolean rotated = false;
 
         for ( ; ; )
         {
-            assert _parentSplay != null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(_parentSplay != null);
 
             Splay p = _parentSplay;
 
-            assert p != null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(p != null);
 
             // If this is a child of the stopper, then we are done
 
@@ -3614,7 +3794,8 @@
         if (rotated && r != null)
             r._leftOnly = false;
 
-        assert r == null || r.validateSplayTree();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(r == null || r.validateSplayTree());
     }
 
     /**
@@ -3626,12 +3807,14 @@
     {
         Root root = r.isRoot() ? (Root) r : null;
 
-        assert r._parentSplay == null;
-        assert root == null || root.validateSplayTree();
-        assert !isRoot();
-        assert !isDoc();
-        assert Root.dv > 0 || getSplayRootSlow() == r;
-
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(r._parentSplay == null);
+            XmlBeans.assertTrue(root == null || root.validateSplayTree());
+            XmlBeans.assertTrue(!isRoot());
+            XmlBeans.assertTrue(!isDoc());
+            XmlBeans.assertTrue(Root.dv > 0 || getSplayRootSlow() == r);
+        }
         // If the splay to be removed has no cch or cbegin, then when the
         // tree is left only children, we need not splay.
 
@@ -3640,8 +3823,11 @@
 
         if (root != null && root._leftOnly && cch == 0 && cbegin == 0)
         {
-            assert _rightSplay == null;
-            assert _parentSplay != null;
+            if (XmlBeans.ASSERTS)
+            {
+                XmlBeans.assertTrue(_rightSplay == null);
+                XmlBeans.assertTrue(_parentSplay != null);
+            }
 
             if ((_parentSplay._leftSplay = _leftSplay) != null)
                 _leftSplay._parentSplay = _parentSplay;
@@ -3664,7 +3850,8 @@
 
                 p.splay( root, this );
 
-                assert p._rightSplay == null;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(p._rightSplay == null);
 
                 r._leftSplay = p;
                 p._parentSplay = r;
@@ -3681,7 +3868,8 @@
         adjustCchLeft( - getCchLeft() );
         adjustCdocBeginLeft( - getCdocBeginLeft() );
 
-        assert root == null || root.validateSplayTree();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(root == null || root.validateSplayTree());
 
         return this;
     }
@@ -3773,7 +3961,8 @@
         Attr ( QName name, boolean isXmlns )
         {
             super( ATTR, true, name );
-            assert isXmlns;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(isXmlns);
         }
 
         Container getContainer ( )
@@ -3832,17 +4021,20 @@
 
         final void set ( Root r, Splay s, int p )
         {
-            assert s != null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(s != null);
             doSet( r, s, p );
         }
 
         private final void doSet ( Root r, Splay s, int p )
         {
-            assert s != null || p == 0;
-            assert Root.dv > 0 || s == null || r == s.getRootSlow();
-            assert Root.dv > 0 || _splay == null || _root == _splay.getRootSlow();
-//            assert Root.dv > 0 || _root == r || _splay.getRootSlow() != s.getRootSlow();
-
+            if (XmlBeans.ASSERTS)
+            {
+                XmlBeans.assertTrue(s != null || p == 0);
+                XmlBeans.assertTrue(Root.dv > 0 || s == null || r == s.getRootSlow());
+                XmlBeans.assertTrue(Root.dv > 0 || _splay == null || _root == _splay.getRootSlow());
+//                XmlBeans.assertTrue(Root.dv > 0 || _root == r || _splay.getRootSlow() != s.getRootSlow());
+            }
             _root = r;
 
             if (_splay != s)
@@ -3854,14 +4046,18 @@
                     append( s );
             }
 
-            assert p >= 0;
-            assert _splay == null || p <= _splay.getMaxPos();
+            if (XmlBeans.ASSERTS)
+            {
+                XmlBeans.assertTrue(p >= 0);
+                XmlBeans.assertTrue(_splay == null || p <= _splay.getMaxPos());
+            }
             _state = p * 8 + (_state & 7);
         }
 
         final void set ( Root r )
         {
-            assert r != null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue(r != null);
             _root = r;
         }
 
@@ -3884,11 +4080,14 @@
 
         private final void append ( Splay s )
         {
-            assert s != null;
-            assert Root.dv > 0 || s.getRootSlow() == _root;
-            assert _splay == null;
-            assert _parent == null;
-            assert _next == null && _prev == null;
+            if (XmlBeans.ASSERTS)
+            {
+                XmlBeans.assertTrue(s != null);
+                XmlBeans.assertTrue(Root.dv > 0 || s.getRootSlow() == _root);
+                XmlBeans.assertTrue(_splay == null);
+                XmlBeans.assertTrue(_parent == null);
+                XmlBeans.assertTrue(_next == null && _prev == null);
+            }
 
             if (s._goobers == null)
             {
@@ -3909,12 +4108,16 @@
 
         private final void remove ( )
         {
-            assert _splay != null;
-            assert _goobers == null;
+            if (XmlBeans.ASSERTS)
+            {
+                XmlBeans.assertTrue(_splay != null);
+                XmlBeans.assertTrue(_goobers == null);
+            }
 
             if (_next == this)
             {
-                assert _parent._goobers == this;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue(_parent._goobers == this);
 
                 _parent._goobers = null;
 
@@ -3923,7 +4126,8 @@
                 if (_parent != _splay)
                 {
                     Goober g = (Goober) _parent;
-                    assert g.getKind() == AGGREGATE;
+                    if (XmlBeans.ASSERTS)
+                        XmlBeans.assertTrue(g.getKind() == AGGREGATE);
                     g.remove();
                 }
             }
@@ -3983,7 +4187,8 @@
         {
             // Creepy way to discover is assert is enabled.
             HashMap map = null;
-            assert (map = new HashMap()) != null;
+            if (XmlBeans.ASSERTS)
+                XmlBeans.assertTrue((map = new HashMap()) != null);
             return map;
         }
 
@@ -4082,15 +4287,19 @@
         if (_goobers == null || _goobers.getKind() != AGGREGATE)
             return _goobers;
 
-        assert _goobers._goobers != null;
-        assert _goobers._goobers.getKind() != AGGREGATE;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue(_goobers._goobers != null);
+            XmlBeans.assertTrue(_goobers._goobers.getKind() != AGGREGATE);
+        }
 
         return _goobers._goobers;
     }
 
     final Goober nextGoober ( Goober g )
     {
-        assert g != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue(g != null);
 
         if ((g = g._next) != g._parent._goobers)
             return g;
@@ -4102,10 +4311,7 @@
 
     private static boolean getAssertEnabled ( )
     {
-        // Creepy way to discover is assert is enabled.
-        boolean enabled = false;
-        assert (enabled = true) || true;
-        return enabled;
+        return XmlBeans.ASSERTS;
     }
 
     static void assertAssertEnabled ( )
@@ -4179,7 +4385,7 @@
     {
         assertAssertEnabled();
 
-        assert Root.dv > 0 || getRootSlow() == sThat.getRootSlow();
+        XmlBeans.assertTrue(Root.dv > 0 || getRootSlow() == sThat.getRootSlow());
 
         if (this == sThat)
             return 0;
@@ -4192,7 +4398,7 @@
             if (s == sThat)
                 return 1;
 
-        assert false: "Yikes!";
+        XmlBeans.assertTrue(false, "Yikes!");
 
         return 0;
     }
diff --git a/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Text.java b/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Text.java
index c4744b2..d63f868 100644
--- a/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Text.java
+++ b/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Text.java
@@ -17,6 +17,8 @@
 
 //import org.apache.xmlbeans.impl.store.Root.WriteContext;
 //import org.apache.xmlbeans.impl.store.Root.ReadContext;
+import org.apache.xmlbeans.XmlBeans;
+
 import java.io.IOException;
 
 public final class Text
@@ -37,7 +39,8 @@
 
     private void copy ( char[] newBuf )
     {
-        assert _buf != null && newBuf.length >= length();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( _buf != null && newBuf.length >= length() );
         
         System.arraycopy( _buf, 0, newBuf, 0, _gap );
 
@@ -50,7 +53,8 @@
 
     void resize ( int cch )
     {
-        assert cch > _gapLen;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( cch > _gapLen );
         
         int newSize = length() + cch;
         int newLen = _buf == null ? 1024 : _buf.length * 2;
@@ -105,7 +109,8 @@
                 insert( pos, (Text) txt, off, cch );
             else
             {
-                assert txt instanceof char[];
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue( txt instanceof char[] );
                 insert( pos, (char[]) txt, off, cch );
             }
         }
@@ -149,9 +154,12 @@
     
     void insert ( int pos, char[] chars, int off, int cch )
     {
-        assert chars != _buf;
-        assert pos >= 0 && pos <= length();
-        
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue( chars != _buf );
+            XmlBeans.assertTrue( pos >= 0 && pos <= length() );
+        }
+
         if (cch > 0)
         {
             if (cch > _gapLen)
@@ -173,13 +181,17 @@
     
     void insert ( int pos, String s, int off, int cch )
     {
-        assert pos >= 0 && pos <= length();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( pos >= 0 && pos <= length() );
         
         if (cch > 0)
         {
-            assert off >= 0 && off < s.length();
-            assert cch <= s.length() - off;
-            
+            if (XmlBeans.ASSERTS)
+            {
+                XmlBeans.assertTrue( off >= 0 && off < s.length() );
+                XmlBeans.assertTrue( cch <= s.length() - off );
+            }
+
             if (cch > _gapLen)
                 resize( cch );
             
@@ -199,11 +211,13 @@
     
     void remove ( int pos, int cch, char[] retBuf, int off )
     {
-        assert pos >= 0 && pos + cch <= length();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( pos >= 0 && pos + cch <= length() );
 
         moveGap( pos );
 
-        assert retBuf == null || retBuf.length - off >= cch;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( retBuf == null || retBuf.length - off >= cch );
 
         if (cch > 0 && retBuf != null)
             System.arraycopy( _buf, _gap + _gapLen, retBuf, off, cch );
@@ -223,8 +237,11 @@
 
     int unObscure ( int pos, int cch )
     {
-        assert cch >= 0;
-        assert pos >= 0 && pos + cch <= length();
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue( cch >= 0 );
+            XmlBeans.assertTrue( pos >= 0 && pos + cch <= length() );
+        }
 
         if (cch > 0 && (pos < _gap && pos + cch > _gap))
             moveGap( pos + cch );
@@ -234,7 +251,8 @@
 
     void fetch ( StringBuffer sb, int pos, int cch )
     {
-        assert pos >= 0 && pos + cch <= length();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( pos >= 0 && pos + cch <= length() );
 
         if (cch == 0)
             return;
@@ -259,7 +277,8 @@
 
     String fetch ( int pos, int cch )
     {
-        assert pos >= 0 && pos + cch <= length();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( pos >= 0 && pos + cch <= length() );
 
         if (cch == 0)
             return "";
@@ -280,9 +299,12 @@
 
     void fetch ( char[] buf, int off, int pos, int cch )
     {
-        assert off >= 0;
-        assert pos >= 0 && pos + cch <= length();
-        assert buf.length - off >= cch;
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue( off >= 0 );
+            XmlBeans.assertTrue( pos >= 0 && pos + cch <= length() );
+            XmlBeans.assertTrue( buf.length - off >= cch );
+        }
 
         if (cch == 0)
             return;
diff --git a/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Type.java b/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Type.java
index 7535d7d..c438d2d 100644
--- a/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Type.java
+++ b/v1/src/xmlstore/org/apache/xmlbeans/impl/store/Type.java
@@ -34,6 +34,7 @@
 import org.apache.xmlbeans.XmlException;
 import org.apache.xmlbeans.XmlObject;
 import org.apache.xmlbeans.XmlOptions;
+import org.apache.xmlbeans.XmlBeans;
 import java.util.ArrayList;
 import java.util.List;
 import javax.xml.namespace.QName;
@@ -49,10 +50,13 @@
     {
         super( r, Splay.TYPE );
         
-        assert s.peekType() == null;
-        assert user != null;
-        assert s.isTypeable();
-        
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue( s.peekType() == null );
+            XmlBeans.assertTrue( user != null );
+            XmlBeans.assertTrue( s.isTypeable() );
+        }
+
         _user = user;
         
         set( s, 0 );
@@ -152,7 +156,8 @@
     
     void invalidateElement ( Container container, Splay s )
     {
-        assert s.getContainer() == container;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( s.getContainer() == container );
         
         if (_inhibitUserInvalidate > 0)
             return;
@@ -171,7 +176,8 @@
         {
             if (s.isFinish())
             {
-                assert s.getContainer() == container;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue( s.getContainer() == container );
                 return;
             }
 
@@ -203,12 +209,16 @@
     {
         Root r = getRoot();
         
-        assert s.isInvalid();
-        assert s.isLeaf() || s.isDoc();
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue( s.isInvalid() );
+            XmlBeans.assertTrue( s.isLeaf() || s.isDoc() );
+        }
 
         String text = build_text( nsm );
 
-        assert text != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( text != null );
 
         _inhibitUserInvalidate++;
 
@@ -230,12 +240,16 @@
     {
         Root r = getRoot();
         
-        assert s.isInvalid();
-        assert s.isNormalAttr();
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue( s.isInvalid() );
+            XmlBeans.assertTrue( s.isNormalAttr() );
+        }
 
         String text = build_text( nsm );
 
-        assert text != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( text != null );
 
         // Validating does not logically change the doc
         long oldVersion = r.getVersion();
@@ -289,7 +303,8 @@
     {
         Splay s = getSplay();
 
-        assert s.isContainer() || s.isNormalAttr();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( s.isContainer() || s.isNormalAttr() );
 
         if (s.isNormalAttr())
             return null;
@@ -305,7 +320,8 @@
 
         Type t = s.getType( getRoot() );
 
-        assert t != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( t != null );
         
         return t._user;
     }
@@ -314,7 +330,8 @@
     {
         Splay s = getSplay();
 
-        assert s.isTypeable();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( s.isTypeable() );
 
         if (s.isInvalid())
             return;
@@ -324,7 +341,8 @@
         s.removeContent( getRoot(), false );
 
         s.toggleIsInvalid();
-        assert s.isInvalid();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( s.isInvalid() );
         
         _inhibitUserInvalidate--;
     }
@@ -333,7 +351,8 @@
     {
         Splay s = getSplay();
 
-        assert !s.isInvalid();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( !s.isInvalid() );
         
         if (s.isInvalid())
             throw new RuntimeException( "Can't fetch text when invalid" );
@@ -352,7 +371,8 @@
     {
         Splay s = getSplay();
         
-        assert s.isTypeable();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( s.isTypeable() );
 
         if (s.isDoc())
             return 0;
@@ -361,7 +381,8 @@
 
         Type parentType = parentContainer.getType( getRoot() );
 
-        assert parentType != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( parentType != null );
 
         TypeStoreUser parentUser = parentType._user;
 
@@ -378,14 +399,16 @@
         if (visitor == null)
             return 0;
 
-        assert !parentContainer.isLeaf();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( !parentContainer.isLeaf() );
         
         for ( Splay t = parentContainer.nextSplay() ; ; t = t.nextSplay() )
         {
             switch ( t.getKind() )
             {
             case Splay.END :
-                assert false;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue( false );
                 break;
 
             case Splay.BEGIN :
@@ -405,7 +428,8 @@
     {
         Splay s = getSplay();
         
-        assert s.isTypeable();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( s.isTypeable() );
 
         if (s.isDoc())
             return null;
@@ -417,10 +441,12 @@
         if (s.isAttr())
             return parentUser.get_attribute_field( s.getName() );
 
-        assert s.isBegin();
+        if (XmlBeans.ASSERTS)
+        {
+            XmlBeans.assertTrue( s.isBegin() );
+            XmlBeans.assertTrue( !parentContainer.isLeaf() );
+        }
 
-        assert !parentContainer.isLeaf();
-        
         TypeStoreVisitor visitor = parentUser.new_visitor();
 
         if (visitor == null)
@@ -431,7 +457,8 @@
             switch ( t.getKind() )
             {
             case Splay.END :
-                assert false;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue( false );
                 break;
 
             case Splay.BEGIN :
@@ -461,7 +488,8 @@
     {
         Splay s = getSplay();
 
-        assert s.isContainer();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( s.isContainer() );
         
         if (!s.isContainer())
             throw new IllegalStateException();
@@ -473,7 +501,8 @@
 
         Type t = nthBegin.getType( getRoot() );
 
-        assert t != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( t != null );
         
         return t._user;
     }
@@ -481,20 +510,23 @@
     public TypeStoreUser find_element_user ( QNameSet names, int i )
     {
         Splay s = getSplay();
-        assert s.isContainer();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( s.isContainer() );
 
         Begin nthBegin = getRoot().findNthBegin(s,  null, names, i);
         if (nthBegin == null) return null;
 
         Type t = nthBegin.getType(getRoot());
-        assert t != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( t != null );
 
         return t._user;
     }
     
     private void findAllElementTypes ( QName name, QNameSet set, List fillMeUp )
     {
-        assert getSplay().isContainer();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( getSplay().isContainer() );
 
         Splay s = getSplay();
 
@@ -519,7 +551,8 @@
                     {
                         Type type = s.getType( getRoot() );
 
-                        assert type != null;
+                        if (XmlBeans.ASSERTS)
+                            XmlBeans.assertTrue( type != null );
                     
                         fillMeUp.add( type );
                     }
@@ -529,7 +562,8 @@
                     if (set.contains(s.getName()))
                     {
                         Type type = s.getType(getRoot());
-                        assert type != null;
+                        if (XmlBeans.ASSERTS)
+                            XmlBeans.assertTrue( type != null );
                         fillMeUp.add(type);
                     }
                 }
@@ -562,7 +596,8 @@
 
     public TypeStoreUser find_attribute_user ( QName name )
     {
-        assert getSplay().isContainer();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( getSplay().isContainer() );
 
         Splay a = getSplay().getAttr( name );
 
@@ -571,7 +606,8 @@
 
         Type t = a.getType( getRoot() );
 
-        assert t != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( t != null );
 
         return t._user;
     }
@@ -580,7 +616,8 @@
     {
         Splay s = getSplay();
         
-        assert s.isTypeable();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( s.isTypeable() );
 
         if (s.isDoc())
             return null;
@@ -589,7 +626,8 @@
 
         Type parentType = parentContainer.getType( getRoot() );
 
-        assert parentType != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( parentType != null );
 
         TypeStoreUser parentUser = parentType._user;
 
@@ -606,14 +644,16 @@
         if (visitor == null)
             return null;
 
-        assert !parentContainer.isLeaf();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( !parentContainer.isLeaf() );
         
         for ( Splay t = parentContainer.nextSplay() ; ; t = t.nextSplay() )
         {
             switch ( t.getKind() )
             {
             case Splay.END :
-                assert false;
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue( false );
                 break;
 
             case Splay.BEGIN :
@@ -633,7 +673,8 @@
     {
         Splay s = getSplay();
 
-        assert s.isTypeable();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( s.isTypeable() );
 
         if (!s.isAttr())
             s.setXsiNil( getRoot(), build_nil() );
@@ -643,7 +684,8 @@
     {
         Splay s = getSplay();
 
-        assert s.isTypeable();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( s.isTypeable() );
   
         return s.isAttr() ? false : s.getXsiNil( getRoot() );
     }
@@ -658,7 +700,8 @@
 
         String result = s.prefixForNamespace( getRoot(), nsuri, suggested_prefix, true);
 
-        assert result != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( result != null );
 
         return result;
     }
@@ -677,7 +720,8 @@
     {
         Splay s = getSplay();
 
-        assert s.isContainer();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( s.isContainer() );
         
         if (!s.isContainer())
             throw new IllegalStateException();
@@ -705,7 +749,8 @@
     {
         Splay s = getSplay();
 
-        assert s.isContainer();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( s.isContainer() );
 
         if (!s.isContainer())
             throw new IllegalStateException();
@@ -734,7 +779,8 @@
     {
         Splay s = getSplay();
 
-        assert s.isContainer();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( s.isContainer() );
         
         if (!s.isContainer())
             throw new IllegalStateException();
@@ -774,7 +820,8 @@
                     }
                 }
 
-                assert t.isContainer();
+                if (XmlBeans.ASSERTS)
+                    XmlBeans.assertTrue( t.isContainer() );
 
                 if (t.getName().equals( qname ))
                     break;
@@ -801,7 +848,8 @@
         
         Type t = b.getType( r );
 
-        assert t != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( t != null );
         
         return t._user;
     }
@@ -813,7 +861,8 @@
         
         Splay s = getSplay();
 
-        assert s.isContainer();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( s.isContainer() );
         
         if (!s.isContainer())
             throw new IllegalStateException();
@@ -836,7 +885,8 @@
 
         Splay s = getSplay();
 
-        assert s.isContainer();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( s.isContainer() );
 
         if (!s.isContainer())
             throw new IllegalStateException();
@@ -857,7 +907,8 @@
     {
         Splay s = getSplay();
 
-        assert s.isContainer();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( s.isContainer() );
         
         if (!s.isContainer())
             throw new IllegalStateException();
@@ -872,7 +923,8 @@
         
         Type t = a.getType( getRoot() );
 
-        assert t != null;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( t != null );
 
         return t._user;
     }
@@ -881,7 +933,8 @@
     {
         Splay s = getSplay();
 
-        assert s.isContainer();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( s.isContainer() );
         
         if (!s.isContainer())
             throw new IllegalStateException();
@@ -896,7 +949,8 @@
     
     public TypeStoreUser copy_contents_from ( TypeStore source )
     {
-        assert source instanceof Type;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( source instanceof Type );
 
         Type sourceType = (Type) source;
 
@@ -946,7 +1000,8 @@
         for ( ; m > n ; n++ )
             add_element_user( elementName );
 
-        assert m == n;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( m == n );
         
         ArrayList elements = new ArrayList();
         
@@ -954,7 +1009,8 @@
 
         Root r = getRoot();
         
-        assert elements.size() == n;
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( elements.size() == n );
 
         for ( int i = 0 ; i < n ; i++ )
         {
@@ -966,10 +1022,12 @@
             {
                 Splay s = type.getSplay();
 
-                assert r == type.getRoot();
+                if (XmlBeans.ASSERTS)
+                {
+                    XmlBeans.assertTrue( r == type.getRoot() );
+                    XmlBeans.assertTrue( s.isContainer() );
+                }
 
-                assert s.isContainer();
-                
                 s.removeContent( r, true );
                 
                 CopyContext copyContext = (CopyContext) copies.get( i );
@@ -993,7 +1051,8 @@
     {
        Splay s = getSplay();
 
-        assert s.isContainer();
+        if (XmlBeans.ASSERTS)
+            XmlBeans.assertTrue( s.isContainer() );
         
         if (!s.isContainer())
             throw new IllegalStateException();
diff --git a/v1/src/xmlstore/org/apache/xmlbeans/impl/store/XmlObjectList.java b/v1/src/xmlstore/org/apache/xmlbeans/impl/store/XmlObjectList.java
index f322326..38dff85 100644
--- a/v1/src/xmlstore/org/apache/xmlbeans/impl/store/XmlObjectList.java
+++ b/v1/src/xmlstore/org/apache/xmlbeans/impl/store/XmlObjectList.java
@@ -18,6 +18,7 @@
 // BUGBUG: ***TLL*** Why isn't this exposed in org.apache.xmlbeans????
 
 import org.apache.xmlbeans.XmlObject;
+import org.apache.xmlbeans.XmlRuntimeException;
 import java.util.Iterator;
 
 
@@ -112,7 +113,7 @@
             try {
                 CLASS = Class.forName("com.bea.wli.variables.XmlObjectListImpl");
             } catch (Throwable t) {
-                IllegalStateException ise = new IllegalStateException("Cannot load XmlObjectListImpl.");
+                XmlRuntimeException ise = new XmlRuntimeException("Cannot load XmlObjectListImpl.");
                 ise.initCause(t);
                 throw ise;
             }
@@ -128,9 +129,9 @@
             try {
                 return (XmlObjectList)CLASS.newInstance();
             } catch (InstantiationException ie) {
-                throw new RuntimeException(ie);
+                throw new XmlRuntimeException(ie);
             } catch (IllegalAccessException iae) {
-                throw new RuntimeException(iae);
+                throw new XmlRuntimeException(iae);
             }
         }
 
@@ -147,9 +148,9 @@
                 newList.addAll(list);
                 return newList;
             } catch (InstantiationException ie) {
-                throw new RuntimeException(ie);
+                throw new XmlRuntimeException(ie);
             } catch (IllegalAccessException iae) {
-                throw new RuntimeException(iae);
+                throw new XmlRuntimeException(iae);
             }
         }
 
@@ -165,9 +166,9 @@
                 newList.addAll(xmlObjects);
                 return newList;
             } catch (InstantiationException ie) {
-                throw new RuntimeException(ie);
+                throw new XmlRuntimeException(ie);
             } catch (IllegalAccessException iae) {
-                throw new RuntimeException(iae);
+                throw new XmlRuntimeException(iae);
             }
         }
     }
diff --git a/v1/src/xmlstore/org/apache/xmlbeans/impl/store/XqrlDelegate.java b/v1/src/xmlstore/org/apache/xmlbeans/impl/store/XqrlDelegate.java
index f51f32f..3c8935b 100644
--- a/v1/src/xmlstore/org/apache/xmlbeans/impl/store/XqrlDelegate.java
+++ b/v1/src/xmlstore/org/apache/xmlbeans/impl/store/XqrlDelegate.java
@@ -17,8 +17,9 @@
 
 import java.lang.reflect.Method;
 import org.apache.xmlbeans.XmlOptions;
+import org.apache.xmlbeans.XmlRuntimeException;
 
-public final class XqrlDelegate 
+public final class XqrlDelegate
 {
     private XqrlDelegate ( )
     {
@@ -54,11 +55,7 @@
         if (e instanceof RuntimeException)
             throw (RuntimeException) e;
         
-        Throwable cause = e.getCause();
-        
-        RuntimeException rte = new RuntimeException( cause.getMessage() );
-        
-        rte.initCause( cause );
+        XmlRuntimeException rte = new XmlRuntimeException( e.toString(), e );
 
         throw rte;
     }
@@ -124,7 +121,7 @@
             }
             catch ( Exception e )
             {
-                throw new RuntimeException( e );
+                throw new XmlRuntimeException( e );
             }
         }
     }
diff --git a/v1/src/xpath/org/apache/xmlbeans/impl/xpath/jaxen/XBeansXPathAdv.java b/v1/src/xpath/org/apache/xmlbeans/impl/xpath/jaxen/XBeansXPathAdv.java
index 608b619..c940a48 100644
--- a/v1/src/xpath/org/apache/xmlbeans/impl/xpath/jaxen/XBeansXPathAdv.java
+++ b/v1/src/xpath/org/apache/xmlbeans/impl/xpath/jaxen/XBeansXPathAdv.java
@@ -18,6 +18,7 @@
 import org.jaxen.BaseXPath;
 import org.jaxen.JaxenException;
 import org.apache.xmlbeans.XmlCursor;
+import org.apache.xmlbeans.XmlRuntimeException;
 import org.apache.xmlbeans.impl.store.JaxenXBeansDelegate;
 
 import java.util.List;
@@ -84,7 +85,7 @@
         }
         catch (JaxenException e)
         {
-            throw new RuntimeException(e);
+            throw new XmlRuntimeException(e);
         }
     }
 }
diff --git a/v1/src/zipcompare/zipcompare/ZipCompare.java b/v1/src/zipcompare/zipcompare/ZipCompare.java
index 27f902b..be22189 100644
--- a/v1/src/zipcompare/zipcompare/ZipCompare.java
+++ b/v1/src/zipcompare/zipcompare/ZipCompare.java
@@ -15,6 +15,8 @@
 
 package zipcompare;
 
+import org.apache.xmlbeans.impl.common.SequencedHashSet;
+
 import java.util.zip.ZipFile;
 import java.util.zip.ZipEntry;
 import java.util.*;
@@ -41,11 +43,11 @@
 
         System.out.println("Comparing " + args[0] + " with " + args[1] + ":");
 
-        Set set1 = new LinkedHashSet();
+        Set set1 = new SequencedHashSet();
         for (Enumeration e = file1.entries(); e.hasMoreElements(); )
             set1.add(((ZipEntry)e.nextElement()).getName());
 
-        Set set2 = new LinkedHashSet();
+        Set set2 = new SequencedHashSet();
         for (Enumeration e = file2.entries(); e.hasMoreElements(); )
             set2.add(((ZipEntry)e.nextElement()).getName());
 
diff --git a/v1/test/src/drt/drtcases/GDateTests.java b/v1/test/src/drt/drtcases/GDateTests.java
index 92d4210..95fa88b 100644
--- a/v1/test/src/drt/drtcases/GDateTests.java
+++ b/v1/test/src/drt/drtcases/GDateTests.java
@@ -271,14 +271,14 @@
         Assert.assertEquals(gdd, gcd);
         
         // set up 2/29, and read out Feb 29 in the year 1 BC.
-        Calendar gregcal = new GDate("--02-29").getCalendar();
-        Assert.assertEquals(29, gregcal.get(Calendar.DAY_OF_MONTH));
-        Assert.assertEquals(2 - 1, gregcal.get(Calendar.MONTH));
-        Assert.assertEquals(1, gregcal.get(Calendar.YEAR));
-        Assert.assertEquals(0, gregcal.get(Calendar.ERA));
+        XmlCalendar gregcal = new GDate("--02-29").getCalendar();
+        Assert.assertEquals(29, gregcal.peek(Calendar.DAY_OF_MONTH));
+        Assert.assertEquals(2 - 1, gregcal.peek(Calendar.MONTH));
+        Assert.assertEquals(1, gregcal.peek(Calendar.YEAR));
+        Assert.assertEquals(0, gregcal.peek(Calendar.ERA));
         // repeat some tests to make sure it's stable.
-        Assert.assertEquals(29, gregcal.get(Calendar.DAY_OF_MONTH));
-        Assert.assertEquals(2 - 1, gregcal.get(Calendar.MONTH));
+        Assert.assertEquals(29, gregcal.peek(Calendar.DAY_OF_MONTH));
+        Assert.assertEquals(2 - 1, gregcal.peek(Calendar.MONTH));
 
         // now try some setters
         gregcal = new GDate("--02-29").getCalendar();
diff --git a/v1/test/src/drt/drtcases/JaxenXPathTests.java b/v1/test/src/drt/drtcases/JaxenXPathTests.java
index 6bbc295..21e33cc 100644
--- a/v1/test/src/drt/drtcases/JaxenXPathTests.java
+++ b/v1/test/src/drt/drtcases/JaxenXPathTests.java
@@ -22,6 +22,7 @@
 import org.apache.xmlbeans.XmlObject;
 import org.apache.xmlbeans.XmlCursor;
 import org.apache.xmlbeans.XmlException;
+import org.apache.xmlbeans.XmlRuntimeException;
 import java.io.FileNotFoundException;
 import java.io.FileWriter;
 import java.io.IOException;
@@ -84,7 +85,7 @@
         }
         catch (Exception e)
         {
-            throw new RuntimeException(e);
+            throw new XmlRuntimeException(e);
         }
     }
 
@@ -159,11 +160,11 @@
         }
         catch (XmlException e)
         {
-            throw new RuntimeException(e);
+            throw new XmlRuntimeException(e);
         }
         catch (IOException e)
         {
-            throw new RuntimeException(e);
+            throw new XmlRuntimeException(e);
         }
     }
 
@@ -182,11 +183,11 @@
         }
         catch (FileNotFoundException e)
         {
-            throw new RuntimeException(e);
+            throw new XmlRuntimeException(e);
         }
         catch (IOException e)
         {
-            throw new RuntimeException(e);
+            throw new XmlRuntimeException(e);
         }
     }
 }
diff --git a/v1/test/src/drt/drtcases/StoreTests.java b/v1/test/src/drt/drtcases/StoreTests.java
index 9c8d6a8..52c1ef4 100644
--- a/v1/test/src/drt/drtcases/StoreTests.java
+++ b/v1/test/src/drt/drtcases/StoreTests.java
@@ -24,6 +24,7 @@
 import org.apache.xmlbeans.XmlObject;
 import org.apache.xmlbeans.XmlOptions;
 import org.apache.xmlbeans.impl.common.XmlNameImpl;
+import org.apache.xmlbeans.impl.common.SequencedHashMap;
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.OutputStream;
@@ -837,8 +838,6 @@
     {
         try
         {
-            assert false;
-
             Assert.assertTrue( false );
         }
         catch ( Throwable e )
@@ -2552,7 +2551,7 @@
     {
         String xml = "<a xmlns:a='aNS'><a:b/></a>";
 
-        Map map = new java.util.LinkedHashMap();
+        Map map = new SequencedHashMap();
         map.put("b", "bNS");
         map.put("c", "cNS");
         map.put("a", "not-aNS");
@@ -2568,7 +2567,7 @@
 
         xml = "<a xmlns='aNS'><b/></a>";
 
-        map = new java.util.LinkedHashMap();
+        map = new SequencedHashMap();
         map.put("b", "bNS");
         map.put("c", "cNS");
         map.put("", "not-aNS");
diff --git a/v1/test/src/drt/drtcases/TestRunUtil.java b/v1/test/src/drt/drtcases/TestRunUtil.java
index cacf738..3d3e3a0 100644
--- a/v1/test/src/drt/drtcases/TestRunUtil.java
+++ b/v1/test/src/drt/drtcases/TestRunUtil.java
@@ -78,7 +78,7 @@
         }
         catch (InvocationTargetException e)
         {
-            throw e.getCause();
+            throw e.getTargetException();
         }
         finally
         {
diff --git a/v1/test/src/erictest/EricTest.java b/v1/test/src/erictest/EricTest.java
index c2d78a7..72ccadb 100644
--- a/v1/test/src/erictest/EricTest.java
+++ b/v1/test/src/erictest/EricTest.java
@@ -58,7 +58,6 @@
 import java.lang.reflect.Field;
 import java.math.BigDecimal;
 import java.math.BigInteger;
-import java.net.URI;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Date;
diff --git a/v1/test/src/extensionsuse/drtcases/FixedAttrTest.java b/v1/test/src/extensionsuse/drtcases/FixedAttrTest.java
index 6f1fe5a..136c552 100644
--- a/v1/test/src/extensionsuse/drtcases/FixedAttrTest.java
+++ b/v1/test/src/extensionsuse/drtcases/FixedAttrTest.java
@@ -52,7 +52,7 @@
         int pos = sb.length();
         sb.append("</pur:items></pur:purchaseOrder>");
 
-        String sExpected = sb.subSequence(0, pos) + sbContent.toString() + sb.subSequence(pos, sb.length());
+        String sExpected = sb.substring(0, pos) + sbContent.toString() + sb.substring(pos, sb.length());
 
         assertEquals(sExpected, poDoc.xmlText());
 
diff --git a/v1/test/src/extensionsuse/drtcases/MultInterfacesTest.java b/v1/test/src/extensionsuse/drtcases/MultInterfacesTest.java
index 674834d..fa7ab23 100644
--- a/v1/test/src/extensionsuse/drtcases/MultInterfacesTest.java
+++ b/v1/test/src/extensionsuse/drtcases/MultInterfacesTest.java
@@ -55,7 +55,7 @@
         int pos = sb.length();
         sb.append("</pur:items></pur:purchaseOrder>");
 
-        String sExpected = sb.subSequence(0, pos) + sbContent.toString() + sb.subSequence(pos, sb.length());
+        String sExpected = sb.substring(0, pos) + sbContent.toString() + sb.substring(pos, sb.length());
         assertEquals(sExpected, poDoc.xmlText());
 
 
@@ -70,7 +70,7 @@
                 sbContent.append("<pur:item><pur:USPrice>" + price + "</pur:USPrice></pur:item>");
             else
                 sbContent.append("<pur:item><pur:USPrice>" + i + "</pur:USPrice></pur:item>");
-        sExpected = sb.subSequence(0, pos) + sbContent.toString() + sb.subSequence(pos, sb.length());
+        sExpected = sb.substring(0, pos) + sbContent.toString() + sb.substring(pos, sb.length());
         assertEquals(sExpected, poDoc.xmlText());
 
         assertEquals(price, poDoc.getMinPrice());
diff --git a/v1/xkit/README.txt b/v1/xkit/README.txt
index 20236ae..699bd86 100644
--- a/v1/xkit/README.txt
+++ b/v1/xkit/README.txt
@@ -1,4 +1,4 @@
-XMLBeans v 1.0.3 Development Kit
+XMLBeans v 1.0.3 Development Kit (jdk1.3 port)
 
 
 Welcome to XMLBeans!