diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..b5ccd235bbb18ec0364c61ee2eada886397d2c5e
--- /dev/null
+++ b/.pre-commit-config.yaml
@@ -0,0 +1,10 @@
+- repo: https://github.com/pre-commit/pre-commit-hooks
+  sha: v0.6.1
+  hooks:
+      - id: check-added-large-files
+      - id: check-ast
+      - id: check-merge-conflict
+      - id: check-case-conflict 
+      - id: check-docstring-first
+      - id: debug-statements
+
diff --git a/.travis.yml b/.travis.yml
index 8c33e46ff8823ade37439662f18135dd2bdc0182..a88c1f75306724a1614f40053e866de64a8e330c 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,18 +1,16 @@
-sudo: required
-dist: trusty
 language: cpp
+dist: trusty
+sudo: required 
 compiler:
     - gcc
     - clang
 os:
     - linux
+    - osx
 notifications:
     email:
         recipients:
             - dilawar.s.rajput@gmail.com
-            - bhalla@ncbs.res.in
-            - hrani@ncbs.res.in
-            - ray.subhasis@gmail.com
         on_success: change
         on_failure: always
 
@@ -21,45 +19,17 @@ env:
 cache: apt
 
 matrix:
-    allow_failures:
-        - clang
-
-before_script:
-    - sudo apt-get install -qq libxml2-dev libbz2-dev
-    - sudo apt-get install -qq libhdf5-serial-dev
-    - sudo apt-get install -qq make cmake
-    - sudo apt-get install -qq  python-numpy python-matplotlib python-networkx
-    - sudo apt-get install -qq  python3-numpy python3-matplotlib python3-dev
-    - sudo apt-get install -qq libboost-all-dev
-    - sudo apt-get install -qq libgsl0-dev
-    - sudo apt-get install -qq python-pip python3-pip
-    - sudo apt-get install -qq libgraphviz-dev
-    - sudo pip install python-libsbml
-    - sudo pip3 install python-libsbml
-    - sudo pip3 install pygraphviz
-
-install:
-    - echo "nothing to do here"
+    allow_failure:
+        os: osx
+        
+before_script : 
+    - echo "OSX related"
+    - if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then ./.travis/travis_prepare_osx.sh; fi
+    - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then sudo ./.travis/travis_prepare_linux.sh; fi
 
 script:
-    - First check no python3 incompatible file.
-    - python3 -m compileall -q .
-    - # Then run the old make scripts
-    - make 
-    - ## CMAKE based flow
-    - mkdir -p _GSL_BUILD && cd _GSL_BUILD && cmake -DDEBUG=ON -DPYTHON_EXECUTABLE=/usr/bin/python ..
-    - make && ctest --output-on-failure
-    - cd .. # Now with boost.
-    - mkdir -p _BOOST_BUILD && cd _BOOST_BUILD && cmake -DWITH_BOOST=ON -DDEBUG=ON -DPYTHON_EXECUTABLE=/usr/bin/python ..
-    - make && ctest --output-on-failure
-    - cd .. 
-    - echo "Python3 support. Removed python2-networkx and install python3"
-    - sudo apt-get remove -qq python-networkx
-    - sudo apt-get install -qq python3-networkx
-    - mkdir -p _GSL_BUILD2 && cd _GSL_BUILD2 && cmake -DDEBUG=ON -DPYTHON_EXECUTABLE=/usr/bin/python3 ..
-    - make && ctest --output-on-failure
-    - cd .. # Now with BOOST and python3
-    - mkdir -p _BOOST_BUILD2 && cd _BOOST_BUILD2 && cmake -DWITH_BOOST=ON -DDEBUG=ON -DPYTHON_EXECUTABLE=/usr/bin/python3 ..
-    - make && ctest --output-on-failure
-    - cd ..
-    - echo "All done. Phew"
+    - # checking if any python3 incompatible file is in the source tree.
+    - python2 -m compileall -q .
+    - if type python3 -c 'import sys' > /dev/null; then python3 -m compileall -q . ; fi
+    - if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then ./.travis/travis_build_osx.sh; fi
+    - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then ./.travis/travis_build_linux.sh; fi
diff --git a/.travis/travis_build_linux.sh b/.travis/travis_build_linux.sh
new file mode 100755
index 0000000000000000000000000000000000000000..302dd129a703d0eeb221c4153b754f6556693275
--- /dev/null
+++ b/.travis/travis_build_linux.sh
@@ -0,0 +1,63 @@
+#!/bin/bash - 
+#===============================================================================
+#
+#          FILE: travis_build_linux.sh
+# 
+#         USAGE: ./travis_build_linux.sh 
+# 
+#   DESCRIPTION:  Build  on linux environment.
+# 
+#       OPTIONS: ---
+#  REQUIREMENTS: ---
+#          BUGS: ---
+#         NOTES: ---
+#        AUTHOR: Dilawar Singh (), dilawars@ncbs.res.in
+#  ORGANIZATION: NCBS Bangalore
+#       CREATED: 01/02/2017 10:11:46 AM
+#      REVISION:  ---
+#===============================================================================
+
+set -o nounset                              # Treat unset variables as an error
+set -e
+
+PYTHON2="/usr/bin/python2"
+PYTHON3="/usr/bin/python3"
+#MAKEFLAGS="-j 4"
+
+# Bug: `which python` returns /opt/bin/python* etc on travis. For which numpy
+# many not be available. Therefore, it is neccessary to use fixed path for
+# python executable.
+
+(
+    # Old makefile based flow.
+    python2 -m compileall -q .
+    if type python3 -c 'import sys' > /dev/null; then python3 -m compileall -q . ; fi
+    # Traditional make.
+    make 
+    ## CMAKE based flow
+    mkdir -p _GSL_BUILD && cd _GSL_BUILD && \
+        cmake -DDEBUG=ON -DPYTHON_EXECUTABLE="$PYTHON2" ..
+    make && ctest --output-on-failure
+    cd .. # Now with boost.
+    mkdir -p _BOOST_BUILD && cd _BOOST_BUILD && \
+        cmake -DWITH_BOOST=ON -DDEBUG=ON -DPYTHON_EXECUTABLE="$PYTHON2" ..
+    make && ctest --output-on-failure
+    cd .. 
+
+    # This is only applicable on linux build.
+    echo "Python3 support. Removed python2-networkx and install python3" 
+    if type $PYTHON3 -c 'import os' > /dev/null; then 
+        sudo apt-get remove -qq python-networkx 
+        sudo apt-get install -qq python3-networkx
+        mkdir -p _GSL_BUILD2 && cd _GSL_BUILD2 && \
+            cmake -DDEBUG=ON -DPYTHON_EXECUTABLE="$PYTHON3" ..
+        make && ctest --output-on-failure
+        cd .. # Now with BOOST and python3
+        mkdir -p _BOOST_BUILD2 && cd _BOOST_BUILD2 && \
+            cmake -DWITH_BOOST=ON -DDEBUG=ON -DPYTHON_EXECUTABLE="$PYTHON3" ..
+        make && ctest --output-on-failure
+        cd .. && echo "All done"
+    else
+        echo "Python3 is not found. Build disabled"
+    fi
+)
diff --git a/.travis/travis_build_osx.sh b/.travis/travis_build_osx.sh
new file mode 100755
index 0000000000000000000000000000000000000000..3235bcc157906e9fdffc465420608cf90db32cfe
--- /dev/null
+++ b/.travis/travis_build_osx.sh
@@ -0,0 +1,30 @@
+#!/bin/bash - 
+#===============================================================================
+#
+#          FILE: travis_build_linux.sh
+# 
+#         USAGE: ./travis_build_linux.sh 
+# 
+#   DESCRIPTION:  Build  on linux environment.
+# 
+#       OPTIONS: ---
+#  REQUIREMENTS: ---
+#          BUGS: ---
+#         NOTES: ---
+#        AUTHOR: Dilawar Singh (), dilawars@ncbs.res.in
+#  ORGANIZATION: NCBS Bangalore
+#       CREATED: 01/02/2017 10:11:46 AM
+#      REVISION:  ---
+#===============================================================================
+
+set -o nounset                              # Treat unset variables as an error
+set -e
+
+(
+    mkdir -p _GSL_BUILD && cd _GSL_BUILD && cmake -DDEBUG=ON -DPYTHON_EXECUTABLE=`which python` ..
+    make && ctest --output-on-failure
+    cd .. # Now with boost.
+    mkdir -p _BOOST_BUILD && cd _BOOST_BUILD && cmake -DWITH_BOOST=ON -DDEBUG=ON -DPYTHON_EXECUTABLE=`which python` ..
+    make && ctest --output-on-failure
+    cd .. 
+)
diff --git a/.travis/travis_prepare_linux.sh b/.travis/travis_prepare_linux.sh
new file mode 100755
index 0000000000000000000000000000000000000000..ce068f9bf2fc2497ef2ca738a468e1acffb46541
--- /dev/null
+++ b/.travis/travis_prepare_linux.sh
@@ -0,0 +1,31 @@
+#!/bin/bash - 
+#===============================================================================
+#
+#          FILE: travis_prepare_linux.sh
+# 
+#         USAGE: ./travis_prepare_linux.sh 
+# 
+#   DESCRIPTION:  Prepare linux build environment on travis.
+# 
+#       OPTIONS: ---
+#  REQUIREMENTS: ---
+#          BUGS: ---
+#         NOTES: ---
+#        AUTHOR: Dilawar Singh (), dilawars@ncbs.res.in
+#  ORGANIZATION: NCBS Bangalore
+#       CREATED: 01/02/2017 10:10:02 AM
+#      REVISION:  ---
+#===============================================================================
+
+set -o nounset                              # Treat unset variables as an error
+set +e  # Let installation fail in some command 
+
+apt-get install -qq libxml2-dev libbz2-dev
+apt-get install -qq libhdf5-serial-dev
+apt-get install -qq make cmake
+apt-get install -qq python-numpy python-matplotlib python-networkx
+apt-get install -qq python3-numpy python3-matplotlib python3-dev
+apt-get install -qq libboost-all-dev
+apt-get install -qq libgsl0-dev
+apt-get install -qq python-pip python3-pip
+apt-get install -qq libgraphviz-dev
diff --git a/.travis/travis_prepare_osx.sh b/.travis/travis_prepare_osx.sh
new file mode 100755
index 0000000000000000000000000000000000000000..28b3b6668e17c480c8a0d88f5bb22d32ebccd152
--- /dev/null
+++ b/.travis/travis_prepare_osx.sh
@@ -0,0 +1,34 @@
+#!/bin/bash - 
+#===============================================================================
+#
+#          FILE: travis_prepare_osx.sh
+# 
+#         USAGE: ./travis_prepare_osx.sh 
+# 
+#   DESCRIPTION: Script to prepare OSX build on Travis CI.
+# 
+#       OPTIONS: ---
+#  REQUIREMENTS: ---
+#          BUGS: ---
+#         NOTES: ---
+#        AUTHOR: Dilawar Singh (), dilawars@ncbs.res.in
+#  ORGANIZATION: NCBS Bangalore
+#       CREATED: 01/02/2017 10:09:00 AM
+#      REVISION:  ---
+#===============================================================================
+
+set -o nounset                              # Treat unset variables as an error
+set +e
+brew update
+#brew outdated cmake || brew install cmake
+brew install gsl
+brew outdated hdf5 || brew install homebrew/science/hdf5
+brew outdated libsbml || brew install homebrew/science/libsbml
+#brew outdated python || brew install python
+#brew outdated numpy || brew install homebrew/python/numpy
+#brew unlink numpy && brew link numpy || echo "Failed to link numpy"
+# Numpy caveats
+mkdir -p $HOME/Library/Python/2.7/lib/python/site-packages
+echo 'import sys; sys.path.insert(1, "/usr/local/lib/python2.7/site-packages")' >> $HOME/Library/Python/2.7/lib/python/site-packages/homebrew.pth
+pip install matplotlib
+
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 1be4010205191f76caaa704a2d46aaf7a248f170..75f76d730606f8cd08def2978b756bbf77d04c9f 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -33,7 +33,7 @@ elseif( (NOT MOOSE_VERSION) AND (NOT GIT_EXEC) )
     message(STATUS "+ Reading ${VERSION_FILE}" )
     file(READ ${VERSION_FILE} GIT_VERSION_OUTPUT )
 elseif(MOOSE_VERSION)
-    message(STATUS "+ Using user VERSION ${MOOSE_VERSION}" )
+    message(STATUS "+ Using user specified VERSION = ${MOOSE_VERSION}" )
     file(WRITE ${VERSION_FILE} ${MOOSE_VERSION})
 else()
     message(FATAL_ERROR "Could not determine MOOSE_VERSION" )
@@ -118,7 +118,7 @@ elseif(ENABLE_UNIT_TESTS)
 else()
     message(STATUS "Building for Release/No unit tests.")
     set(CMAKE_BUILD_TYPE Release)
-    add_definitions(-UDO_UNIT_TESTS -O3)
+    add_definitions(-UDO_UNIT_TESTS -DQUIET_MODE -O3)
 endif()
 
 if(GPROF AND DEBUG)
@@ -127,17 +127,6 @@ if(GPROF AND DEBUG)
     set(CMAKE_EXE_LINKER_FLAGS_DEBUG "-pg")
 endif()
 
-IF(NOTIFY_PROGRESS)
-    IF(COMPILER_SUPPORTS_CXX11 OR COMPILER_SUPPORTS_CXX0X)
-        MESSAGE(STATUS "MOOSE will occasionally write to __moose__progress__ file "
-            " status of simulation (done time/total time)"
-            )
-    ELSE()
-        MESSAGE(FATAL_ERROR "No c++11 or c++0x support in compiler."
-            "You can not use -DNOTIFY_PROGRESS=ON without it"
-            )
-    ENDIF()
-ENDIF()
 ################################### TARGETS ####################################
 
 add_library(libmoose SHARED basecode/main.cpp)
@@ -176,7 +165,7 @@ if(WITH_GSL)
             " Or build and install gsl from source code \n"
             "     https://www.gnu.org/software/gsl/ \n"
             " After installing gsl, rerun cmake.\n\n"
-            " If you install gsl in non-standard place, set the GSL_HOME environment \n"
+            " If you install gsl in non-standard place, set the GSL_ROOT_DIR environment \n"
             " variable. CMAKE use this to search for required files. \n"
             "====================================================================\n"
             )
@@ -186,7 +175,7 @@ if(WITH_GSL)
     # top level.
     include_directories( ${GSL_INCLUDE_DIRS} )
 elseif(WITH_BOOST)
-    find_package(Boost 1.44 COMPONENTS filesystem random REQUIRED)
+    find_package(Boost 1.44 COMPONENTS system filesystem random REQUIRED)
     find_package( LAPACK REQUIRED )
     add_definitions( -DUSE_BOOST -UUSE_GSL )
     include_directories( ${Boost_INCLUDE_DIRS} )
@@ -228,10 +217,17 @@ if(HDF5_FOUND)
         find_library(HDF5_HL_LIBRARIES NAMES libhdf5_hl.a
             PATHS $ENV{HDF5_ROOT}/lib $ENV{HDF5_ROOT}/lib64 
             )
+        set(HDF5_LIBRARIES ${HDF5_CXX_LIBRARIES} ${HDF5_HL_LIBRARIES})
     endif()
-
-    set(HDF5_LIBRARIES ${HDF5_CXX_LIBRARIES} ${HDF5_HL_LIBRARIES})
-    message(STATUS "MOOSE will use ${HDF5_LIBRARIES}" )
+    
+    # Make sure, HDF5_HL_LIBRARIES are set. The COMPONENTS in find_package may
+    # or may not work. See BhallaLab/moose-core#163. 
+    if(NOT HDF5_HL_LIBRARIES)
+        set(HDF5_HL_LIBRARIES ${HDF5_HL_LIBRARIES})
+    endif(NOT HDF5_HL_LIBRARIES)
+    list(APPEND HDF5_LIBRARIES ${HDF5_HL_LIBRARIES})
+
+    message(STATUS "MOOSE will use following HDF5 ${HDF5_LIBRARIES}" )
     foreach(HDF5_LIB ${HDF5_LIBRARIES})
         if(HDF5_LIB)
             get_filename_component( HDF5_LIB_EXT ${HDF5_LIB} EXT )
@@ -244,6 +240,8 @@ if(HDF5_FOUND)
             endif()
         endif( )
     endforeach( )
+else( HDF5_FOUND )
+    message(STATUS "HDF5 is not found" )
 endif( HDF5_FOUND )
 
 # This is a fix for new HDF5 package on Debian/Ubuntu which installs hdf5
@@ -285,7 +283,7 @@ endif(WITH_BOOST)
 # these two types because of --whole-archive option. See
 # BhallaLab/moose-core#66,
 if(WITH_GSL)
-    message(STATUS "Using STATIC gsl libraries: ${GSL_LIBRARIES}")
+    message(STATUS "Using gsl libraries: ${GSL_LIBRARIES}")
     foreach(GSL_LIB ${GSL_LIBRARIES} )
         if(GSL_LIB)
             get_filename_component( GSL_LIB_EXT ${GSL_LIB} EXT )
@@ -391,7 +389,10 @@ endif(MACOSX)
 
 add_dependencies(moose.bin libmoose)
 
-target_link_libraries(moose.bin LINK_PUBLIC moose ${CMAKE_DL_LIBS})
+target_link_libraries(moose.bin moose ${CMAKE_DL_LIBS})
+if( WITH_BOOST )
+    target_link_libraries( moose.bin ${Boost_LIBRARIES} )
+endif( WITH_BOOST )
 
 ######################### BUILD PYMOOSE ########################################
 # Root of all python module.
diff --git a/INSTALL.md b/INSTALL.md
index 0bc6e631d502e55efd4ac623f3f1464e82ffe2b5..db608dab82ff2889eecc4fe953aa593297fe52ec 100644
--- a/INSTALL.md
+++ b/INSTALL.md
@@ -1,16 +1,25 @@
 # Pre-built packages
 
+## Linux
+
 Use our repositories hosted at [Open Build Service](http://build.opensuse.org).
 We have packages for Debian, Ubuntu, CentOS, Fedora, OpenSUSE/SUSE, RHEL,
 Scientific Linux.  Visit the following page for instructions.
 
 https://software.opensuse.org/download.html?project=home:moose&package=moose
 
+## MacOSX
+
+MOOSE is available via [homebrew](http://brew.sh).
+
+    $ brew install homebrew/science/moose 
+
+
 # Building MOOSE from source
 
 To build `MOOSE` from source, you can either use `cmake` (recommended) or GNU `make` based flow.
 
-Download the latest source code of moose from github or sourceforge.
+Download the latest source code of moose from github.
 
     $ git clone -b master https://github.com/BhallaLab/moose-core
 
@@ -29,6 +38,10 @@ On Ubuntu-12.04 or higher, these can be installed with:
 
 __NOTE__ : On Ubuntu 12.04, gsl version is 1.15. You should skip `libgsl0-dev` install gsl-1.16 or higher manually.
 
+SBML support is enabled by installing [python-libsbml](http://sbml.org/Software/libSBML/docs/python-api/libsbml-installation.html). Alternatively, it can be installed by using `python-pip`
+
+    $ sudo pip install python-libsbml
+
 ## Use `cmake` to build moose:
     
     $ cd /path/to/moose-core 
diff --git a/MooseTests.cmake b/MooseTests.cmake
index 77e9fc866fc57d6bba0b59bd42518fce79313232..58be0f4b931d637b3c4ae6bfa8a4fa15a4e8e79b 100644
--- a/MooseTests.cmake
+++ b/MooseTests.cmake
@@ -79,16 +79,17 @@ set_tests_properties(pymoose-ksolve-test
     PROPERTIES ENVIRONMENT "PYTHONPATH=${PROJECT_BINARY_DIR}/python"
     )
 
-## Test basic SBML support.
-#ADD_TEST(NAME pymoose-test-basic-sbml-support
-    #COMMAND ${TEST_COMMAND}
-    #${PROJECT_SOURCE_DIR}/tests/python/test_sbml_support.py
-    #)
-#set_tests_properties(pymoose-test-basic-sbml-support 
-    #PROPERTIES ENVIRONMENT "PYTHONPATH=${PROJECT_BINARY_DIR}/python"
-    #)
-
-# Test basic SBML support.
+## Test basic SBML support. Only for python2.
+if( PYTHON_VERSION_STRING VERSION_LESS "3.0.0" )
+    ADD_TEST(NAME pymoose-test-basic-sbml-support
+        COMMAND ${TEST_COMMAND}
+        ${PROJECT_SOURCE_DIR}/tests/python/test_sbml.py
+        )
+    set_tests_properties(pymoose-test-basic-sbml-support 
+        PROPERTIES ENVIRONMENT "PYTHONPATH=${PROJECT_BINARY_DIR}/python"
+        )
+endif( )
+
 ADD_TEST(NAME pymoose-test-rng
     COMMAND ${PROJECT_SOURCE_DIR}/tests/python/test_random_gen.sh
     ${PYTHON_EXECUTABLE} ${PROJECT_BINARY_DIR}/python
@@ -114,3 +115,13 @@ ADD_TEST( NAME pymoose-test-streaming_in_tables
 set_tests_properties(pymoose-test-streaming_in_tables
     PROPERTIES ENVIRONMENT "PYTHONPATH=${PROJECT_BINARY_DIR}/python"
     )
+
+# Test kkit support.
+ADD_TEST( NAME pymoose-test-kkit 
+    COMMAND ${TEST_COMMAND} 
+    ${PROJECT_SOURCE_DIR}/tests/python/test_kkit.py
+    )
+set_tests_properties(pymoose-test-kkit
+    PROPERTIES ENVIRONMENT "PYTHONPATH=${PROJECT_BINARY_DIR}/python"
+    )
+
diff --git a/VERSION b/VERSION
deleted file mode 100644
index bad061c1d8dde6d3f7b8f05cf11fa949eafa1642..0000000000000000000000000000000000000000
--- a/VERSION
+++ /dev/null
@@ -1 +0,0 @@
-3.1.0-155-gb7f1834
\ No newline at end of file
diff --git a/basecode/Id.h b/basecode/Id.h
index 9b3aee7e61ca027871bfc8f5f216c9f844b7e4f6..04bb31523e660bf417281fb130cfa14d770cee90 100644
--- a/basecode/Id.h
+++ b/basecode/Id.h
@@ -16,165 +16,162 @@
  */
 class Id
 {
-	public:
-		//////////////////////////////////////////////////////////////
-		//	Id creation
-		//////////////////////////////////////////////////////////////
-		/**
-		 * Returns the root Id
-		 */
-		Id();
-
-		/**
-		 * Creates an id with the specified Element number
-		 */
-		Id( unsigned int id );
-
-		/**
-		 * Returns an id found by traversing the specified path
-		 */
-		Id( const std::string& path, const std::string& separator = "/" );
-
-		/**
-		 * Downconverts an OjbId to an Id
-		 */
-		Id( const ObjId& oi );
-
-		/**
-		 * Destroys an Id. Doesn't do anything much.
-		 */
-		~Id(){}
-
-		//////////////////////////////////////////////////////////////
-		//	Element creation and deletion.
-		//////////////////////////////////////////////////////////////
-
-//		static Id create( Element* e );
-
-		/**
-		 * Reserves an id for assigning to an Element. Each time it is
-		 * called a new id is reserved, even if previous ones have not been
-		 * used yet.
-		 */
-		static Id nextId();
-
-
-		/**
-		 * Returns the number of Ids in use.
-		 */
-		static unsigned int numIds();
-
-		/**
-		 * The specified element is placed into current id.
-		 */
-		void bindIdToElement( Element* e ); 
-
-		/**
-		 * Cleanly deletes the associated Element, and zeroes out
-		 * contents of elements vector at the location pointed to by
-		 * this->id_.
-		 */
-		void destroy() const;
-    
-		//////////////////////////////////////////////////////////////
-		//	Id info
-		//////////////////////////////////////////////////////////////
-		/**
-		 * Returns the full pathname of the object on the id.
-		 */
-		std::string path( const std::string& separator = "/" ) const;
-
-
-		/**
-		 * Returns the Element pointed to by the id
-		 * If it is off-node, returns an allocated wrapper element with 
-		 * postmaster and id information. Calling func has to free it.
-		 * This wrapper element may also point to UNKNOWN NODE, in which
-		 * case the master node IdManager has to figure out where it
-		 * belongs.
-		 * Returns 0 on failure.
-		 * Deprecated.
-		Element* operator()() const;
-		 */
-
-		/**
-		 * Returns the Element pointed to by the Id.
-		 * Perhaps cleaner to use than operator()() as it is an explicit 
-		 * function.
-		 */
-		Element* element() const;
+public:
+    //////////////////////////////////////////////////////////////
+    //	Id creation
+    //////////////////////////////////////////////////////////////
+    /**
+     * Returns the root Id
+     */
+    Id();
+
+    /**
+     * Creates an id with the specified Element number
+     */
+    Id( unsigned int id );
+
+    /**
+     * Returns an id found by traversing the specified path
+     */
+    Id( const std::string& path, const std::string& separator = "/" );
+
+    /**
+     * Downconverts an OjbId to an Id
+     */
+    Id( const ObjId& oi );
+
+    /**
+     * Destroys an Id. Doesn't do anything much.
+     */
+    ~Id() {}
+
+    /**
+     * Reserves an id for assigning to an Element. Each time it is
+     * called a new id is reserved, even if previous ones have not been
+     * used yet.
+     */
+    static Id nextId();
+
+
+    /**
+     * Returns the number of Ids in use.
+     */
+    static unsigned int numIds();
+
+    /**
+     * The specified element is placed into current id.
+     */
+    void bindIdToElement( Element* e );
+
+    /**
+     * Cleanly deletes the associated Element, and zeroes out
+     * contents of elements vector at the location pointed to by
+     * this->id_.
+     */
+    void destroy() const;
+
+    //////////////////////////////////////////////////////////////
+    //	Id info
+    //////////////////////////////////////////////////////////////
+    /**
+     * Returns the full pathname of the object on the id.
+     */
+    std::string path( const std::string& separator = "/" ) const;
+
+
+    /**
+     * Returns the Element pointed to by the id
+     * If it is off-node, returns an allocated wrapper element with
+     * postmaster and id information. Calling func has to free it.
+     * This wrapper element may also point to UNKNOWN NODE, in which
+     * case the master node IdManager has to figure out where it
+     * belongs.
+     * Returns 0 on failure.
+     * Deprecated.
+    Element* operator()() const;
+     */
+
+    /**
+     * Returns the Element pointed to by the Id.
+     * Perhaps cleaner to use than operator()() as it is an explicit
+     * function.
+     */
+    Element* element() const;
 
 //		unsigned int index() const;
 
-		/**
-		 * Returns the Eref to the element plus index
-		 */
-		Eref eref() const;
-
-		/**
-		 * Returns an id whose value is string-converted from the 
-		 * specified string. 
-		 */
-		static Id str2Id( const std::string& s );
-
-		/**
-		 * Returns a string holding the ascii value of the id_ .
-		 */
-		static std::string id2str( Id id );
-
-		unsigned int value() const;
-
-		//////////////////////////////////////////////////////////////
-		//	Comparisons between ids
-		//////////////////////////////////////////////////////////////
-		bool operator==( const Id& other ) const {
-			// return id_ == other.id_ && index_ == other.index_;
-			return id_ == other.id_;
-		}
-
-		bool operator!=( const Id& other ) const {
-			// return id_ != other.id_ || index_ != other.index_;
-			return id_ != other.id_;
-		}
-
-		bool operator<( const Id& other ) const {
-		//	return ( id_ < other.id_ ) ||
-		//		( id_ == other.id_ && index_ < other.index_ );
-			return ( id_ < other.id_ );
-		}
+    /**
+     * Returns the Eref to the element plus index
+     */
+    Eref eref() const;
+
+    /**
+     * Returns an id whose value is string-converted from the
+     * specified string.
+     */
+    static Id str2Id( const std::string& s );
+
+    /**
+     * Returns a string holding the ascii value of the id_ .
+     */
+    static std::string id2str( Id id );
+
+    unsigned int value() const;
+
+    //////////////////////////////////////////////////////////////
+    //	Comparisons between ids
+    //////////////////////////////////////////////////////////////
+    bool operator==( const Id& other ) const
+    {
+        // return id_ == other.id_ && index_ == other.index_;
+        return id_ == other.id_;
+    }
+
+    bool operator!=( const Id& other ) const
+    {
+        // return id_ != other.id_ || index_ != other.index_;
+        return id_ != other.id_;
+    }
+
+    bool operator<( const Id& other ) const
+    {
+        //	return ( id_ < other.id_ ) ||
+        //		( id_ == other.id_ && index_ < other.index_ );
+        return ( id_ < other.id_ );
+    }
 
     // The follwoing two functions check if the Id is associated with
     // an existing element. Needed for handling objects that have been destroyed.
-        static bool isValid(Id id)
-        {
-            return (id.id_ < elements().size()) && (elements()[id.id_] != 0);
-        }
-
-        static bool isValid(unsigned int id)
-        {
-            return (id < elements().size()) && (elements()[id] != 0);
-        }                
-
-		//////////////////////////////////////////////////////////////
-		/**
-		 * Used to clean up all Elements when the simulation is terminated
-		 */
-		static void clearAllElements();
-
-		/**
-		 * Used to clean out any specific Id.
-		 */
-		void zeroOut() const;
-		//////////////////////////////////////////////////////////////
-
-		friend ostream& operator <<( ostream& s, const Id& i );
-		friend istream& operator >>( istream& s, Id& i );
-
-	private:
-		// static void setManager( Manager* m );
-		unsigned int id_; // Unique identifier for Element*
+    static bool isValid(Id id)
+    {
+        return (id.id_ < elements().size()) && (elements()[id.id_] != 0);
+    }
+
+    static bool isValid(unsigned int id)
+    {
+        return (id < elements().size()) && (elements()[id] != 0);
+    }
+
+    //////////////////////////////////////////////////////////////
+    /**
+     * Used to clean up all Elements when the simulation is terminated
+     */
+    static void clearAllElements();
+
+    /**
+     * Used to clean out any specific Id.
+     */
+    void zeroOut() const;
+    //////////////////////////////////////////////////////////////
+
+    friend ostream& operator <<( ostream& s, const Id& i );
+    friend istream& operator >>( istream& s, Id& i );
+
+private:
+    // static void setManager( Manager* m );
+    unsigned int id_; // Unique identifier for Element*
 //		unsigned int index_; // Index of array entry within element.
-		static vector< Element* >& elements();
+    static vector< Element* >& elements();
 };
 
 #endif // _ID_H
diff --git a/basecode/global.cpp b/basecode/global.cpp
index c5c75f4633a3f6a5d3f18d6e25b07b7fe01c29aa..ec5a523e78e911755e12565e854af321b5172ada 100644
--- a/basecode/global.cpp
+++ b/basecode/global.cpp
@@ -89,6 +89,7 @@ namespace moose {
      */
     void mtseed( unsigned int x )
     {
+        moose::__rng_seed__ = x;
         moose::rng.setSeed( x );
         isRNGInitialized = true;
     }
diff --git a/basecode/header.h b/basecode/header.h
index edc0d559a28d37807c1d882193b09cca3b8e59ea..20f3cc1eb2454cae4430f3dce6fd2efc182c095f 100644
--- a/basecode/header.h
+++ b/basecode/header.h
@@ -107,6 +107,8 @@ class Neutral;
 #include "SharedFinfo.h"
 #include "FieldElementFinfo.h"
 #include "FieldElement.h"
+#include "../builtins/Streamer.h"
 #include "../shell/Neutral.h"
 
+
 #endif // _HEADER_H
diff --git a/basecode/main.cpp b/basecode/main.cpp
index 5d234e2febce0396b23fa05cdfbc65e98f91d83c..dae67a9858922dd8901351c4c04e2c80ab68348f 100644
--- a/basecode/main.cpp
+++ b/basecode/main.cpp
@@ -9,13 +9,6 @@
 
 #include "header.h"
     
-
-#if 0
-#include <boost/log/trivial.hpp>
-#include <boost/log/core.hpp>
-#include <boost/log/expressions.hpp>
-#endif
-
 #ifndef WIN32
 #include <sys/time.h>
 #else
@@ -153,30 +146,10 @@ void checkChildren( Id parent, const string& info )
     }
 }
 
-/**
- * @brief Initialize logger.
- */
-void initLogger( void )
-{
-
-#if 0
-    boost::log::core::get()->set_filter
-    (
-#ifdef DEBUG
-        boost::log::trivial::severity >= boost::log::trivial::debug
-#else
-        boost::log::trivial::severity >= boost::log::trivial::info
-#endif
-    );
-#endif
-
-}
 
 Id init( int argc, char** argv, bool& doUnitTests, bool& doRegressionTests,
          unsigned int& benchmark )
 {
-    initLogger( );
-
     unsigned int numCores = getNumCores();
     int numNodes = 1;
     int myNode = 0;
diff --git a/builtins/Streamer.cpp b/builtins/Streamer.cpp
index 93d4419411ce35fea94b37a2911a8da8ca08fe17..fc21fc05612830c7bea3d8af0fa361fa39dc9b53 100644
--- a/builtins/Streamer.cpp
+++ b/builtins/Streamer.cpp
@@ -157,14 +157,6 @@ Streamer& Streamer::operator=( const Streamer& st )
 
 Streamer::~Streamer()
 {
-    cleanUp();
-}
-
-void Streamer::cleanUp( void )
-{
-    /*  Write the left-overs. */
-    zipWithTime( data_, currTime_ );
-    StreamerBase::writeToOutFile( outfilePath_, format_, "a", data_, columns_ );
 }
 
 /**
@@ -212,7 +204,6 @@ void Streamer::reinit(const Eref& e, ProcPtr p)
         tableDt_.push_back( clk->getTickDt( tickNum ) );
     }
 
-
     // Make sure all tables have same dt_ else disable the streamer.
     vector<unsigned int> invalidTables;
     for (size_t i = 1; i < tableTick_.size(); i++) 
@@ -242,11 +233,24 @@ void Streamer::reinit(const Eref& e, ProcPtr p)
         string defaultPath = "_tables/" + moose::moosePathToUserPath( e.id().path() );
         setOutFilepath( defaultPath );
     }
+
+    // Prepare data. Add columns names and write whatever values are available
+    // write now.
     currTime_ = 0.0;
-    // Prepare data.
-    zipWithTime( data_, currTime_ );
+    zipWithTime( );
     StreamerBase::writeToOutFile( outfilePath_, format_, "w", data_, columns_);
-    data_.clear();
+    data_.clear( );
+}
+
+/**
+ * @brief This function is called from Shell when simulation is called to write
+ * the left-over data to streamer file.
+ */
+void Streamer::cleanUp( )
+{
+    zipWithTime( );
+    StreamerBase::writeToOutFile( outfilePath_, format_, "a", data_, columns_ );
+    data_.clear( );
 }
 
 /**
@@ -257,12 +261,15 @@ void Streamer::reinit(const Eref& e, ProcPtr p)
  */
 void Streamer::process(const Eref& e, ProcPtr p)
 {
-    // Prepare data.
-    zipWithTime( data_, currTime_ );
-    StreamerBase::writeToOutFile( outfilePath_, format_, "a", data_, columns_ );
+    //LOG( moose::debug, "Writing to table" );
+    zipWithTime( );
 
-    // clean the arrays
-    data_.clear();
+    // Write only if there are more than 100 entry in first table.
+    if( tables_[0]->getVecSize() > 100 )
+    {
+        StreamerBase::writeToOutFile( outfilePath_, format_, "a", data_, columns_ );
+        data_.clear( );
+    }
 }
 
 
@@ -285,8 +292,8 @@ void Streamer::addTable( Id table )
 
     // NOTE: If user can make sure that names are unique in table, using name is
     // better than using the full path.
-    if( t->getName().size() > 0 )
-        columns_.push_back( t->getName( ) );
+    if( t->getColumnName().size() > 0 )
+        columns_.push_back( t->getColumnName( ) );
     else
         columns_.push_back( moose::moosePathToUserPath( table.path() ) );
 }
@@ -381,19 +388,47 @@ string Streamer::getFormat( void ) const
     return format_;
 }
 
-void Streamer::zipWithTime( vector<double>& data, double currTime)
+/**
+ * @brief This function prepares data to be written to a file.
+ */
+void Streamer::zipWithTime( )
 {
-    size_t N = tables_[0]->getVecSize();
-    for (size_t i = 0; i < N; i++) 
+    size_t numEntriesInEachTable = tables_[0]->getVecSize( );
+
+    //LOG( moose::debug, "Entries in each table " << numEntriesInEachTable );
+
+    // Collect data from all table. If some table does not have enough data,
+    // fill it with nan
+    vector< vector< double > > collectedData;
+    for( size_t i = 0; i < tables_.size( ); i++ )
     {
-        /* Each entry we write, currTime_ increases by dt.  */
-        data.push_back( currTime_ );
-        currTime_ += tableDt_[0];               
-        for( size_t i = 0; i < tables_.size(); i++)
-            data.push_back( tables_[i]->getVec()[i] );
+        vector<double> tVec( tables_[i]->getVec( ) );
+        if( tVec.size( ) <= numEntriesInEachTable )
+        {
+#if 0
+            LOG( moose::debug
+                    , "Table " << tables_[i]->getName( ) << " is not functional. Filling with zero " 
+                    );
+#endif
+            tVec.resize( numEntriesInEachTable, 0 );
+        }
+        collectedData.push_back( tVec );
+    }
+
+    // Turn it into a table format. Its like taking a transpose of vector<
+    // vector >.
+    double allTableDt = tableDt_[ 0 ];
+    for( size_t i = 0; i < collectedData[0].size( ); i++ )
+    {
+        data_.push_back( currTime_ );
+        currTime_ += allTableDt;
+        for( size_t ii = 0; ii < collectedData.size(); ii++ )
+            data_.push_back( collectedData[ ii ][ i ] );
     }
 
-    // clear the data from tables now.
+    // After collection data from table, clear tables.
     for(size_t i = 0; i < tables_.size(); i++ )
-        tables_[i]->clearVec();
+        tables_[i]->clearVec( );
+
+    return;
 }
diff --git a/builtins/Streamer.h b/builtins/Streamer.h
index 738788a9508b6aa2c04f0a901c2bbe994563c88c..cc379e6ca2b0586673b74044496de314b5c65ba1 100644
--- a/builtins/Streamer.h
+++ b/builtins/Streamer.h
@@ -30,7 +30,7 @@
 
 using namespace std;
 
-class Streamer
+class Streamer : public StreamerBase 
 {
 
 public:
@@ -56,7 +56,7 @@ public:
     void removeTable( Id table );
     void removeTables( vector<Id> table );
 
-    void zipWithTime( vector<double>& data, double currTime);
+    void zipWithTime( );
 
     /** Dest functions.
      * The process function called by scheduler on every tick
diff --git a/builtins/StreamerBase.cpp b/builtins/StreamerBase.cpp
index 90904c34b751cd6148440e19a14de591f969961b..7eebfcbf17059887cb4e117ed09f95192d04724e 100644
--- a/builtins/StreamerBase.cpp
+++ b/builtins/StreamerBase.cpp
@@ -65,10 +65,10 @@ void StreamerBase::writeToOutFile( const string& filepath
     if( data.size() == 0 )
         return;
 
-    if( "csv" == outputFormat )
-        writeToCSVFile( filepath, openmode, data, columns );
-    else if( "npy" == outputFormat )
+    if( "npy" == outputFormat )
         writeToNPYFile( filepath, openmode, data, columns );
+    else if( "csv" == outputFormat or "dat" == outputFormat )
+        writeToCSVFile( filepath, openmode, data, columns );
     else
     {
         LOG( moose::warning, "Unsupported format " << outputFormat 
@@ -76,7 +76,6 @@ void StreamerBase::writeToOutFile( const string& filepath
            );
         writeToCSVFile( filepath, openmode, data, columns );
     }
-
 }
 
 
diff --git a/builtins/StreamerBase.h b/builtins/StreamerBase.h
index 731e9bbe92bc204f0f83634a5c69764c52d112d3..3fd70ad0ae23c00ad43b7f3696c2561928806eb6 100644
--- a/builtins/StreamerBase.h
+++ b/builtins/StreamerBase.h
@@ -52,7 +52,7 @@ public:
      * @param format 
      *
      *  npy : numpy binary format (version 1 and 2), version 1 is default.
-     *  csv : comma separated value (delimiter ',' )
+     *  csv or dat: comma separated value (delimiter ' ' )
      *
      * @param  openmode (write or append)
      * 
diff --git a/builtins/Table.cpp b/builtins/Table.cpp
index c9c641809b826fd039fe286efd781b2b03066fdc..5b6914b0a131dbeabaecdd13cd76ec71e8f29d08 100644
--- a/builtins/Table.cpp
+++ b/builtins/Table.cpp
@@ -74,11 +74,13 @@ const Cinfo* Table::initCinfo()
         , &Table::getFormat
     );
 
-    static ValueFinfo< Table, string > name(
-        "name"
-        , "Name of the table."
-        , &Table::setName
-        , &Table::getName
+    // relevant for Streamer class.  When data is written to a datafile, this is
+    // used to create column name.
+    static ValueFinfo< Table, string > columnName(
+        "columnName"
+        , "Name of the table written in header of data file."
+        , &Table::setColumnName
+        , &Table::getColumnName
     );
 
     //////////////////////////////////////////////////////////////
@@ -126,7 +128,7 @@ const Cinfo* Table::initCinfo()
     {
         &threshold,		// Value
         &format,                // Value
-        &name,                  // Value
+        &columnName,            // Value
         &outfile,               // Value 
         &useStreamer,           // Value
         handleInput(),		// DestFinfo
@@ -347,15 +349,15 @@ string Table::getFormat( void ) const
     return format_;
 }
 
-/*  User defined name  */
-string Table::getName( void ) const
+/*  User defined column name for streamer  */
+string Table::getColumnName( void ) const
 {
-    return tableName_;
+    return tableColumnName_;
 }
 
-void Table::setName( const string name )
+void Table::setColumnName( const string colname )
 {
-    tableName_ = name ;
+    tableColumnName_ = colname ;
 }
 
 /* Enable/disable streamer support. */
diff --git a/builtins/Table.h b/builtins/Table.h
index 3e2e086e3d4b6671f8308b9edd5d6ce158152574..5a21b2d31c13d9d26ef53a2d9d9c0e6366691aab 100644
--- a/builtins/Table.h
+++ b/builtins/Table.h
@@ -25,45 +25,45 @@ public:
     Table();
     ~Table();
 
-    Table& operator=( const Table& tab );
+    Table& operator= ( const Table& tab );
 
     //////////////////////////////////////////////////////////////////
     // Field assignment stuff
     //////////////////////////////////////////////////////////////////
 
-    void setThreshold( double v );
+    void setThreshold ( double v );
     double getThreshold() const;
 
-    void setFormat( const string format );
+    void setFormat ( const string format );
     string getFormat( ) const;
 
-    void setName( const string name );
-    string getName( ) const;
+    void setColumnName( const string colname );
+    string getColumnName( ) const;
 
-    void setUseStreamer( bool status );
-    bool getUseStreamer( void ) const;
+    void setUseStreamer ( bool status );
+    bool getUseStreamer ( void ) const;
 
-    void setOutfile( string outfilepath );
-    string getOutfile( void ) const;
+    void setOutfile ( string outfilepath );
+    string getOutfile ( void ) const;
 
     // Access the dt_ of table.
-    double getDt( void ) const;
+    double getDt ( void ) const;
 
-    void zipWithTime( 
-            const vector<double>& yvec
-            , vector<double>& tvec
-            , const double& lasttime 
-            );
+    void zipWithTime (
+        const vector<double>& yvec
+        , vector<double>& tvec
+        , const double& lasttime
+    );
 
     //////////////////////////////////////////////////////////////////
     // Dest funcs
     //////////////////////////////////////////////////////////////////
 
-    void process( const Eref& e, ProcPtr p );
-    void reinit( const Eref& e, ProcPtr p );
+    void process ( const Eref& e, ProcPtr p );
+    void reinit ( const Eref& e, ProcPtr p );
 
-    void input( double v );
-    void spike( double v );
+    void input ( double v );
+    void spike ( double v );
 
     //////////////////////////////////////////////////////////////////
     // Lookup funcs for table
@@ -77,14 +77,19 @@ private:
     double input_;
 
     /**
-     * @brief Keep the data, each entry is preceeded by time value. 
+     * @brief Keep the data, each entry is preceeded by time value.
      * t0, v0, t1, v1, t2, v2 etc.
      */
     vector<double> data_;
     vector<string> columns_;                    /* Store the name of tables */
 
     string tablePath_;
-    string tableName_;
+
+
+    /**
+     * @brief Column name of this table. Use it when writing data to a datafile.
+     */
+    string tableColumnName_;
 
     /**
      * @brief If stream is set to true, then stream to outfile_. Default value
@@ -105,10 +110,10 @@ private:
     /**
      * @brief Wheather or not outfile path is set by user
      */
-    bool outfileIsSet_;                         
+    bool outfileIsSet_;
 
     /**
-     * @brief format of data. Currently fixed to csv.
+     * @brief format of data. Default to csv.
      */
     string format_;
 
diff --git a/builtins/TableBase.cpp b/builtins/TableBase.cpp
index dabf350151aaf6a7ad8fac66f6025533271aca38..e2e05ba521d49b3992534bf7164e6084a397e804 100644
--- a/builtins/TableBase.cpp
+++ b/builtins/TableBase.cpp
@@ -485,3 +485,9 @@ vector< double >& TableBase::vec()
 {
 	return vec_;
 }
+
+// Fetch the const copy of table. Used in Streamer class.
+const vector< double >& TableBase::data( )
+{
+    return vec_;
+}
diff --git a/builtins/TableBase.h b/builtins/TableBase.h
index 6474a0572852395a8fc0ec475ba50b6894cf8c30..7d4bccb6fd36c5da6193e61b31bb86dc87b4b55b 100644
--- a/builtins/TableBase.h
+++ b/builtins/TableBase.h
@@ -25,6 +25,8 @@ public:
      *  Functions related to field assignment.
      *-----------------------------------------------------------------------------*/
     vector< double > getVec() const;
+    const vector< double >& data( );
+
     void setVec( vector< double > val );
 
     double getOutputValue() const;
diff --git a/external/odeint-v2/fix-copyright.py b/external/odeint-v2/fix-copyright.py
index f4848226a434ed2ed6f62586599b1dbfb1255112..2dea71f5d3bb06ba747b8f4fc06ff7645e45b1d5 100755
--- a/external/odeint-v2/fix-copyright.py
+++ b/external/odeint-v2/fix-copyright.py
@@ -1,4 +1,5 @@
 #!/usr/bin/env python
+from __future__ import print_function
 from subprocess import check_output as run
 from datetime import datetime
 from itertools import groupby
@@ -18,10 +19,10 @@ def authors(filename):
 def new_copyright(filename, previous):
     def f():
         au = list(authors(filename))
-        alldates = map(itemgetter(1), au)
-        aup = sorted(au + map(lambda a: (a, None), previous), key=itemgetter(0))
+        alldates = list(map(itemgetter(1), au))
+        aup = sorted(au + [(a, None) for a in previous], key=itemgetter(0))
         for author, records in groupby(aup, itemgetter(0)):
-            dates = filter(None, map(itemgetter(1), records))
+            dates = [_f for _f in map(itemgetter(1), records) if _f]
             if not dates: dates = alldates
             start = min(dates)
             end = max(dates)
@@ -29,7 +30,7 @@ def new_copyright(filename, previous):
             line = 'Copyright ' + fmt.format(start.year, end.year) + ' ' + author
             key = (start, author)
             yield key, line
-    return map(itemgetter(1), sorted(f()))
+    return list(map(itemgetter(1), sorted(f())))
 
 def fix_copyright(filename):
     # Find copyright block in original file
@@ -46,19 +47,19 @@ def fix_copyright(filename):
             lines.append(i)
             names.append(d['name'].strip())
     if len(prefix) != 1:
-        print 'Not found:', filename
+        print('Not found:', filename)
         return
     prefix = list(prefix)[0]
 
-    print filename
+    print(filename)
     new = iter(new_copyright(filename, names))
     with open(filename, 'w') as f:
         for i, line in enumerate(content):
             if i in lines:
                 for repl in new:
-                    print >>f, prefix + repl
+                    print(prefix + repl, file=f)
             else:
-                print >>f, line,
+                print(line, end=' ', file=f)
     pass
 
 def all_files():
diff --git a/ksolve/GssaVoxelPools.cpp b/ksolve/GssaVoxelPools.cpp
index c4b529ee6aaaa59572d33bd005d3262953805f0b..b74900aa7bf9183474b51e4144c234bb4eaf183a 100644
--- a/ksolve/GssaVoxelPools.cpp
+++ b/ksolve/GssaVoxelPools.cpp
@@ -218,7 +218,7 @@ void GssaVoxelPools::advance( const ProcInfo* p, const GssaSystem* g )
 
 void GssaVoxelPools::reinit( const GssaSystem* g )
 {
-    //rng_.setSeed( moose::__rng_seed__ );
+    rng_.setSeed( moose::__rng_seed__ );
     VoxelPoolsBase::reinit(); // Assigns S = Sinit;
     unsigned int numVarPools = g->stoich->getNumVarPools();
     g->stoich->updateFuncs( varS(), 0 );
diff --git a/pymoose/melement.cpp b/pymoose/melement.cpp
index 04308f217363ac38e17bf1dc136bbb339a10aca2..7cd4ee914d7162e3296717cc0c3b71d96d1fec7a 100644
--- a/pymoose/melement.cpp
+++ b/pymoose/melement.cpp
@@ -180,7 +180,7 @@ int moose_ObjId_init_from_path(_ObjId * self, PyObject * args,
     ostringstream err;
     // First see if there is an existing object with at path
     self->oid_ = ObjId(path);
-    PyTypeObject * basetype = getBaseClass((PyObject*)self);
+    PyTypeObject* basetype = getBaseClass((PyObject*)self);
     string basetype_str;
     if (type == NULL){
         if (basetype == NULL){
@@ -210,15 +210,26 @@ int moose_ObjId_init_from_path(_ObjId * self, PyObject * args,
     } else { // this is a non-root existing element
         // If the current class is a subclass of some predefined
         // moose class, do nothing.
+        string className = self->oid_.element()->cinfo()->name();
+        map <string, PyTypeObject * >::iterator ii = 
+        	get_moose_classes().find( className );
+        PyTypeObject * basetype = 0;
+        if ( ii != get_moose_classes().end() ) {
+    	    basetype = ii->second;
+            basetype_str = string(basetype->tp_name).substr(6); // remove `moose.` prefix from type name
+        } else {
+            err << "Unknown class: " << className << endl;
+            basetype = getBaseClass((PyObject*)self);
+        }
         if ((basetype != NULL) && PyType_IsSubtype(mytype, basetype)){
             return 0;
         }
         // element exists at this path, but it does not inherit from any moose class.
         // throw an error
         err << "cannot convert "
-            << Field<string>::get(self->oid_, "className")
+			<< className 
             << " to "
-            << basetype_str
+            << mytypename
             << ". To get the existing object use `moose.element(obj)` instead.";
         PyErr_SetString(PyExc_TypeError, err.str().c_str());
         return -1;
diff --git a/pymoose/moosemodule.cpp b/pymoose/moosemodule.cpp
index 97f66dad6ed9c30ec9aba9b417cee2c8d8d3f077..62a9ea2eb85cc6c16ab8bd9dd145e39eeebc8421 100644
--- a/pymoose/moosemodule.cpp
+++ b/pymoose/moosemodule.cpp
@@ -1791,50 +1791,6 @@ PyObject * moose_exists(PyObject * dummy, PyObject * args)
     return Py_BuildValue("i", Id(path) != Id() || string(path) == "/" || string(path) == "/root");
 }
 
-//Harsha : For writing genesis file to sbml
-/*
-PyObject * moose_writeSBML(PyObject * dummy, PyObject * args)
-{
-    char * fname = NULL, * modelpath = NULL;
-    if(!PyArg_ParseTuple(args, "ss:moose_writeSBML", &modelpath, &fname))
-    {
-        return NULL;
-    }
-    int ret = SHELLPTR->doWriteSBML(string(modelpath),string(fname));
-    return Py_BuildValue("i", ret);
-}
-*/
-/*
-PyObject * moose_readSBML(PyObject * dummy, PyObject * args)
-{
-    char * fname = NULL, * modelpath = NULL, * solverclass = NULL;
-    if(!PyArg_ParseTuple(args, "ss|s:moose_readSBML", &fname, &modelpath, &solverclass))
-    {
-        return NULL;
-    }
-    //Id ret = SHELLPTR->doReadSBML(string(fname), string(modelpath));
-    //return Py_BuildValue("i", ret);
-    _Id * model = (_Id*)PyObject_New(_Id, &IdType);
-    //model->id_ = SHELLPTR->doReadSBML(string(fname), string(modelpath), string(solverclass));
-    if (!solverclass)
-    {
-        model->id_ = SHELLPTR->doReadSBML(string(fname), string(modelpath));
-    }
-    else
-    {
-        model->id_ = SHELLPTR->doReadSBML(string(fname), string(modelpath), string(solverclass));
-    }
-
-    if (model->id_ == Id())
-    {
-        Py_XDECREF(model);
-        PyErr_SetString(PyExc_IOError, "could not load model");
-        return NULL;
-    }
-    PyObject * ret = reinterpret_cast<PyObject*>(model);
-    return ret;
-}
-*/
 PyDoc_STRVAR(moose_loadModel_documentation,
              "loadModel(filename, modelpath, solverclass) -> vec\n"
              "\n"
@@ -1882,7 +1838,7 @@ PyObject * moose_loadModel(PyObject * dummy, PyObject * args)
     PyObject * ret = reinterpret_cast<PyObject*>(model);
     return ret;
 }
-
+/*
 PyDoc_STRVAR(moose_saveModel_documentation,
              "saveModel(source, filename) -> None\n"
              "\n"
@@ -1939,7 +1895,7 @@ PyObject * moose_saveModel(PyObject * dummy, PyObject * args)
     SHELLPTR->doSaveModel(model, filename);
     Py_RETURN_NONE;
 }
-
+*/
 PyObject * moose_setCwe(PyObject * dummy, PyObject * args)
 {
     PyObject * element = NULL;
@@ -3075,15 +3031,11 @@ static PyMethodDef MooseMethods[] =
     {"stop", (PyCFunction)moose_stop, METH_VARARGS, "Stop simulation"},
     {"isRunning", (PyCFunction)moose_isRunning, METH_VARARGS, "True if the simulation is currently running."},
     {"exists", (PyCFunction)moose_exists, METH_VARARGS, "True if there is an object with specified path."},
-    //{"writeSBML", (PyCFunction)moose_writeSBML, METH_VARARGS, "Export biochemical model to an SBML file."},
-    //{"readSBML",  (PyCFunction)moose_readSBML,  METH_VARARGS, "Import SBML model to Moose."},
     {"loadModel", (PyCFunction)moose_loadModel, METH_VARARGS, moose_loadModel_documentation},
-    {"saveModel", (PyCFunction)moose_saveModel, METH_VARARGS, moose_saveModel_documentation},
+    //{"saveModel", (PyCFunction)moose_saveModel, METH_VARARGS, moose_saveModel_documentation},
     {"connect", (PyCFunction)moose_connect, METH_VARARGS, moose_connect_documentation},
     {"getCwe", (PyCFunction)moose_getCwe, METH_VARARGS, "Get the current working element. 'pwe' is an alias of this function."},
-    // {"pwe", (PyCFunction)moose_getCwe, METH_VARARGS, "Get the current working element. 'getCwe' is an alias of this function."},
     {"setCwe", (PyCFunction)moose_setCwe, METH_VARARGS, "Set the current working element. 'ce' is an alias of this function"},
-    // {"ce", (PyCFunction)moose_setCwe, METH_VARARGS, "Set the current working element. setCwe is an alias of this function."},
     {"getFieldDict", (PyCFunction)moose_getFieldDict, METH_VARARGS, moose_getFieldDict_documentation},
     {
         "getField", (PyCFunction)moose_getField, METH_VARARGS,
diff --git a/pymoose/moosemodule.h b/pymoose/moosemodule.h
index 712d590bf2b1c8d7b6d0c74e4bc13ce63357ba34..7ef0e79375c65c8fddf49c9e4fdaec1c4807ebc1 100644
--- a/pymoose/moosemodule.h
+++ b/pymoose/moosemodule.h
@@ -235,9 +235,7 @@ PyObject * moose_stop(PyObject * dummy, PyObject * args);
 PyObject * moose_isRunning(PyObject * dummy, PyObject * args);
 PyObject * moose_exists(PyObject * dummy, PyObject * args);
 PyObject * moose_loadModel(PyObject * dummy, PyObject * args);
-PyObject * moose_saveModel(PyObject * dummy, PyObject * args);
-PyObject * moose_writeSBML(PyObject * dummy, PyObject * args);
-PyObject * moose_readSBML(PyObject * dummy, PyObject * args);
+//PyObject * moose_saveModel(PyObject * dummy, PyObject * args);
 PyObject * moose_setCwe(PyObject * dummy, PyObject * args);
 PyObject * moose_getCwe(PyObject * dummy, PyObject * args);
 PyObject * moose_copy(PyObject * dummy, PyObject * args, PyObject * kwargs);
diff --git a/python/libmumbl/__init__.py b/python/libmumbl/__init__.py
deleted file mode 100644
index 6dafa670e99658aceea4d0ad60110bfb9fce87f6..0000000000000000000000000000000000000000
--- a/python/libmumbl/__init__.py
+++ /dev/null
@@ -1,2 +0,0 @@
-__all__ = [ "utility", "contrib" ]
-from main import *
diff --git a/python/libmumbl/core/__init__.py b/python/libmumbl/core/__init__.py
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/python/libmumbl/core/config.py b/python/libmumbl/core/config.py
deleted file mode 100644
index 4d9805864b7632d2d411d7b1414998cf1d95aa2b..0000000000000000000000000000000000000000
--- a/python/libmumbl/core/config.py
+++ /dev/null
@@ -1,31 +0,0 @@
-import moose
-import logging
-import datetime
-import time
-import os
-
-# Universal paths 
-nmlPath = '/neuroml'
-nmlCellPath = os.path.join(nmlPath, 'cells')
-libraryPath = os.path.join(nmlPath, 'cells')
-cellPath = nmlCellPath
-elecPath = os.path.join(nmlPath, 'electrical')
-
-mumblePath = '/mumbl'
-
-
-st = time.time()
-st = datetime.datetime.fromtimestamp(st).strftime('%Y-%m-%d-%H%M')
-
-logDir = 'logs'
-logFile = os.path.join(logDir, 'moose.log')
-if not os.path.isdir(logDir):
-    os.makedirs(logDir)
-
-if os.path.exists(logFile):
-    os.rename(logFile, 'logs/{0}'.format(st))
-
-logging.basicConfig(filename=logFile, level=logging.DEBUG)
-mooseLogger = logging.getLogger()
-disbleCopyingOfObject = True
-
diff --git a/python/libmumbl/core/dynamic_vars.py b/python/libmumbl/core/dynamic_vars.py
deleted file mode 100644
index ae56381a9f295efff01e8ebc7903a78b1248a752..0000000000000000000000000000000000000000
--- a/python/libmumbl/core/dynamic_vars.py
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
-"""dynamic_vars.py: Class to create variables out of strings.
-
-Last modified: Wed Dec 11, 2013  07:08PM
-
-"""
-    
-__author__           = "Dilawar Singh"
-__copyright__        = "Copyright 2013, NCBS Bangalore"
-
-__credits__          = ["NCBS Bangalore", "Bhalla Lab"]
-__license__          = "GPL"
-__version__          = "1.0.0"
-__maintainer__       = "Dilawar Singh"
-__email__            = "dilawars@ncbs.res.in"
-__status__           = "Development"
-
-
-class DynamicObject:
-    def __init__(self):
-        pass
-
-    def __init__(self, name):
-        setattr(self, 'name', name)
diff --git a/python/libmumbl/core/loader.py b/python/libmumbl/core/loader.py
deleted file mode 100644
index 77743abcc56350a552cc1a599a205ad616ef064d..0000000000000000000000000000000000000000
--- a/python/libmumbl/core/loader.py
+++ /dev/null
@@ -1,9 +0,0 @@
-"""
-File: loader.py
-Author: Dilawar Singh
-Created on: 2013-11-16
-Description:
-
-    This file takes care of loading moose models into moose.
-"""
-
diff --git a/python/libmumbl/core/methods.py b/python/libmumbl/core/methods.py
deleted file mode 100644
index eab2a0cfca595c3ea62540a898169e5b75d00b12..0000000000000000000000000000000000000000
--- a/python/libmumbl/core/methods.py
+++ /dev/null
@@ -1,8 +0,0 @@
-"""
-File: methods.py
-Author: Dilawar Singh
-Created on: 2013-11-26
-Description: 
-
-"""
-
diff --git a/python/libmumbl/core/stimulus.py b/python/libmumbl/core/stimulus.py
deleted file mode 100644
index f10879d5ec58a6119cecb201bd26f99499c3cfd2..0000000000000000000000000000000000000000
--- a/python/libmumbl/core/stimulus.py
+++ /dev/null
@@ -1,194 +0,0 @@
-"""
-File: stimulus.py
-Author: Dilawar Singh
-Created on: 2013-11-25
-Description: generates stimuous
-"""
-
-import random
-import numpy as np
-
-def countSpikes(spikeArray):
-    count = 0
-    for i in spikeArray:
-        if i == True:
-            count += 1
-    return count
-
-def generateSpikeTrainPoission(frequency, dt=1e-3, simTime=100e-3
-                               , refractoryPeriod=1e-3
-                               ):
-    """
-    Generate a Poission spike train.
-
-    All units are in SI.
-
-    @return:  A numpy array of time when there is a spike.
-
-    @raise e:  Description
-    """
-
-    frequency = float(frequency)
-
-    def checkIfRefractoryPeriodIsViolated(simArray):
-        """
-        Local function to check if refractory period is violated.
-        """
-        deadPeriod = int(refractoryPeriod / dt)
-        indicesOfViolation = []
-        for i in range(simArray.size - deadPeriod):
-            if simArray[i] == True:
-                for j in range(1, deadPeriod+1):
-                    if simArray[i+j] == True:
-                        indicesOfViolation.append((i, i+j))
-        return indicesOfViolation
-
-
-    def fixRefractoryViolation(simArray):
-        """
-        Fix violation of refractory period, if any. We are just deleting the
-        spike. Can't think of a fast solution.
-        """
-        deadPeriod = int(refractoryPeriod / dt)
-        for i in range(simArray.size - deadPeriod):
-            if simArray[i] == True:
-                for j in range(1, deadPeriod+1):
-                    if simArray[i+j] == True:
-                        simArray[i+j] = False
-        return simArray
-
-
-    arraySize = int(simTime/dt)
-    # Initialize array to hold absense or presence of spike. By default there is
-    # no spike.
-    simArray = np.zeros(arraySize, dtype=np.bool_)
-    stepSize = dt * frequency
-    for i in range(arraySize):
-        # generate a random number between 0 and 1 and check if it is larger
-        # than (frequency*dt)/1000 (sec)
-        n = random.random()
-        if n < stepSize:
-            simArray[i] = True
-    # If refractory period is given then shift invalid firing to next location.
-    simArray = fixRefractoryViolation(simArray)
-    # We need to return only time on which there is a spike.
-    eventArray = np.array([], dtype=np.float_)
-    for i in range(simArray.size):
-        if simArray[i] == True:
-            eventArray = np.append(eventArray, i*dt)
-    return eventArray
-
-
-"""
-
-
-Following functions create two time tables.  #1 is filled with entries in a
-numpy array and #2 is filled from a text file containing the event times.
-
-The `state` field of #1, which becomes 1 when an event occurs and 0
-otherwise, is recorded.
-
-On the other hand, #2 is connected to a synapse (in a SynChan element)
-to demonstrate artificial spike event generation.
-
-"""
-
-import numpy as np
-
-simdt = 1e-3
-simtime = 100
-
-def generate_poisson_times(rate=20, simtime=100, seed=1):
-    """Generate Poisson spike times using `rate`. Use `seed` for seeding
-    the numpy rng"""
-    np.random.seed(seed) # ensure repeatability
-    isi = np.random.exponential(rate, int(simtime/rate))
-    # The stimulus times are the cumulative sum of the inter-stimulus intervals.
-    stimtimes = np.cumsum(isi)
-    # Select only stimulus times that are within simulation time -
-    # this may leave out some possible stimuli at the end, but the
-    # exoected number of Poisson events within simtime is
-    # simtime/rate.
-    stimtimes = stimtimes[stimtimes < simtime]
-    return stimtimes
-
-def timetable_nparray(simtime=100):
-    """Create a time table and populate it with numpy array. The `vec`
-    field in a Table can be directly assigned a sequence to fill the
-    table entries.
-
-    """
-    times = generate_poisson_times(rate=20, simtime=simtime, seed=1)
-    model = moose.Neutral('/model')
-    tt = moose.TimeTable('%s/tt_array' % (model.path))
-    tt.vec = times
-    return tt, times,
-
-def timetable_file(filename='timetable.txt', simtime=100):
-    """Create a TimeTable and populate it from file specified by
-    `filename`. If `filename` does not exist, a file of the same name is
-    created and a random series of spike times is saved in it"""
-    if not os.access(filename, os.R_OK):
-        times = generate_poisson_times(rate=10, simtime=simtime, seed=1)
-        np.savetxt(filename, times)
-    model = moose.Neutral('/model')
-    tt = moose.TimeTable('%s/tt_file' % (model.path))
-    tt.filename = filename
-    return tt, np.loadtxt(filename),
-
-def timetable_demo():
-
-    tt_array, sp_array = timetable_nparray()
-    print(sp_array)
-    tt_file, sp_file = timetable_file()
-    # Create a synchan inside a compartment to demonstrate how to use
-    # TimeTable to send artificial spike events to a synapse.
-    comp = moose.Compartment('/model/comp')
-    comp.Em = -60e-3
-    comp.Rm = 1e9
-    comp.Cm = 1e-12
-    synchan = moose.SynChan('/model/comp/synchan')
-    synchan.Gbar = 1e-6
-    synchan.Ek = 0.0
-    moose.connect(synchan, 'channel', comp, 'channel')
-    synchan.synapse.num = 1
-    moose.connect(tt_file, 'event', moose.element(synchan.path + '/synapse'), 'addSpike')
-    # Data recording: record the `state` of the time table filled
-    # using array.
-    data = moose.Neutral('/data')
-    tab_array = moose.Table('/data/tab_array')
-    moose.connect(tab_array, 'requestData', tt_array, 'get_state')
-    # Record the synaptic conductance for the other time table, which
-    # is filled from a text file and sends spike events to a synchan.
-    tab_file = moose.Table('/data/tab_file')
-    moose.connect(tab_file, 'requestData', synchan, 'get_Gk')
-
-    # Scheduling
-    moose.setClock(0, simdt)
-    moose.setClock(1, simdt)
-
-    # Using clocks
-    moose.useClock(1, '/model/##[ISA=Compartment]', 'init')
-    moose.useClock(1, '/model/##,/data/##', 'process')
-    moose.useClock(0, '/neuroml/cells/##', 'process')
-    moose.reinit()
-    moose.start(simtime)
-
-    # Plotting
-    pylab.subplot(2,1,1)
-    pylab.plot(sp_array, np.ones(len(sp_array)), 'rx', label='spike times from numpy array')
-    pylab.plot(np.linspace(0, simtime, len(tab_array.vec)), tab_array.vec, 'b-', label='TimeTable state')
-    pylab.legend()
-    pylab.subplot(2,1,2)
-    pylab.plot(sp_file, np.ones(len(sp_file)), 'rx', label='spike times from file')
-    pylab.plot(np.linspace(0, simtime, len(tab_file.vec)), tab_file.vec*1e6, 'b-', label='Syn Gk (uS)')
-    pylab.legend()
-    pylab.show()
-
-if __name__ == '__main__':
-    import moose
-    import os
-    import pylab
-    timetable_demo()
-
-
diff --git a/python/libmumbl/core/types.py b/python/libmumbl/core/types.py
deleted file mode 100644
index 272ae847cf3c4969cdd7a24e82033bc6733f73cb..0000000000000000000000000000000000000000
--- a/python/libmumbl/core/types.py
+++ /dev/null
@@ -1,78 +0,0 @@
-
-
-"""types.py: Implement some data-types.
-
-Last modified: Tue Jan 07, 2014  10:58AM
-
-"""
-    
-__author__           = "Dilawar Singh"
-__copyright__        = "Copyright 2013, NCBS Bangalore"
-__credits__          = ["NCBS Bangalore", "Bhalla Lab"]
-__license__          = "GPL"
-__version__          = "1.0.0"
-__maintainer__       = "Dilawar Singh"
-__email__            = "dilawars@ncbs.res.in"
-__status__           = "Development"
-
-class DoubleDict:
-    '''This is a double dict. It maps keys to values and values to keys.
-    '''
-    def __init__(self):
-        self.k = dict()
-        self.v = dict()
-
-    def __str__(self):
-        txt = []
-        for k in self.k:
-            if k == self.v[self.k.get(k, None)]:
-                txt.append(u'{} <-> {}'.format(k, self.k[k]))
-            else:
-                raise UserWarning, "Duplicate Entries: {} {}".format(
-                        self.k
-                        , self.v
-                        )
-        return '{' + ', '.join(txt) + '}'
-
-
-
-    def insert(self, key, value):
-        if self.k.get(key, 0) != value:
-            self.k[key] = value
-            self.v[value] = key
-        else:
-            self.v[value] = key
-
-    def insertUniqueVal(self, key):
-        self.k[key] = self.k.get(key, self.k.__len__() + 1)
-        self.v[self.k[key]] = key
-        assert len(set(self.k.values())) == len(self.k.values()), self.k.values()
-
-    def get(self, key, dictId=-1, default=None):
-        if dictId == 0:  # Fetch from key dict k
-            return self.k.get(key, default)
-        elif dictId == 1: # Fetch from key dict v
-            return self.v.get(key, default)
-
-        # Else query both
-        if self.k.get(key, None) is not None:
-            return self.k[key]
-        elif self.v.get(key, None) is not None:
-            return self.v[key]
-        else:
-            return default
-    
-    def get0(self, key, default=None):
-        return self.get(key, 0, default)
-
-    def get1(self, key, default=None):
-        return self.get(key, 1, default)
-
-
-if __name__ == "__main__":
-    a = DoubleDict()
-    b = ['Ka', 'Ca', 'Na', 'Ca', 'Fe']
-    for s in b:
-        a.insertUniqueVal(s)
-
-    print(a)
diff --git a/python/libmumbl/docs/config.pandoc b/python/libmumbl/docs/config.pandoc
deleted file mode 100644
index 349653d918442f5dcbbbcf99979e667ef897a023..0000000000000000000000000000000000000000
--- a/python/libmumbl/docs/config.pandoc
+++ /dev/null
@@ -1,73 +0,0 @@
-% About config.xml
-% Dilawar Singh
-
-This document describe `config.xml` file. This configure moose simulator and
-tell it what and how to plot.
-
-    
-In <element>, `cell_name` are useless, we use population and their instance id
-to search for a cell. Once the cell is found, appropriate messages are setup
-inside moose to record the simulation data.
-
-
-## Example
-```xml
-<!-- Write your simulation specific settings here. -->
-<moose elec_path='/neuroml/electrical' simulate='true' runtime="0.6" save_path='./figs'>
-    <global sim_dt="1e-3" plot_dt="1e-3" sim_method="hsolve" />
-
-    <!-- This setup recording settings for soma. Each type of element should
-        be contained in <element> </element> tag. In nutshell, we write the group
-        of variable first then we write its individual details.
-    -->
-
-    <!-- If single_plot is true then plot all plots in one figure -->
-    <element type="soma" population="granuleGroup"  instance_id="0">
-        <record type="table" file_name="figs/granule.eps">
-            <!--
-                 We should be able to form the following from this XML.
-                 somaVm = moose.setupTable(
-                        'somaVm'
-                        , moose.Compartment(parentPath+'/'+path)
-                        , 'Vm'
-                     )
-                prefixed_by_element, if not specified, will be treated as true.
-            -->
-            <variable name="Vm">
-                <target_in_simulator type="Compartment" path="Soma(0)"
-                     prefixed_by_element="true" />
-                 <plot plot="true" output="" plot_args="">
-                    <label x="Time" y="Soma Vm (V)" />
-                </plot>
-            </variable>
-            <variable name="Cm">
-                <target_in_simulator type="Compartment" path="Soma(0)/data/Cm" />
-                <plot output="">
-                    <label x="Time" y="Soma(0)/data/Cm" title="" />
-                </plot>
-            </variable>
-        </record>
-    </element>
-    <element type="soma" population="cellB"  instance_id="0">
-        <record type="table" single_plot="true" file_name="figs/purkinje.eps">
-            <!--
-                 This should translate to following in moose. 
-
-                 somaVm = moose.setupTable(
-                        'somaVm'
-                        , moose.Compartment(parentPath+'/'+path)
-                        , 'Vm'
-                     )
-                prefixed_by_element, if not specified, will be treated as true.
-            -->
-            <variable name="Vm">
-                <target_in_simulator type="Compartment" path="Soma(0)"
-                     prefixed_by_element="true" />
-                 <plot plot="true" output="" plot_args="">
-                    <label x="Time" y="Soma Vm (V)" />
-                </plot>
-            </variable>
-        </record>
-    </element>
-</moose>
-```
diff --git a/python/libmumbl/docs/mumbl.pandoc b/python/libmumbl/docs/mumbl.pandoc
deleted file mode 100644
index c16233cdcc65f27371fd063a277702d663c3bdb5..0000000000000000000000000000000000000000
--- a/python/libmumbl/docs/mumbl.pandoc
+++ /dev/null
@@ -1,140 +0,0 @@
-% Multiscale Modeling in Biology, Language
-% Dilawar dilawars@ncbs.res.in
-
-## Scope
-
-This document describes the format of MuMBL and its uses with moose simulator.
-
-## Format
-
-The general structure of MuMBL is following.
-
-```xml
-<?xml version="1.0"?>
-<mumbl>
-    <global elec_dt="50e-5" chem_dt="50e-5"/>
-    list of <model>
-    list of <domain>
-```
-
-#### <model> element
-
-Its looks like following 
-
-```xml
-<model id="3" 
-    domain_type="chemical" 
-    model_type="miscellenous"
-    lad_using_external_script="false"
-    loader_script="proto8.py" 
-    diff_length="20e-6" >
-    <compartments geometry='cylinder'>
-        <compartment id="1">
-            <pool species="Ca" conc="1e-3" />
-            <pool species="Na" conc="1e-16" />
-        </compartment>
-        <compartment id="2">
-            <pool species="K" conc="1e-10" />
-        </compartment>
-        <compartment path="" id="3" />
-    </compartments>
-</model>
-```
-
-### Domain element 
-
-```xml
-    <domain population="cellB" 
-        segment="Soma" 
-        instance_id="0"
-        >
-        <mapping direction="in" type="one_to_one" >
-            <source type="chemical" species="Ca" compartment_id = "1" >
-                <relation input="conc" output="Vm">
-                    <scale>1.5e24</scale>
-                    <offset>1e-16</offset>
-                </relation>
-            </source>
-        </mapping>
-    </domain>
-<
-```
-
-## Example 
-
-```
-<?xml version="1.0"?>
-<!--
-    All comments by : Dilawar, dilawars@ncbs.res.in
-This is the main top-level XML file to do multiscale modelling.
-    We parse it after mapping neuroML to moose.
- -->
-<mumbl>
-
-    <!-- 
-        Locals can override them.
-    -->
-    <global elec_dt="50e-5" chem_dt="50e-5"/>
-
-    <!-- This model is not loaded by moose. We have to run an external script to
-        load it.
-
-        TODO: For moose, we should not use an external script.
-        if load_using_external_script is false then do not use 'loader_script'
-        attribute.
-
-        Sub-element comapatments contains the compartment in which this model 
-        should be injected.
-    -->
-
-    <model id="3" 
-        domain_type="chemical" 
-        model_type="miscellenous"
-        lad_using_external_script="false"
-        loader_script="proto8.py" 
-        diff_length="20e-6" >
-        <compartments geometry='cylinder'>
-            <compartment id="1">
-                <pool species="Ca" conc="1e-3" />
-                <pool species="Na" conc="1e-16" />
-            </compartment>
-            <compartment id="2">
-                <pool species="K" conc="1e-10" />
-            </compartment>
-            <compartment path="" id="3" />
-        </compartments>
-    </model>
-
-    <!-- Here is how a sbml model is integrated -->
-    <model id="1"
-        domain_type="chemical"
-        model_type="sbml"
-        file_path="chem_model_sbml.xml" />
-
-    <!-- Here are mappings from compartment to compartment. -->
-    <!-- if mapping_type is source and this compartment influence others, if it
-        is target than this compartment gets influenced by other compartments.
-    -->
-
-    <!-- id is moose like path, it can influence either a single compartment of
-        a group of compartments depending on the nature of paths.
-        TODO: It should be more generic than this.
-
-        If electrical model was speficied in NeuroML then we can make use of 
-        paths
-    -->
-    <domain population="cellB" 
-        segment="Soma" 
-        instance_id="0"
-        >
-        <mapping direction="in" type="one_to_one" >
-            <source type="chemical" species="Ca" compartment_id = "1" >
-                <relation input="conc" output="Vm">
-                    <scale>1.5e24</scale>
-                    <offset>1e-16</offset>
-                </relation>
-            </source>
-        </mapping>
-    </domain>
-</mumbl>
-```
diff --git a/python/libmumbl/figs/topology.dot b/python/libmumbl/figs/topology.dot
deleted file mode 100644
index 62d6068492c462fa6a226badb89563eb9506c9e2..0000000000000000000000000000000000000000
--- a/python/libmumbl/figs/topology.dot
+++ /dev/null
@@ -1,96 +0,0 @@
-digraph G {
-	concentrate=true
-	neuroml -> cells
-	neuroml -> cells -> cellB
-	neuroml -> cells -> cellB -> Soma0
-	neuroml -> cells -> cellB -> mainAxon1
-	neuroml -> cells -> cellB -> Axon_12
-	neuroml -> cells -> cellB -> Axon_23
-	neuroml -> cells -> cellB -> Axon_34
-	neuroml -> cells -> cellB -> Axon_45
-	neuroml -> cells -> cellB -> Axon_56
-	neuroml -> cells -> cellB -> Axon_67
-	neuroml -> cells -> cellA
-	neuroml -> cells -> cellA -> Soma0
-	neuroml -> cells -> cellA -> mainAxon1
-	neuroml -> cells -> cellA -> axon12
-	neuroml -> cells -> cellA -> axon23
-	neuroml -> cells -> cellA -> root4
-	neuroml -> cells -> cellA -> mainDend15
-	neuroml -> cells -> cellA -> mainDend26
-	neuroml -> cells -> cellA -> mainDend37
-	neuroml -> cells -> cellA -> Dend_48
-	neuroml -> cells -> cellA -> Dend_59
-	neuroml -> cells -> cellA -> Dend_610
-	neuroml -> cells -> cellA -> Dend_711
-	neuroml -> cells -> cellA -> Dend_812
-	neuroml -> cells -> cellA -> Dend_913
-	neuroml -> cells -> cellA -> Dend_1014
-	neuroml -> cells -> cellA -> Dend_1115
-	neuroml -> cells -> cellA -> Dend_1216
-	neuroml -> cells -> cellA -> Dend_1317
-	neuroml -> cells -> cellA -> Dend_1418
-	neuroml -> cells -> cellA -> Dend_1519
-	neuroml -> cells -> cellA -> Dend_1620
-	neuroml -> cells -> cellA -> Dend_1721
-	neuroml -> cells -> cellA -> Dend_1822
-	neuroml -> cells -> cellA -> Dend_1923
-	neuroml -> cells -> cellA -> Dend_2024
-	neuroml -> cells -> cellA -> Dend_2125
-	neuroml -> cells -> cellA -> Dend_2226
-	neuroml -> cells -> cellA -> Dend_2327
-	neuroml -> cells -> cellA -> Dend_2428
-	neuroml -> cells -> cellA -> Dend_2529
-	neuroml -> cells -> cellA -> Dend_2630
-	neuroml -> cells -> cellA -> Dend_2731
-	neuroml -> cells -> cellA -> Dend_2832
-	neuroml -> cells -> cellA -> Dend_2933
-	neuroml -> cells -> cellA -> Dend_3034
-	neuroml -> cells -> cellA -> Dend_3135
-	neuroml -> cells -> cellA -> Dend_3236
-	neuroml -> cells -> cellA -> Dend_3337
-	neuroml -> cells -> cellA -> Dend_3438
-	neuroml -> cells -> cellA -> Dend_3539
-	neuroml -> cells -> cellA -> Dend_3640
-	neuroml -> cells -> cellA -> Dend_3741
-	neuroml -> cells -> cellA -> Dend_3842
-	neuroml -> cells -> cellA -> Dend_3943
-	neuroml -> cells -> DoubExpSyn
-	neuroml -> cells -> DoubExpSyn -> synapse0
-	neuroml -> cells -> DoubExpSyn -> graded
-	neuroml -> cells -> DoubExpSyn -> mgblock
-	neuroml -> cells -> cellB -> Soma0 -> DoubExpSyn
-	neuroml -> cells -> cellB -> Soma0 -> DoubExpSyn -> synapse0
-	neuroml -> cells -> cellB -> Soma0 -> DoubExpSyn -> graded
-	neuroml -> cells -> cellB -> Soma0 -> DoubExpSyn -> mgblock
-	neuroml -> cells -> cellA -> mainAxon1 -> DoubExpSyn_spikegen
-	neuroml -> electrical
-	neuroml -> electrical -> PulseGen
-	neuroml -> electrical -> PulseGen -> SampleIClamp
-	neuroml -> electrical -> iClamp
-	neuroml -> electrical -> iClamp -> SampleIClamp
-	mumbl -> Chemical
-	mumbl -> Electrical
-	mumbl -> Adaptor
-	mumbl -> Chemical -> Compartment
-	mumbl -> Chemical -> Compartment -> 1
-	mumbl -> Chemical -> Compartment -> 1 -> Ca
-	mumbl -> Chemical -> Compartment -> 1 -> Na
-	mumbl -> Chemical -> Compartment -> 2
-	mumbl -> Chemical -> Compartment -> 2 -> K
-	mumbl -> Chemical -> Compartment -> 3
-	mumbl -> Chemical -> Compartment -> calcium
-	mumbl -> Chemical -> Compartment -> calcium -> mesh0
-	mumbl -> Chemical -> Compartment -> calcium -> boundary0
-	mumbl -> Chemical -> Compartment -> calcium -> ca
-	mumbl -> Chemical -> Compartment -> calcium -> stoich
-	mumbl -> Chemical -> Compartment -> calcium -> stoich -> junction0
-	neuroml -> cells -> cellB -> Soma0 -> Vm
-	Tables -> somaVm
-	Tables -> somaVm -> table0
-	neuroml -> cells -> cellB -> Soma0 -> Cm
-	Tables -> somaCm
-	Tables -> somaCm -> table0
-	neuroml -> cells -> cellB -> solve
-	neuroml -> cells -> cellA -> solve
-}
\ No newline at end of file
diff --git a/python/libmumbl/helper/__init__.py b/python/libmumbl/helper/__init__.py
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/python/libmumbl/helper/graph_methods.py b/python/libmumbl/helper/graph_methods.py
deleted file mode 100644
index 50c400ebed26d1b4c45629355f71d1a27a85fc87..0000000000000000000000000000000000000000
--- a/python/libmumbl/helper/graph_methods.py
+++ /dev/null
@@ -1,79 +0,0 @@
-
-
-__author__  = "Dilawar Singh <dilawars@ncbs.res.in>"
-
-__log__     = """
-
-
-"""
-
-def segGrp2Color(grpName, grps):
-    """
-    Convert a  segmenet group name to an appropriate color.
-    """
-    index = 1
-    for i in grps:
-        if i != grpName:
-            index += 1
-        else:
-            break
-    level = format((index * 16777215)/len(grps), '06x')
-    return "color=\"#"+level+"\""
-
-def attachToNodesInGroup(cellG, groups, pName, pValue):
-    """
-    Attach a key=vlaue pair to node; these nodes belong to certain groups.
-    """
-    for g in groups:
-        for n in cellG.nodes():
-            if g in cellG.node[n]['belongsTo']:
-                cellG.node[n][pName] = pValue
-
-
-def write_dot(g, filename):
-    """
-    Write this graph to a graphviz file.
-    """
-    dotFile = []
-    dotFile.append("digraph moose {")
-    dotFile.append("dim=3")
-    #dotFile.append("concentrate=True")
-    if g.number_of_nodes() > 100:
-        dotFile.append("node[fixedsize=true,width=0.2,height=0.2]")
-    #dotFile.append("node[shape=box]")
-    segmentGroups = g.graph['gProp']
-    i = 0
-    for n in g.nodes():
-        i += 1
-        nodeLabel = "[label=\"\"".format(i)
-        if 'proximal' in g.node[n].keys():
-            x = (float(g.node[n]['proximal'].get('x')) + float(g.node[n]['distal'].get('x')))/2
-            y = (float(g.node[n]['proximal'].get('y')) + float(g.node[n]['distal'].get('y')))/2
-            z = (float(g.node[n]['proximal'].get('z')) + float(g.node[n]['distal'].get('z')))/2
-            nodeLabel += "pos=\"{0},{1},{2}!\"".format(x,y,z)
-
-        # color the segment groups
-        if g.node[n]['color']:
-            nodeLabel += ",style=filled,color=\""+g.node[n]['color']+"\""
-        segG = g.node[n].get('segmentGroup')
-        if segG:
-            colorName = segGrp2Color(segG, g.graph['gProp']['segmentGroup'])
-            nodeLabel += "style=filled,"+colorName+","
-
-        nodeLabel += "]"
-        dotFile.append(g.node[n]['label'] + " " + nodeLabel)
-    for (f, t) in g.edges():
-        edge = g.node[f]['label'] + " -> " + g.node[t]['label']
-        edge += " ["
-        if 'synapse' in g.edge[f][t].keys():
-            # color this edge and make it look like a synapse
-            edge += " label=\"{0}\",".format(g.edge[f][t]['id'])
-            edge += "color=blue,style=dotted,"
-        edge += "]"
-        dotFile.append(edge)
-
-    # End the file
-    dotFile.append("}")
-    txt = "\n".join(dotFile)
-    with open(filename, "w") as outFile:
-        outFile.write(txt)
diff --git a/python/libmumbl/helper/moose_methods.py b/python/libmumbl/helper/moose_methods.py
deleted file mode 100644
index c5b0cb8f610b8ef924be8378756a37717ae28d17..0000000000000000000000000000000000000000
--- a/python/libmumbl/helper/moose_methods.py
+++ /dev/null
@@ -1,192 +0,0 @@
-
-
-"""moose_methods.py:  Some helper function related with moose to do multiscale
-modelling.
-
-Last modified: Thu Jun 05, 2014  01:20AM
-
-"""
-    
-__author__           = "Dilawar Singh"
-__copyright__        = "Copyright 2013, NCBS Bangalore"
-__credits__          = ["NCBS Bangalore", "Bhalla Lab"]
-__license__          = "GPL"
-__version__          = "1.0.0"
-__maintainer__       = "Dilawar Singh"
-__email__            = "dilawars@ncbs.res.in"
-__status__           = "Development"
-
-import re
-import os
-import moose
-import debug.debug as debug
-
-nameSep = '_'
-
-def toFloat(string):
-    if type(string) == float:
-        return string 
-    elif type(string) == str:
-        return stringToFloat(string)
-    else:
-        raise RuntimeError("Converting type %s to float" % type(str))
-
-def commonPath(pathA, pathB):
-    ''' Find common path at the beginning of two paths. '''
-    a = pathA.split('/')
-    b = pathB.split('/')
-    common = []
-    for (i, p) in enumerate(a):
-        if a[i] == b[i]: 
-            common.append(p)
-        else: 
-            return '/'.join(common)
-    return '/'.join(common)
-
-def moosePath(baseName, append):
-    """ 
-    Append instance index to basename
-
-    TODO: Ideally - should be replace with [ and ]
-
-    """
-    if append.isdigit():
-        if len(nameSep) == 1:
-            return baseName + nameSep + append 
-        elif len(nameSep) == 2:
-            return baseName + nameSep[0] + append + nameSep[1]
-        else:
-            raise UserWarning, "Not more than 2 characters are not supported"
-    else:
-        return "{}/{}".format(baseName, append)
-
-
-def splitComparmentExpr(expr):
-    """ Breaks compartment expression into name and id.
-    """
-    if len(nameSep) == 1:
-        p = re.compile(r'(?P<name>[\w\/\d]+)\{0}(?P<id>\d+)'.format(nameSep[0]))
-    else:
-        # We have already verified that nameSep is no longer than 2 characters.
-        a, b = nameSep 
-        p = re.compile(r'(?P<name>[\w\/\d]+)\{0}(?P<id>\d+)\{1}'.format(a, b))
-    m = p.match(expr)
-    assert m.group('id').isdigit() == True
-    return m.group('name'), m.group('id')
-
-
-
-def getCompartmentId(compExpr):
-    """Get the id of compartment.
-    """
-    return splitComparmentExpr(compExpr)[1]
-
-def getCompName(compExpr):
-    """Get the name of compartment.
-    """
-    return splitComparmentExpr(compExpr)[0]
-
-def stringToFloat(text):
-    text = text.strip()
-    if not text:
-        return 0.0
-    try:
-        val = float(text)
-        return val
-    except Exception:
-        raise UserWarning, "Failed to convert {0} to float".format(text)
-
-
-def dumpMoosePaths(pat, isRoot=True):
-    ''' Path is pattern '''
-    moose_paths = getMoosePaths(pat, isRoot)
-    return "\n\t{0}".format(moose_paths)
-
-def getMoosePaths(pat, isRoot=True):
-    ''' Return a list of paths for a given pattern. '''
-    if type(pat) != str:
-        pat = pat.path
-        assert type(pat) == str
-    moose_paths = [x.path for x in moose.wildcardFind(pat)]
-    return moose_paths
-
-def dumpMatchingPaths(path, pat='/##'):
-    ''' return the name of path which the closely matched with given path 
-    pattern pat is optional.
-    '''
-    a = path.split('/')
-    start = a.pop(0)
-    p = moose.wildcardFind(start+'/##')
-    common = []
-    while len(p) > 0:
-        common.append(p)
-        start = start+'/'+a.pop(0)
-        p = moose.wildcardFind(start+'/##')
-        
-    if len(common) > 1:
-        matchedPaths = [x.getPath() for x in common[-1]]
-    else:
-        matchedPaths = []
-    return '\n\t'+('\n\t'.join(matchedPaths))
-
-
-def dumpFieldName(path, whichInfo='valueF'):
-    print(path.getFieldNames(whichInfo+'info'))
-
-def writeGraphviz(pat='/##', filename=None, filterList=[]):
-    '''This is  a generic function. It takes the the pattern, search for paths
-    and write a graphviz file.
-    '''
-    def ignore(line):
-        for f in filterList:
-            if f in line:
-                return True
-        return False
-
-    pathList = getMoosePaths(pat)
-    dot = []
-    dot.append("digraph G {")
-    dot.append("\tconcentrate=true")
-    for p in pathList:
-        if ignore(p):
-            continue
-        else:
-            p = re.sub('[]()]', '', p)
-            dot.append('\t'+' -> '.join(filter(None, p.split('/'))))
-    dot.append('}')
-    dot = '\n'.join(dot)
-    if not filename:
-        print(dot)
-    else:
-        with open(filename, 'w') as graphviz:
-            debug.printDebug("INFO"
-                    , "Writing topology to file {}".format(filename)
-                    )
-            graphviz.write(dot)
-    return 
-
-def setupTable(name, obj, qtyname, tablePath=None, threshold=None):
-    '''This is replacement function for moose.utils.setupTable
-
-    It stores qtyname from obj.
-    '''
-    assert qtyname[0].isupper(), "First character must be uppercase character"
-    debug.printDebug("DEBUG"
-            , "Setting up table for: {} -> get{}".format(obj.path, qtyname)
-            )
-    if tablePath is None:
-        tablePath = '{}/{}'.format(obj.path, 'data')
-        debug.printDebug("WARN"
-                , "Using default table path: {}".format(tablePath)
-                , frame = inspect.currentframe()
-                )
-    if not moose.exists(obj.path):
-        raise RuntimeError("Unknown path {}".format(obj.path))
-
-    moose.Neutral(tablePath)
-    table = moose.Table('{}/{}'.format(tablePath, name))
-    if threshold is None:
-        moose.connect(table, "requestOut", obj, "get{}".format(qtyname))
-    else:
-        raise UserWarning("TODO: Table with threshold is not implemented yet")
-    return table
diff --git a/python/libmumbl/helper/xml_methods.py b/python/libmumbl/helper/xml_methods.py
deleted file mode 100644
index d3fb63948d8bd15db1e8bb5c266607c99e0d3204..0000000000000000000000000000000000000000
--- a/python/libmumbl/helper/xml_methods.py
+++ /dev/null
@@ -1,35 +0,0 @@
-
-
-__author__  = "Dilawar Singh <dilawars@ncbs.res.in>"
-
-__log__     = """
-
-    Methods to help parsing xml.
-
-"""
-import re
-import sys
-
-def elemExists(rootElem, nmExpr, path) :
-  elem = rootElem.xpath(nmExpr, name=path) 
-  if elem :
-    return True
-  else :
-    return False
-
-
-def getElement(rootElem, nmlExpr, path) :
-  elem = rootElem.xpath(nmlExpr, name=path) 
-  return elem
-
-def isTaggedWith(nmElem, tag) :
-  regex = re.compile(r"\{.+\}"+tag+'$')
-  m = regex.match(nmElem.tag)
-  if m : return True
-  else : return False
-
-def getTagName(nmTag) :
-  regex = re.compile(r"\{.+\}(?P<name>\w+)$")
-  m = regex.match(nmTag)
-  return m.group('name')
-
diff --git a/python/libmumbl/main.py b/python/libmumbl/main.py
deleted file mode 100755
index 38983da6f1069ceda0c7a3ebcce40783026a1b0a..0000000000000000000000000000000000000000
--- a/python/libmumbl/main.py
+++ /dev/null
@@ -1,56 +0,0 @@
-"""
-Copyright (C) 2014 Dilawar Singh
-
-This program is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program; if not, see <http://www.gnu.org/licenses/>.
-
-"""
-
-"""main.py: 
-
-Last modified: Sat Jan 18, 2014  05:01PM
-
-"""
-    
-__author__           = "Dilawar Singh"
-__copyright__        = "Copyright 2013, Dilawar Singh and NCBS Bangalore"
-__credits__          = ["NCBS Bangalore"]
-__license__          = "GNU GPL"
-__version__          = "1.0.0"
-__maintainer__       = "Dilawar Singh"
-__email__            = "dilawars@ncbs.res.in"
-__status__           = "Development"
-
-import os
-import sys
-import inspect
-from utility import xml_parser
-
-def parseMumbl(mumblFilePath):
-    """Parse MUMBL are return the ElementTree """
-    return xml_parser.parseWithoutValidation("mumbl", mumblFilePath)
-    
-
-def main():
-    # standard module for building a command line parser.
-    import argparse
-
-    # This section build the command line parser
-    argParser = argparse.ArgumentParser(description= 'Mutiscale modelling of neurons')
-    argParser.add_argument('--mumbl', metavar='mumbl', required = True, nargs = '+'
-        , help = 'Lanaguge to do multi-scale modelling in moose'
-        )
-    args = argParser.parse_args()
-
-if __name__ == '__main__':
-    main()
diff --git a/python/libmumbl/mumble_twocells.sh b/python/libmumbl/mumble_twocells.sh
deleted file mode 100755
index dfcc0f40b8e2d310075474b392bdc0a177ca15fa..0000000000000000000000000000000000000000
--- a/python/libmumbl/mumble_twocells.sh
+++ /dev/null
@@ -1,54 +0,0 @@
-#!/bin/bash
-set -e
-
-# Set pythonpath
-# If first argument is not "d" then normal execution else run inside python
-# debugger.
-
-version=1
-export PYTHONPATH=..
-projDir=./models/NeuroConstruct/two_cells
-projName=two_cells.nml
-nmlFile=$projDir/$projName
-if [ ! -f $nmlFile ]; then
-    echo "File $nmlFile is not found"
-    exit
-fi
-
-function runCode 
-{
-  $PYC main.py \
-    --nml $nmlFile \
-    --mumbl $projDir/mumbl.xml \
-    --config $projDir/config.xml 
-  #twopi -Teps graphs/moose.dot > graphs/topology.eps
-}
-
-function testPythonCode 
-{
-    pf=$1
-    echo "== $0 Checking .... $pf"
-    pylint -E $p
-
-}
-
-PYC=python
-if [ "$1" == "d" ]; then
-  PYC="gdb -ex r --args python2.7"
-  runCode
-elif [ "$1" == "c" ]; then 
-    FILES=$(find . -name "*.py" -type f)
-    for pf in $FILES; do
-        testPythonCode $pf
-    done
-else
-  PYC=python
-  runCode
-fi
-
-dotFile=./figs/topology.dot 
-if [ -f $dotFile ]; then
-    epsFile=${dotFile%.dot}.eps
-    echo "== $0" "Converting $dotFile -> $epsFile"
-    dot -Teps "$dotFile" > "$epsFile"
-fi
diff --git a/python/libmumbl/nml_parser/ChannelML.py b/python/libmumbl/nml_parser/ChannelML.py
deleted file mode 100644
index f07fbd422e8b48cce28a91f3e5fb3aa99348b88e..0000000000000000000000000000000000000000
--- a/python/libmumbl/nml_parser/ChannelML.py
+++ /dev/null
@@ -1,573 +0,0 @@
-# Description: class ChannelML for loading ChannelML from file or xml element
-# into MOOSE Version 1.0 by Aditya Gilra, NCBS, Bangalore, India, 2011 for
-# serial MOOSE Version 1.5 by Niraj Dudani, NCBS, Bangalore, India, 2012,
-# ported to parallel MOOSE Version 1.6 by Aditya Gilra, NCBS, Bangalore, India,
-# 2012, minor changes for parallel MOOSE Version 1.7 by Aditya Gilra, NCBS,
-# Bangalore, India, 2013, further support for NeuroML 1.8.1
-
-"""
-NeuroML.py is the preferred interface. Use this only if NeuroML L1,L2,L3 files
-are misnamed/scattered.  Instantiate ChannelML class, and thence use method:
-    readChannelMLFromFile(...) to load a standalone ChannelML file
-    (synapse/channel), OR readChannelML(...) / readSynapseML to load from an
-    xml.etree xml element (could be part of a larger NeuroML file).
-"""
-
-from xml.etree import cElementTree as ET
-import debug.debug as debug
-import string
-import os, sys
-import math
-import inspect
-
-import moose
-from moose.neuroml import utils
-import core.config as config
-
-class ChannelML:
-    """Loads channelML file. Base class. Inherited by NeuroML
-    """
-
-    def __init__(self, nml_params):
-        self.cml='http://morphml.org/channelml/schema'
-        self.libraryPath = config.libraryPath
-        self.nml_params = nml_params
-        temp = '{0}'.format(nml_params['temperature'])
-        if temp is None or len(temp) == 0:
-            self.temperature = 32.0
-            debug.printDebug("INFO"
-                    , "Using default temp of {0} C".format(self.temperature)
-                    )
-        else:
-            self.temperature = float(temp)
-            debug.printDebug("INFO"
-                    , "Using temperature {0}".format(self.temperature)
-                    )
-
-    def readChannelMLFromFile(self, _filename, _params={}):
-
-        """ specify params as a dict: e.g. temperature that you need to pass to
-        channels """
-
-        tree = ET.parse(_filename)
-        channelml_element = tree.getroot()
-
-        cts = channelml_element.findall('.//{'+self.cml+'}channel_type')
-        for channel in cts:
-            # ideally I should read in extra params from within the
-            # channel_type element and put those in also. Global params should
-            # override local ones.
-            self.readChannelML(channel
-                    , self.nml_params
-                    , channelml_element.attrib['units']
-                    )
-
-        syns = channelml_element.findall('.//{'+self.cml+'}synapse_type')
-        for synapse in syns:
-            self.readSynapseML(synapse,channelml_element.attrib['units'])
-
-
-        chics = channelml_element.findall('.//{'+self.cml+'}ion_concentration')
-        for ionConc in chics:
-            self.readIonConcML(ionConc,channelml_element.attrib['units'])
-
-   
-    def readSynapseML(self, synapseElement, units="SI units"):
-        # see pg 219 (sec 13.2) of Book of Genesis
-        if 'Physiological Units' in units:
-            Vfactor = 1e-3 # V from mV
-            Tfactor = 1e-3 # s from ms
-            Gfactor = 1e-3 # S from mS
-        elif 'SI Units' in units:
-            Vfactor = 1.0
-            Tfactor = 1.0
-            Gfactor = 1.0
-        else:
-            debug.printDebug("ERROR", "Wrong units {0}".format(units))
-            raise UserWarning, "Wrong value or parameter {0}".format(units)
-
-        # creates /library in MOOSE tree; elif present, wraps
-        # NOTE: This path is created by NeuroML now in __init__. Disabling,
-        # Dilawar Singh
-        #moose.Neutral(self.libraryPath+'')
-
-        if utils.neuroml_debug:
-            synName = synapseElement.attrib['name']
-            msg = "Loading synapse : %s into library ." % synName
-            debug.printDebug("INFO", msg)
-
-        self.mooseSynp = moose.SynChan(os.path.join(self.libraryPath
-                , synapseElement.attrib['name']))
-        doub_exp_syn = synapseElement.find('./{' + self.cml + '}doub_exp_syn')
-
-        self.mooseSynp.Ek = float(doub_exp_syn.attrib['reversal_potential']) \
-                * Vfactor
-        self.mooseSynp.Gbar = float(doub_exp_syn.attrib['max_conductance'])\
-                 * Gfactor
-        # seconds
-        self.mooseSynp.tau1 = float(doub_exp_syn.attrib['rise_time']) * Tfactor 
-        # second\s
-        self.mooseSynp.tau2 = float(doub_exp_syn.attrib['decay_time'])*Tfactor 
-
-        # The delay and weight can be set only after connecting a spike event
-        # generator.  delay and weight are arrays: multiple event messages can
-        # be connected to a single synapse
-        self.mooseSynp_graded = moose.Mstring(self.mooseSynp.path+'/graded')
-        self.mooseSynp_graded.value = 'False'
-        self.mooseSynp_mgblock = moose.Mstring(self.mooseSynp.path+'/mgblock')
-        self.mooseSynp_mgblock.value = 'False'
-
-    def readChannelML(self, channelElement, params={}, units="SI units"):
-        """Loads a single channel
-        """
-        # I first calculate all functions assuming a consistent system of units.
-        # While filling in the A and B tables, I just convert to SI.  Also
-        # convert gmax and Erev.
-        if 'Physiological Units' in units: 
-            # see pg 219 (sec 13.2) of Book of Genesis
-            Vfactor = 1e-3   # V from mV
-            Tfactor = 1e-3   # s from ms
-            Gfactor = 1e1    # S/m^2 from mS/cm^2
-            concfactor = 1e6 # Mol = mol/m^-3 from mol/cm^-3
-        elif 'SI Units' in units:
-            Vfactor = 1.0
-            Tfactor = 1.0
-            Gfactor = 1.0
-            concfactor = 1.0
-        else:
-            debug.printDebug("ERR"
-                    , "wrong units %s. Existing... " % units
-                    , frame = inspect.currentframe()
-                    )
-            raise UserWarning, "Unknown units"
-
-        # creates /library in MOOSE tree; elif present, wraps
-        channel_name = channelElement.attrib['name']
-        if utils.neuroml_debug:
-            msg = "Loading channel {} into {} ".format (channel_name,
-                    self.libraryPath)
-            debug.printDebug("INFO", msg)
-
-        IVrelation = channelElement.find(
-                './{'+self.cml+'}current_voltage_relation'
-                )
-        concdep = IVrelation.find('./{'+self.cml+'}conc_dependence')
-        cPath = os.path.join(self.libraryPath, channel_name)
-        if concdep is None:
-            channel = moose.HHChannel(cPath)
-        else:
-            channel = moose.HHChannel2D(cPath)
-
-        if IVrelation.attrib['cond_law'] == "ohmic":
-            channel.Gbar = float(IVrelation.attrib['default_gmax']) * Gfactor
-            channel.Ek = float(IVrelation.attrib['default_erev']) * Vfactor
-            channelIon = moose.Mstring(channel.path+'/ion')
-            channelIon.value = IVrelation.attrib['ion']
-            if concdep is not None:
-                channelIonDependency = moose.Mstring(
-                        channel.path + '/ionDependency'
-                        )
-                channelIonDependency.value = concdep.attrib['ion']
-
-        nernstnote = IVrelation.find('./{'+utils.meta_ns+'}notes')
-        if nernstnote is not None:
-            # the text in nernstnote is "Nernst,Cout=<float>,z=<int>"
-            nernst_params = nernstnote.text.split(',')
-            if nernst_params[0] == 'Nernst':
-                nernstMstring = moose.Mstring(channel.path+'/nernst_str')
-                nernstMstring.value = str(
-                        float(nernst_params[1].split('=')[1]) * concfactor
-                ) + ',' + str(int(nernst_params[2].split('=')[1]))
-
-        gates = IVrelation.findall('./{'+self.cml+'}gate')
-        if len(gates) > 3:
-            msg = "Sorry! Maximum x, y, and z (three) gates are possible in\
-                      MOOSE/Genesis"
-            debug.printDebug("ERR", msg, frame=inspect.currentframe())
-            raise UserWarning, "Bad value or parameter"
-           
-        # These are the names that MOOSE uses to create gates.
-        gate_full_name = [ 'gateX', 'gateY', 'gateZ' ] 
-
-        # if impl_prefs tag is present change VMIN, VMAX and NDIVS
-        impl_prefs = channelElement.find('./{'+self.cml+'}impl_prefs')
-        if impl_prefs is not None:
-            table_settings = impl_prefs.find('./{'+self.cml+'}table_settings')
-            # some problem here... disable
-            VMIN_here = float(table_settings.attrib['min_v'])
-            VMAX_here = float(table_settings.attrib['max_v'])
-            NDIVS_here = int(table_settings.attrib['table_divisions'])
-            dv_here = (VMAX_here - VMIN_here) / NDIVS_here
-        else:
-            # default VMIN, VMAX and dv are in SI convert them to current
-            # calculation units used by channel definition while loading into
-            # tables, convert them back to SI
-            VMIN_here = utils.VMIN/Vfactor
-            VMAX_here = utils.VMAX/Vfactor
-            NDIVS_here = utils.NDIVS
-            dv_here = utils.dv/Vfactor
-        offset = IVrelation.find('./{'+self.cml+'}offset')
-        if offset is None:
-            vNegOffset = 0.0
-        else:
-            vNegOffset = float(offset.attrib['value'])
-        self.parameters = []
-        for parameter in channelElement.findall('.//{'+self.cml+'}parameter'):
-            self.parameters.append((parameter.attrib['name']
-                        , float(parameter.attrib['value'])) 
-                    )
-
-        for num,gate in enumerate(gates):
-            # if no q10settings tag, the q10factor remains 1.0 if present but no
-            # gate attribute, then set q10factor if there is a gate attribute,
-            # then set it only if gate attrib matches gate name
-            self.q10factor = 1.0
-            self.gate_name = gate.attrib['name']
-            q10sets = IVrelation.findall('./{'+self.cml+'}q10_settings')
-            for q10settings in q10sets:
-                # self.temperature from neuro.utils
-                if 'gate' in list(q10settings.attrib.keys()):
-                    if q10settings.attrib['gate'] == self.gate_name:
-                        self.setQ10(q10settings)
-                        break
-                else:
-                    self.setQ10(q10settings)
-
-            # HHChannel2D crashing on setting Xpower!  temperamental! If you
-            # print something before, it gives cannot creategate from copied
-            # channel, else crashes Setting power first. This is necessary
-            # because it also initializes the gate's internal data structures as
-            # a side effect. Alternatively, gates can be initialized explicitly
-            # by calling HHChannel.createGate().
-            gate_power = float( gate.get( 'instances' ) )
-            if num == 0:
-                channel.Xpower = gate_power
-                if concdep is not None: channel.Xindex = "VOLT_C1_INDEX"
-            elif num == 1:
-                channel.Ypower = gate_power
-                if concdep is not None: channel.Yindex = "VOLT_C1_INDEX"
-            elif num == 2:
-                channel.Zpower = gate_power
-                if concdep is not None: channel.Zindex = "VOLT_C1_INDEX"
-
-            ## Getting handle to gate using the gate's path.
-            gate_path = os.path.join(channel.path, gate_full_name[ num ])
-            if concdep is None:
-                moosegate = moose.HHGate( gate_path )
-                # set SI values inside MOOSE
-                moosegate.min = VMIN_here*Vfactor
-                moosegate.max = VMAX_here*Vfactor
-                moosegate.divs = NDIVS_here
-                ## V.IMP to get smooth curves, else even with 3000 divisions
-                ## there are sudden transitions.
-                moosegate.useInterpolation = True
-            else:
-                moosegate = moose.HHGate2D( gate_path )
-
-            # If alpha and beta functions exist, make them here
-            for transition in gate.findall('./{'+self.cml+'}transition'):
-                # make python functions with names of transitions...
-                fn_name = transition.attrib['name']
-                # I assume that transitions if present are called alpha and beta
-                # for forwand backward transitions...
-                if fn_name in ['alpha','beta']:
-                    self.make_cml_function(transition, fn_name, concdep)
-                else:
-                    debug.printDebug("ERROR"
-                            , "Unsupported transition {0}".format(fn_name)
-                            )
-                    sys.exit()
-
-            time_course = gate.find('./{'+self.cml+'}time_course')
-            # tau is divided by self.q10factor in make_function() thus, it gets
-            # divided irrespective of <time_course> tag present or not.
-            if time_course is not None:
-                self.make_cml_function(time_course, 'tau', concdep)
-            steady_state = gate.find('./{'+self.cml+'}steady_state')
-            if steady_state is not None:
-                self.make_cml_function(steady_state, 'inf', concdep)
-
-            if concdep is None:
-                 ca_name = ''                        # no Ca dependence
-            else:
-                # Ca dependence
-                 ca_name = ','+concdep.attrib['variable_name']     
-
-            # Create tau() and inf() if not present, from alpha() and beta()
-            for fn_element,fn_name,fn_expr in [
-                    (time_course,'tau',"1/(alpha+beta)")
-                    , (steady_state,'inf',"alpha/(alpha+beta)")
-                    ]:
-                # put in args for alpha and beta, could be v and Ca dep.
-                expr_string = fn_expr.replace('alpha', 'self.alpha(v'+ca_name+')')
-                expr_string = expr_string.replace('beta', 'self.beta(v'+ca_name+')')
-                # if time_course/steady_state are not present, then alpha annd
-                # beta transition elements should be present, and fns created.
-                if fn_element is None:
-                    self.make_function(
-                            fn_name
-                            ,'generic'
-                            , expr_string = expr_string
-                            , concdep=concdep
-                            )
-
-            # non Ca dependent channel
-            if concdep is None:
-                # while calculating, use the units used in xml defn, while
-                # filling in table, I convert to SI units.
-                v0 = VMIN_here - vNegOffset
-                n_entries = NDIVS_here + 1
-                tableA = [0.0] * n_entries
-                tableB = [0.0] * n_entries
-                for i in range(n_entries):
-                    v = v0 + (i * dv_here)
-                    inf = self.inf(v)
-                    tau = self.tau(v)
-                    # convert to SI before writing to table
-                    # qfactor is already in inf and tau
-                    tableA[i] = (inf / tau) / Tfactor
-                    tableB[i] = (1.0 / tau) / Tfactor
-
-                moosegate.tableA = tableA
-                moosegate.tableB = tableB
-
-            ## Ca dependent channel
-            else:
-                # UNITS: while calculating, use the units used in xml defn,
-                # while filling in table, I convert to SI units.  Note here Ca
-                # units do not enter, but units of CaMIN, CaMAX and ca_conc in
-                # fn expr should match.
-                v = VMIN_here - vNegOffset
-                CaMIN = float(concdep.attrib['min_conc'])
-                CaMAX = float(concdep.attrib['max_conc'])
-                CaNDIVS = 100
-                dCa = (CaMAX-CaMIN)/CaNDIVS
-
-                # CAREFUL!: tableA = [[0.0]*(CaNDIVS+1)]*(NDIVS_here+1) will not
-                # work!  * does a shallow copy, same list will get repeated 200
-                # times!  Thus setting tableA[35][1] = 5.0 will set all rows,
-                # 1st col to 5.0!!!!
-                tableA = [[0.0]*(CaNDIVS+1) for i in range(NDIVS_here+1)]
-                tableB = [[0.0]*(CaNDIVS+1) for i in range(NDIVS_here+1)]
-                for i in range(NDIVS_here + 1):
-                    Ca = CaMIN
-                    for j in range(CaNDIVS + 1):
-                        inf = self.inf(v, Ca)
-                        tau = self.tau(v, Ca)
-                        # convert to SI (Tfactor) before writing to table
-                        # qfactor is already in inf and tau
-                        tableA[i][j] = (inf / tau) / Tfactor
-                        tableB[i][j] = (1.0 / tau) / Tfactor
-                        Ca += dCa
-                    v += dv_here
-
-                # Presently HHGate2D doesn't allow the setting of tables as 2D
-                # vectors directly
-                #moosegate.tableA = tableA #moosegate.tableB = tableB
-
-                # Instead, I wrap the interpol2D objects inside HHGate2D and set
-                # the tables
-                moosegate_tableA = moose.Interpol2D(moosegate.path+'/tableA')
-
-                # set SI values inside MOOSE
-                moosegate_tableA.xmin = VMIN_here*Vfactor
-                moosegate_tableA.xmax = VMAX_here*Vfactor
-                moosegate_tableA.xdivs = NDIVS_here
-                #moosegate_tableA.dx = dv_here*Vfactor
-                moosegate_tableA.ymin = CaMIN*concfactor
-                moosegate_tableA.ymax = CaMAX*concfactor
-                moosegate_tableA.ydivs = CaNDIVS
-                #moosegate_tableA.dy = dCa*concfactor
-                moosegate_tableA.tableVector2D = tableA
-
-                moosegate_tableB = moose.Interpol2D(moosegate.path+'/tableB')
-                ## set SI values inside MOOSE
-                moosegate_tableB.xmin = VMIN_here*Vfactor
-                moosegate_tableB.xmax = VMAX_here*Vfactor
-                moosegate_tableB.xdivs = NDIVS_here
-                #moosegate_tableB.dx = dv_here*Vfactor
-                moosegate_tableB.ymin = CaMIN*concfactor
-                moosegate_tableB.ymax = CaMAX*concfactor
-                moosegate_tableB.ydivs = CaNDIVS
-                #moosegate_tableB.dy = dCa*concfactor
-                moosegate_tableB.tableVector2D = tableB
-
-    def setQ10(self, q10settings):
-       
-        if 'q10_factor' in list(q10settings.attrib.keys()):
-            expTemp = float(q10settings.attrib['experimental_temp'])
-            self.q10factor = float(q10settings.attrib['q10_factor']) ** (
-                        ( self.temperature - expTemp) /10.0
-                    )
-        elif 'fixed_q10' in list(q10settings.attrib.keys()):
-            self.q10factor = float(q10settings.attrib['fixed_q10'])
-
-
-    def readIonConcML(self, ionConcElement, units="SI units"):
-        if units == 'Physiological Units': 
-            # see pg 219 (sec 13.2) of Book of Genesis
-            Vfactor = 1e-3   # V from mV
-            Tfactor = 1e-3   # s from ms
-            Gfactor = 1e1    # S/m^2 from mS/cm^2
-            concfactor = 1e6 # mol/m^3 from mol/cm^3
-            Lfactor = 1e-2   # m from cm
-            Ifactor = 1e-6   # A from microA
-        else:
-            Vfactor = 1.0
-            Tfactor = 1.0
-            Gfactor = 1.0
-            concfactor = 1.0
-            Lfactor = 1.0
-            Ifactor = 1.0
-        # creates /library in MOOSE tree; elif present, wraps
-        moose.Neutral(self.libraryPath+'') 
-        ionSpecies = ionConcElement.find('./{'+self.cml+'}ion_species')
-        if ionSpecies is not None:
-            if not 'ca' in ionSpecies.attrib['name']:
-                msg = "Sorry, I cannot handle non-Ca-ion pools. Exiting..."
-                debug.printDebug("ERR", msg, frame=inspect.currentframe())
-                sys.exit(1)
-
-        capoolName = ionConcElement.attrib['name']
-        debug.printDebug("INFO"
-                , "Loading Ca pool {} into {}".format(capoolName
-                    , self.libraryPath)
-                )
-        caPool = moose.CaConc(self.libraryPath+'/'+capoolName)
-        poolModel = ionConcElement.find('./{'+self.cml+'}decaying_pool_model')
-        caPool.CaBasal = float(poolModel.attrib['resting_conc']) * concfactor
-        caPool.Ca_base = float(poolModel.attrib['resting_conc']) * concfactor
-
-        if 'decay_constant' in poolModel.attrib:
-            caPool.tau = float(poolModel.attrib['decay_constant']) * Tfactor
-        elif 'inv_decay_constant' in poolModel.attrib:
-            caPool.tau = 1.0 / float(poolModel.attrib['inv_decay_constant']) \
-                    * Tfactor
-
-        # Only one of pool_volume_info or fixed_pool_info should be present, but
-        # not checking
-        volInfo = poolModel.find('./{'+self.cml+'}pool_volume_info')
-        if volInfo is not None:
-            caPool.thick = float(volInfo.attrib['shell_thickness']) * Lfactor
-        fixedPoolInfo = poolModel.find('./{'+self.cml+'}fixed_pool_info')
-        if fixedPoolInfo is not None:
-            # Put in phi under the caPool, so that it can be used instead of
-            # thickness to set B (see section 19.2 in Book of Genesis)
-            caPool_phi = moose.Mstring(caPool.path+'/phi')
-            caPool_phi.value = str( float(fixedPoolInfo.attrib['phi']) \
-                    * concfactor/Ifactor/Tfactor )
-        # Put a high ceiling and floor for the Ca conc
-        #~ self.context.runG('setfield ' + caPool.path + ' ceiling 1e6')
-        #~ self.context.runG('setfield ' + caPool.path + ' floor 0.0')
-
-    def make_cml_function(self, element, fn_name, concdep=None):
-        fn_type = element.attrib['expr_form']
-        if fn_type in ['exponential','sigmoid','exp_linear']:
-            fn = self.make_function(
-                    fn_name
-                    , fn_type
-                    , rate=float(element.attrib['rate'])
-                    , midpoint=float(element.attrib['midpoint'])
-                    , scale=float(element.attrib['scale'] ) 
-                    )
-        elif fn_type == 'generic':
-            # OOPS! These expressions should be in SI units, since I converted
-            # to SI Ideally I should not convert to SI and have the user
-            # consistently use one or the other Or convert constants in these
-            # expressions to SI, only voltage and ca_conc appear!  NO! SEE
-            # ABOVE, for calculating values for tables, I use units specified in
-            # xml file, then I convert to SI while writing to MOOSE internal
-            # tables.
-            expr_string = element.attrib['expr']
-            if concdep is None: 
-                ca_name = ''                        # no Ca dependence
-            else: 
-                ca_name = ','+concdep.attrib['variable_name']     
-                # Ca dependence
-            expr_string = expr_string.replace('alpha', 'self.alpha(v'+ca_name+')')
-            expr_string = expr_string.replace('beta', 'self.beta(v'+ca_name+')')
-            fn = self.make_function(
-                    fn_name
-                    , fn_type
-                    , expr_string=expr_string
-                    , concdep=concdep 
-                    )
-        else:
-            debug.printDebug("ERR"
-                    , "Unsupported function type %s " % fn_type
-                    , frame=inspect.currentframe()
-                    )
-            sys.exit()
-
-    def make_function(self, fn_name, fn_type, **kwargs):
-        """ This dynamically creates a function called fn_name
-        If fn_type is exponential, sigmoid or exp_linear,
-            **kwargs is a dict having keys rate, midpoint and scale.
-        If fin_type is generic, **kwargs is a dict having key expr_string """
-
-        if fn_type == 'exponential':
-            def fn(self,v):
-                v = kwargs['rate'] * math.exp(
-                        (v - kwargs['midpoint']) / kwargs['scale']
-                        )
-                return v
-        elif fn_type == 'sigmoid':
-            def fn(self,v):
-                v = kwargs['rate'] / ( 
-                        1 + math.exp((v-kwargs['midpoint'])/kwargs['scale']) 
-                        )
-                return v
-        elif fn_type == 'exp_linear':
-            def fn(self,v):
-                if v-kwargs['midpoint'] == 0.0: return kwargs['rate']
-                else:
-                    return kwargs['rate'] * ( (v-kwargs['midpoint']) \
-                            / kwargs['scale']) \
-                            / ( 1 - math.exp(
-                                (kwargs['midpoint'] - v) / kwargs['scale']
-                                ) 
-                            )
-        elif fn_type == 'generic':
-            # python cannot evaluate the ternary operator ?:, so evaluate
-            # explicitly for security purposes eval() is not allowed any
-            # __builtins__ but only safe functions in utils.safe_dict and only
-            # the local variables/functions v, self
-            allowed_locals = {'self':self}
-            allowed_locals.update(utils.safe_dict)
-            def fn(self,v,ca=None):
-                expr_str = kwargs['expr_string']
-                allowed_locals['v'] = v
-                allowed_locals['celsius'] = self.temperature
-                allowed_locals['temp_adj_'+self.gate_name] = self.q10factor
-                for i,parameter in enumerate(self.parameters):
-                    allowed_locals[parameter[0]] = self.parameters[i][1]
-                if 'concdep' in kwargs:
-                    concdep = kwargs['concdep']
-                    # ca should appear as neuroML defined 'variable_name' to
-                    # eval()
-                    if concdep is not None:
-                        allowed_locals[concdep.attrib['variable_name']] = ca
-                if '?' in expr_str:
-                    condition, alternatives = expr_str.split('?',1)
-                    alternativeTrue, alternativeFalse = alternatives.split(':',1)
-                    if eval(condition,{"__builtins__":None},allowed_locals):
-                        val = eval(
-                                alternativeTrue
-                                , {"__builtins__":None}
-                                , allowed_locals
-                                )
-                    else:
-                        val = eval(
-                                alternativeFalse
-                                , {"__builtins__":None}
-                                , allowed_locals
-                                )
-                else:
-                    val = eval(expr_str, {"__builtins__" : None}, allowed_locals)
-                if fn_name == 'tau': 
-                    return val/self.q10factor
-                else: 
-                    return val
-
-        fn.__name__ = fn_name
-        setattr(self.__class__, fn.__name__, fn)
diff --git a/python/libmumbl/nml_parser/MorphML.py b/python/libmumbl/nml_parser/MorphML.py
deleted file mode 100644
index d6788a3ef3ffb5917f0e125ab769f0cc7248e903..0000000000000000000000000000000000000000
--- a/python/libmumbl/nml_parser/MorphML.py
+++ /dev/null
@@ -1,766 +0,0 @@
-"""
-
-Description: class MorphML for loading MorphML from file or xml element into
-MOOSE.
-
-NeuroML.py is the preferred interface. Use this only if NeuroML L1,L2,L3 files
-are misnamed/scattered.  Instantiate MorphML class, and thence use methods:
-readMorphMLFromFile(...) to load a standalone MorphML from file OR
-readMorphML(...) to load from an xml.etree xml element (could be part of a
-larger NeuroML file).  
-
-It is assumed that any channels and synapses referred to by above MorphML have
-already been loaded under that same name in /library in MOOSE (use ChannelML
-loader).  Note: This has been changed. Default path is now /neuroml/library 
-
-
-"""
-# cELementTree is mostly API-compatible but faster than ElementTree
-from xml.etree import cElementTree as ET
-import math
-import sys
-import moose
-from moose import utils as moose_utils
-from moose.neuroml import utils as neuroml_utils
-import helper.moose_methods as moose_methods
-
-from ChannelML import ChannelML
-import core.config as config
-import debug.debug as debug
-import inspect
-import re
-
-class MorphML():
-
-    def __init__(self,nml_params):
-        self.neuroml='http://morphml.org/neuroml/schema'
-        self.bio='http://morphml.org/biophysics/schema'
-        self.mml='http://morphml.org/morphml/schema'
-        self.nml='http://morphml.org/networkml/schema'
-        self.meta='http://morphml.org/metadata/schema'
-        self.cellDictBySegmentId={}
-        self.cellDictByCableId={}
-        self.nml_params = nml_params
-        self.model_dir = nml_params['model_dir']
-        self.temperature = nml_params['temperature']
-        self.libraryPath = config.libraryPath
-        self.cellPath = config.cellPath
-        moose.Neutral(self.libraryPath)
-
-    def stringToFloat(self, tempString):
-        if type(tempString) == str:
-            tempString = tempString.strip()
-            if len(tempString) == 0 or tempString is None:
-                return 0.0
-        else:
-            return float(tempString)
-
-    def readMorphMLFromFile(self, filename, params={}):
-        """
-        specify global params as a dict (presently none implemented)
-        returns { cellName1 : segDict, ... }
-        see readMorphML(...) for segDict
-        """
-        debug.printDebug("INFO", "{}".format(filename))
-        tree = ET.parse(filename)
-        neuroml_element = tree.getroot()
-        cellsDict = {}
-        for cell in neuroml_element.findall('.//{'+self.neuroml+'}cell'):
-            cellDict = self.readMorphML(
-                cell
-                , params
-                , neuroml_element.attrib['lengthUnits']
-            )
-            cellsDict.update(cellDict)
-        return cellsDict
-
-
-    def addSegment(self, cellName, segnum, segment):
-
-        """
-        Adding segment to cell.
-        """
-        run_dia = 0.0
-        running_comp = None
-        running_dia_nums = 0
-        segmentname = segment.attrib['name']
-
-        debug.printDebug("DEBUG"
-                , "Adding segment {} in cell {}".format(segmentname, cellName)
-                )
-
-        # cable is an optional attribute. WARNING: Here I assume it is always
-        # present.
-        cableid = segment.attrib['cable']
-        segmentid = segment.attrib['id']
-
-        # Old cableid still running, hence don't start a new compartment, skip
-        # to next segment.
-        if cableid == self.running_cableid:
-            self.cellDictBySegmentId[cellName][1][segmentid] = running_comp
-            proximal = segment.find('./{'+self.mml+'}proximal')
-            if proximal is not None:
-                run_dia += float(proximal.attrib["diameter"])*self.length_factor
-                running_dia_nums += 1
-            distal = segment.find('./{'+self.mml+'}distal')
-            if distal is not None:
-                run_dia += float(distal.attrib["diameter"])*self.length_factor
-                running_dia_nums += 1
-
-        # new cableid starts, hence start a new compartment; also finish
-        # previous / last compartment.
-        else:
-
-            # Create a new compartment, the moose "hsolve" method assumes
-            # compartments to be asymmetric compartments and symmetrizes them
-            # but that is not what we want when translating from Neuron
-            # which has only symcompartments -- so be careful!
-
-            # just segmentname is NOT unique - eg: mitral bbmit exported from
-            # NEURON.
-            mooseCompname = moose_methods.moosePath(segmentname, segmentid)
-            mooseComppath = self.mooseCell.path + '/' + mooseCompname
-            mooseComp = moose.Compartment(mooseComppath)
-            self.cellDictBySegmentId[cellName][1][segmentid] = mooseComp
-
-            # Cables are grouped and densities set for cablegroups. Hence I
-            # need to refer to segment according to which cable they belong
-            # to..
-            self.cellDictByCableId[cellName][1][cableid] = mooseComp
-            self.running_cableid = cableid
-            running_segid = segmentid
-            running_comp = mooseComp
-            run_dia = 0.0
-            running_dia_nums = 0
-
-            if 'parent' in segment.attrib:
-                # I assume the parent is created before the child so that I can
-                # immediately # connect the child.
-                parentid = segment.attrib['parent']
-                parent = self.cellDictBySegmentId[cellName][1][parentid]
-
-                # It is always assumed that axial of parent is connected to
-                # raxial of moosesegment THIS IS WHAT GENESIS readcell()
-                # DOES!!! UNLIKE NEURON!  THIS IS IRRESPECTIVE OF WHETHER
-                # PROXIMAL x,y,z OF PARENT = PROXIMAL x,y,z OF CHILD.  THIS IS
-                # ALSO IRRESPECTIVE OF fraction_along_parent SPECIFIED IN
-                # CABLE!  THUS THERE WILL BE NUMERICAL DIFFERENCES BETWEEN
-                # MOOSE/GENESIS and NEURON.  moosesegment sends Ra and Vm to
-                # parent, parent sends only Vm actually for symmetric
-                # compartment, both parent and moosesegment require each
-                # other's Ra/2, but axial and raxial just serve to distinguish
-                # ends.
-
-                moose.connect(parent, 'axial', mooseComp, 'raxial')
-            else:
-                parent = None
-            proximal = segment.find('./{'+self.mml+'}proximal')
-            if proximal is None:
-                # If proximal tag is not present, then parent attribute MUST be
-                # present in the segment tag!  if proximal is not present, then
-                # by default the distal end of the parent is the proximal end
-                # of the child
-                mooseComp.x0 = parent.x
-                mooseComp.y0 = parent.y
-                mooseComp.z0 = parent.z
-            else:
-                mooseComp.x0 = float(proximal.attrib["x"])*self.length_factor
-                mooseComp.y0 = float(proximal.attrib["y"])*self.length_factor
-                mooseComp.z0 = float(proximal.attrib["z"])*self.length_factor
-                run_dia += float(proximal.attrib["diameter"])*self.length_factor
-                running_dia_nums += 1
-            distal = segment.find('./{'+self.mml+'}distal')
-            if distal is not None:
-                run_dia += float(distal.attrib["diameter"]) * self.length_factor
-                running_dia_nums += 1
-
-            # finished creating new compartment Update the end position,
-            # diameter and length, and segDict of this comp/cable/section with
-            # each segment that is part of this cable (assumes contiguous
-            # segments in xml).  This ensures that we don't have to do any
-            # 'closing ceremonies', if a new cable is encoutered in next
-            # iteration.
-
-            if distal is not None:
-                running_comp.x = float(distal.attrib["x"])*self.length_factor
-                running_comp.y = float(distal.attrib["y"])*self.length_factor
-                running_comp.z = float(distal.attrib["z"])*self.length_factor
-
-            # Set the compartment diameter as the average diameter of all the
-            # segments in this section
-            running_comp.diameter = run_dia / float(running_dia_nums)
-
-            # Set the compartment length
-            running_comp.length = math.sqrt(
-                (running_comp.x-running_comp.x0)**2+\
-                (running_comp.y-running_comp.y0)**2+\
-                (running_comp.z-running_comp.z0)**2
-            )
-
-            # NeuroML specs say that if (x0,y0,z0)=(x,y,z), then round
-            # compartment e.g. soma.  In Moose set length = dia to give same
-            # surface area as sphere of dia.
-
-            if running_comp.length == 0.0:
-                running_comp.length = running_comp.diameter
-
-            # Set the segDict the empty list at the end below will get
-            # populated with the potential synapses on this segment, in
-            # function set_compartment_param(..)
-            self.segDict[running_segid] = [
-                running_comp.name
-                , (running_comp.x0 , running_comp.y0 , running_comp.z0)
-                , (running_comp.x,running_comp.y,running_comp.z)
-                , running_comp.diameter
-                , running_comp.length
-                , []
-            ]
-
-            if neuroml_utils.neuroml_debug:
-                debug.printDebug(
-                    "STEP"
-                    , "Set up compartment/section %s" % running_comp.name
-                )
-
-
-
-    def readMorphML(self, cell, params={}, lengthUnits="micrometer"):
-
-        """
-        returns {cellName:segDict}
-        where segDict = { segid1 : [ segname
-        , (proximalx,proximaly,proximalz)
-        , (distalx,distaly,distalz),diameter,length,[potential_syn1, ... ] ]
-        , ... }
-        segname is "<name>_<segid>" because 1) guarantees uniqueness,
-        2) later scripts obtain segid from the compartment's name!
-        """
-
-        debug.printDebug("DEBUG", "Entered function readMorphML")
-        if lengthUnits in ['micrometer','micron']:
-            self.length_factor = 1e-6
-        else:
-            self.length_factor = 1.0
-        cellName = cell.attrib["name"]
-
-        if cellName == 'LIF':
-            self.mooseCell = moose.LeakyIaF(self.cellPath+'/'+cellName)
-            self.segDict = {}
-        else:
-            # using moose Neuron class - in previous version 'Cell' class
-            # Chaitanya.
-            self.mooseCell = moose.Neuron(self.cellPath+'/'+cellName)
-            self.cellDictBySegmentId[cellName] = [self.mooseCell,{}]
-            self.cellDictByCableId[cellName] = [self.mooseCell,{}]
-            self.segDict = {}
-
-            # load morphology and connections between compartments Many neurons
-            # exported from NEURON have multiple segments in a section Combine
-            # those segments into one Compartment / section assume segments of
-            # a compartment/section are in increasing order and assume all
-            # segments of a compartment/section have the same cableid findall()
-            # returns elements in document order:
-
-            self.running_cableid = ''
-            running_segid = ''
-            segments = cell.findall(".//{"+self.mml+"}segment")
-            segmentstotal = len(segments)
-            for segnum, segment in enumerate(segments):
-                self.addSegment(cellName, segnum, segment)
-
-        # load cablegroups into a dictionary
-        self.cablegroupsDict = {}
-
-        # Two ways of specifying cablegroups in neuroml 1.x
-        # <cablegroup>s with list of <cable>s
-        cablegroups = cell.findall(".//{"+self.mml+"}cablegroup")
-        for cablegroup in cablegroups:
-            cablegroupname = cablegroup.attrib['name']
-            self.cablegroupsDict[cablegroupname] = []
-            for cable in cablegroup.findall(".//{"+self.mml+"}cable"):
-                cableid = cable.attrib['id']
-                self.cablegroupsDict[cablegroupname].append(cableid)
-
-        # <cable>s with list of <meta:group>s
-        cables = cell.findall(".//{"+self.mml+"}cable")
-        for cable in cables:
-            cableid = cable.attrib['id']
-            cablegroups = cable.findall(".//{"+self.meta+"}group")
-            for cablegroup in cablegroups:
-                cablegroupname = cablegroup.text
-                if cablegroupname in list(self.cablegroupsDict.keys()):
-                    self.cablegroupsDict[cablegroupname].append(cableid)
-                else:
-                    self.cablegroupsDict[cablegroupname] = [cableid]
-
-        # Add bioPhysics to the cell
-        self.addBiophysics(cell, cellName)
-
-        # load connectivity / synapses into the compartments
-        connectivity = cell.find(".//{"+self.neuroml+"}connectivity")
-        if connectivity is not None:
-            self.addConnectivity(cell, cellName, connectivity)
-        return {cellName:self.segDict}
-
-    def addConnectivity(self, cell, cellName, connectivity):
-
-      """
-      Add connectivity to cell.
-      """
-      synLocs = cell.findall(".//{"+self.nml+"}potential_syn_loc")
-      for psl in synLocs:
-        if 'synapse_direction' in list(psl.attrib.keys()):
-            if psl.attrib['synapse_direction'] in ['post']:
-                self.set_group_compartment_param(
-                    cell
-                    , cellName
-                    , psl
-                    , 'synapse_type'
-                    , psl.attrib['synapse_type']
-                    , self.nml
-                    , mechName='synapse'
-                )
-            if psl.attrib['synapse_direction'] in ['pre']:
-                self.set_group_compartment_param(
-                    cell
-                    , cellName
-                    , psl
-                    , 'spikegen_type'
-                    , psl.attrib['synapse_type']
-                    , self.nml
-                    , mechName='spikegen'
-                )
-
-
-    def addBiophysics(self, cell, cellName):
-        """Add Biophysics to cell
-        """
-        biophysics = cell.find(".//{"+self.neuroml+"}biophysics")
-        if biophysics is None: return None
-
-        if biophysics.attrib["units"] == 'Physiological Units':
-            # see pg 219 (sec 13.2) of Book of Genesis
-            self.CMfactor = 1e-2 # F/m^2 from microF/cm^2
-            self.Cfactor = 1e-6  # F from microF
-            self.RAfactor = 1e1  # Ohm*m from KOhm*cm
-            self.RMfactor = 1e-1 # Ohm*m^2 from KOhm*cm^2
-            self.Rfactor = 1e-3  # Ohm from KOhm
-            self.Efactor = 1e-3  # V from mV
-            self.Gfactor = 1e1   # S/m^2 from mS/cm^2
-            self.Ifactor = 1e-6  # A from microA
-            self.Tfactor = 1e-3  # s from ms
-        else:
-            self.CMfactor = 1.0
-            self.Cfactor = 1.0
-            self.RAfactor = 1.0
-            self.RMfactor = 1.0
-            self.Rfactor = 1.0
-            self.Efactor = 1.0
-            self.Gfactor = 1.0
-            self.Ifactor = 1.0
-            self.Tfactor = 1.0
-
-        IaFpresent = False
-        for mechanism in cell.findall(".//{"+self.bio+"}mechanism"):
-            mechName = mechanism.attrib["name"]
-            if mechName == "integrate_and_fire": IaFpresent = True
-            ## integrate-and-fire-meachanism
-            if IaFpresent:
-                self.integateAndFireMechanism(mechanism)
-
-        # Other mechanism are non-I&F type
-        sc = cell.find(".//{"+self.bio+"}spec_capacitance")
-        if sc is not None:
-            self.addSpecCapacitance(sc, cell, cellName)
-
-        sar = cell.find(".//{"+self.bio+"}spec_axial_resistance")
-        if sar is not None:
-            self.addSpecAxialResistance(sar, cell, cellName)
-
-        imp = cell.find(".//{"+self.bio+"}init_memb_potential")
-        if imp is not None:
-            self.addInitMembPotential(imp, cell, cellName)
-
-        # Add mechanisms
-
-        mechanisms = cell.findall(".//{"+self.bio+"}mechanism")
-        for mechanism in mechanisms:
-            self.addMechanism(mechanism, cell, cellName)
-
-
-    def addMechanism(self, mechanism, cell, cellName):
-        """ Add mechanism to cell.
-        """
-        mechName = mechanism.attrib["name"]
-        debug.printDebug("STEP", "Loading mechanism {0}".format(mechName))
-        passive = False
-        if "passive_conductance" in mechanism.attrib:
-            if mechanism.attrib['passive_conductance'].lower() == "true":
-                passive = True
-
-        # ONLY creates channel if at least one parameter (like gmax) is
-        # specified in the xml  Neuroml does not allow you to specify all
-        # default values.  However, granule cell example in neuroconstruct has
-        # Ca ion pool without a parameter, applying default values to all
-        # compartments!
-
-        mech_params = mechanism.findall(".//{"+self.bio+"}parameter")
-
-        ## if no params, apply all default values to all compartments
-        if len(mech_params) == 0:
-            compartments = self.cellDictByCableId[cellName][1].values()
-            for c in compartments:
-                self.set_compartment_param(c, None, 'default', mechName)
-
-        # if params are present, apply params to specified cable/compartment
-        # groups.
-
-        for parameter in mech_params:
-            options = { 'cellName' : cellName
-                       , 'mechName' : mechName
-                       , 'passive' : passive
-                       }
-            self.addParameterToCompartment(parameter, cell, options)
-
-        # Connect the Ca pools and channels Am connecting these at the very end
-        # so that all channels and pools have been created Note: this function
-        # is in moose.utils not moose.neuroml.utils !
-
-        # temperature should be in Kelvin for Nernst
-        temperature = self.stringToFloat(self.temperature)
-        moose_utils.connect_CaConc(
-            list(self.cellDictByCableId[cellName][1].values())
-            , temperature + neuroml_utils.ZeroCKelvin
-        )
-
-    def addParameterToCompartment(self, parameter, cell, options):
-        """ Add parameter to compartment
-        """
-        cellName = options['cellName']
-        mechName = options['mechName']
-        passive = options['passive']
-
-        paramName = parameter.attrib['name']
-        if passive:
-            if paramName in ['gmax']:
-                self.set_group_compartment_param(
-                    cell
-                    , cellName
-                    , parameter
-                    , 'RM'
-                    , self.RMfactor*1.0/float(parameter.attrib["value"])
-                    , self.bio
-                )
-            elif paramName in ['e','erev']:
-                self.set_group_compartment_param(
-                    cell
-                    , cellName
-                    , parameter
-                    , 'Em'
-                    , self.Efactor*float(parameter.attrib["value"])
-                    , self.bio
-                )
-            elif paramName in ['inject']:
-                self.set_group_compartment_param(
-                    cell
-                    , cellName
-                    , parameter
-                    , 'inject'
-                    , self.Ifactor*float(parameter.attrib["value"])
-                    , self.bio
-                )
-            else:
-                msg = "Yo programmar of MorphML! You did not implemented"
-                msg += " parameter {0} in mechanism {1} ".format(
-                    paramName
-                    , mechName
-                    )
-                debug.printDebug("WARN", msg, frame=inspect.currentframe())
-        else:
-            if paramName in ['gmax']:
-                gmaxval = float(eval( parameter.attrib["value"]
-                                     ,{"__builtins__":None},{}
-                                     )
-                                )
-                self.set_group_compartment_param(
-                    cell
-                    , cellName
-                    , parameter
-                    , 'Gbar'
-                    , self.Gfactor*gmaxval
-                    , self.bio
-                    , mechName
-                )
-            elif paramName in ['e','erev']:
-                self.set_group_compartment_param(
-                    cell
-                    , cellName
-                    , parameter
-                    , 'Ek'
-                    , self.Efactor*float(parameter.attrib["value"])
-                    , self.bio
-                    , mechName
-                )
-            elif paramName in ['depth']: # has to be type Ion Concentration!
-                self.set_group_compartment_param(
-                    cell
-                    , cellName
-                    , parameter
-                    , 'thick'
-                    , self.length_factor*float(parameter.attrib["value"])
-                    , self.bio
-                    , mechName
-                )
-            else:
-                msg = "Yo programmar of MorphML! You did not implemented"
-                msg += " parameter {0} in mechanism {1} ".format(
-                    paramName
-                    , mechName
-                    )
-                debug.printDebug("WARN", msg, frame=inspect.currentframe())
-
-    def addSpecCapacitance(self, spec_capacitance, cell, cellName):
-        """
-        Adding specific capacitance to cell
-        """
-        for parameter in spec_capacitance.findall(".//{"+self.bio+"}parameter"):
-            self.set_group_compartment_param(
-                cell
-                , cellName
-                , parameter
-                , 'CM'
-                , float(parameter.attrib["value"])*self.CMfactor
-                , self.bio
-            )
-
-
-    def addSpecAxialResistance(self, spec_axial_resistance, cell, cellName):
-        """
-        Add specific axial resistance to cell.
-        """
-        for p in spec_axial_resistance.findall(".//{"+self.bio+"}parameter"):
-            self.set_group_compartment_param(
-                cell
-                , cellName
-                , p
-                , 'RA'
-                , float(p.attrib["value"])*self.RAfactor
-                , self.bio
-            )
-
-    def integateAndFireMechanism(self, mechanism):
-        """  Integrate and fire mechanism
-        """
-        mech_params = mechanism.findall(".//{"+self.bio+"}parameter")
-        for parameter in mech_params:
-            paramName = parameter.attrib['name']
-            if paramName == 'inject':
-                self.mooseCell.inject = float(parameter.attrib["value"])*self.Ifactor
-            elif paramName == 'Rm':
-                self.mooseCell.Rm = float(parameter.attrib["value"])*self.Rfactor
-            elif paramName == 'Cm':
-                self.mooseCell.Cm = float(parameter.attrib["value"])*self.Cfactor
-            elif paramName == 'Em':
-                self.mooseCell.Em = float(parameter.attrib["value"])*self.Efactor
-            elif paramName == 'v_reset':
-                # voltage after spike, typicaly below resting
-                self.mooseCell.Vreset = float(parameter.attrib["value"])*self.Efactor
-                self.mooseCell.initVm = self.mooseCell.Vreset
-            elif paramName == 'threshold':
-                # firing threshold potential
-                self.mooseCell.Vthreshold = \
-                        float(parameter.attrib["value"])*self.Efactor
-            elif paramName == 't_refrac':
-                # min refractory time before next spike
-                msg = "Use this refractory period in simulation"
-                debug.printDebug("TODO" , msg, frame=inspect.currentframe())
-                self.mooseCell.refractoryPeriod = \
-                        float(parameter.attrib["value"])*self.Tfactor
-            elif paramName == 'inject':
-                # inject into soma
-                self.mooseCell.refractoryPeriod = \
-                        float(parameter.attrib["value"])*self.Ifactor
-
-
-    def addInitMembPotential(self, init_memb_potential, cell, cellName):
-        """Add init membrane potential to cell.
-        """
-        parameters = init_memb_potential.findall(".//{"+self.bio+"}parameter")
-        for parameter in parameters:
-            self.set_group_compartment_param(
-                    cell
-                    , cellName
-                    , parameter
-                    , 'initVm'
-                    , float(parameter.attrib["value"]) * self.Efactor
-                    , self.bio
-                    )
-
-
-    def set_group_compartment_param(self, cell, cellName, parameter, name
-        , value, grouptype, mechName=None):
-
-        """
-        Find the compartments that belong to the cablegroups refered to
-         for this parameter and set_compartment_param.
-        """
-
-        for group in parameter.findall(".//{"+grouptype+"}group"):
-            cablegroupname = group.text
-            if cablegroupname == 'all':
-                for compartment in self.cellDictByCableId[cellName][1].values():
-                    self.set_compartment_param(
-                        compartment
-                        , name
-                        , value
-                        , mechName
-                    )
-            else:
-                for cableid in self.cablegroupsDict[cablegroupname]:
-                    compartment = self.cellDictByCableId[cellName][1][cableid]
-                    self.set_compartment_param(
-                        compartment
-                        , name
-                        , value
-                        , mechName
-                    )
-
-    def set_compartment_param(self, compartment, name, value, mechName):
-        """ Set the param for the compartment depending on name and mechName. """
-        if name == 'CM':
-            compartment.Cm = value *math.pi*compartment.diameter*compartment.length
-        elif name == 'RM':
-            compartment.Rm = value/(math.pi*compartment.diameter*compartment.length)
-        elif name == 'RA':
-            compartment.Ra = value * compartment.length / \
-                    (math.pi*(compartment.diameter/2.0)**2)
-        elif name == 'Em':
-            compartment.Em = value
-        elif name == 'initVm':
-            compartment.initVm = value
-        elif name == 'inject':
-            msg = " {0} inject {1} A.".format(compartment.name, value)
-            debug.printDebug("INFO", msg)
-            compartment.inject = value
-        elif mechName is 'synapse':
-
-           # synapse being added to the compartment
-           # these are potential locations, we do not actually make synapses.
-           # I assume below that compartment name has _segid at its end
-
-           # get segment id from compartment name
-           segid = moose_methods.getCompartmentId(compartment.name)
-           self.segDict[segid][5].append(value)
-
-        # spikegen being added to the compartment
-        elif mechName is 'spikegen': 
-            # these are potential locations, we do not actually make the
-            # spikegens.  spikegens for different synapses can have different
-            # thresholds, hence include synapse_type in its name value contains
-            # name of synapse i.e. synapse_type
-            #spikegen = moose.SpikeGen(compartment.path+'/'+value+'_spikegen')
-            #moose.connect(compartment,"VmSrc",spikegen,"Vm")
-            pass
-        elif mechName is not None:
-
-            # if mechanism is not present in compartment, deep copy from library
-            if not moose.exists(compartment.path+'/'+mechName):
-
-                # if channel does not exist in library load it from xml file
-                if not moose.exists(self.libraryPath+"/"+mechName):
-                    cmlR = ChannelML(self.nml_params)
-                    model_filename = mechName+'.xml'
-                    model_path = neuroml_utils.find_first_file(
-                        model_filename
-                        , self.model_dir
-                    )
-                    if model_path is not None:
-                        cmlR.readChannelMLFromFile(model_path)
-                    else:
-                        msg = 'Mechanism {0}: files {1} not found under {2}'\
-                                .format( mechName
-                                        , model_filename
-                                        , self.model_dir
-                                        )
-                        debug.printDebug("ERROR"
-                                , msg
-                                , frame = inspect.currentframe()
-                                )
-                        sys.exit(0)
-
-                neutralObj = moose.Neutral(self.libraryPath+"/"+mechName)
-
-                # Ion concentration pool
-                if 'CaConc' == neutralObj.className:
-                    libcaconc = moose.CaConc(self.libraryPath+"/"+mechName)
-
-                    # deep copies the library caconc under the compartment
-                    caconc = moose.copy(libcaconc,compartment,mechName)
-                    caconc = moose.CaConc(caconc)
-
-                    # CaConc connections are made later using connect_CaConc()
-                    # Later, when calling connect_CaConc, B is set for caconc
-                    # based on thickness of Ca shell and compartment l and dia
-                    # OR based on the Mstring phi under CaConc path.
-                    channel = None
-
-                elif 'HHChannel2D' == neutralObj.className : ## HHChannel2D
-                    libchannel = moose.HHChannel2D(self.libraryPath+"/"+mechName)
-                    ## deep copies the library channel under the compartment
-                    channel = moose.copy(libchannel,compartment,mechName)
-                    channel = moose.HHChannel2D(channel)
-                    moose.connect(channel,'channel',compartment,'channel')
-                elif 'HHChannel' == neutralObj.className : ## HHChannel
-                    libchannel = moose.HHChannel(self.libraryPath+"/"+mechName)
-
-                    # deep copies the library channel under the compartment
-                    channel = moose.copy(libchannel,compartment,mechName)
-                    channel = moose.HHChannel(channel)
-                    moose.connect(channel,'channel',compartment,'channel')
-            # if mechanism is present in compartment, just wrap it
-            else:
-                neutralObj = moose.Neutral(compartment.path+'/'+mechName)
-                # Ion concentration pool
-                if 'CaConc' == neutralObj.className:
-                    # wraps existing channel
-                    caconc = moose.CaConc(compartment.path+'/'+mechName)
-                    channel = None
-                elif 'HHChannel2D' == neutralObj.className: ## HHChannel2D
-                    # wraps existing channel
-                    channel = moose.HHChannel2D(compartment.path+'/'+mechName)
-                elif 'HHChannel' == neutralObj.className : ## HHChannel
-                    # wraps existing channel
-                    channel = moose.HHChannel(compartment.path+'/'+mechName)
-            if name == 'Gbar':
-                # if CaConc, neuroConstruct uses gbar for thickness or phi
-                if channel is None:
-                    # If child Mstring 'phi' is present, set gbar as phi BUT,
-                    # value has been multiplied by Gfactor as a Gbar, SI or
-                    # physiological not known here, ignoring Gbar for CaConc,
-                    # instead of passing units here
-                    child = moose_utils.get_child_Mstring(caconc,'phi')
-                    if child is not None:
-                        #child.value = value
-                        pass
-                    else:
-                        #caconc.thick = value
-                        pass
-                else: # if ion channel, usual Gbar
-                    channel.Gbar = value * math.pi * compartment.diameter \
-                            * compartment.length
-            elif name == 'Ek':
-                channel.Ek = value
-
-            # thick seems to be NEURON's extension to NeuroML level 2.
-            elif name == 'thick':
-                # JUST THIS WILL NOT DO - HAVE TO SET B based on this thick!
-                caconc.thick = value
-                # Later, when calling connect_CaConc, B is set for caconc based
-                # on thickness of Ca shell and compartment l and dia.  OR based
-                # on the Mstring phi under CaConc path.
-
-        if neuroml_utils.neuroml_debug:
-            msg = "Setting {0} for {1} value {2}".format(name, compartment.path
-                                                         , value
-                                                         )
-            debug.printDebug("DEBUG", msg, frame=inspect.currentframe())
diff --git a/python/libmumbl/nml_parser/NetworkML.py b/python/libmumbl/nml_parser/NetworkML.py
deleted file mode 100644
index 4bf87b602e0a360b45b1186f7003d1fcc78c0f7f..0000000000000000000000000000000000000000
--- a/python/libmumbl/nml_parser/NetworkML.py
+++ /dev/null
@@ -1,934 +0,0 @@
-# This file is part of MOOSE simulator: http://moose.ncbs.res.in.
-
-# MOOSE is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-
-# MOOSE is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-# You should have received a copy of the GNU General Public License
-# along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
-
-
-"""
-
- Description: class NetworkML for loading NetworkML from file or xml element
- into MOOSE
-
- Version 1.0 by Aditya Gilra, NCBS, Bangalore, India, 2011 for serial MOOSE
-
- Version 1.5 by Niraj Dudani, NCBS, Bangalore, India, 2012, ported to parallel
- MOOSE
-
- Version 1.6 by Aditya Gilra, NCBS, Bangalore, India, 2012, further changes for
- parallel MOOSE
-
- Version 1.7 by Aditya Gilra, NCBS, Bangalore, India, 2013, further support for
- NeuroML 1.8.1
-
-    NeuroML.py is the preferred interface. Use this only if NeuroML L1,L2,L3
-    files are misnamed/scattered.  Instantiate NetworlML class, and thence use
-    method: readNetworkMLFromFile(...) to load a standalone NetworkML file, OR
-    readNetworkML(...) to load from an xml.etree xml element (could be part of a
-    larger NeuroML file).
-
-"""
-
-from xml.etree import cElementTree as ET
-import string
-import os
-import sys
-import MorphML
-import ChannelML
-import moose
-import moose.neuroml.utils as nmu
-import moose.utils as utils
-import inspect
-import helper.xml_methods as xml_methods
-import helper.moose_methods as moose_methods
-import core.stimulus as stimulus
-import core.config as config
-import debug.bugs as bugs
-import matplotlib.pyplot as plt
-import numpy as np
-import re
-
-from math import cos, sin
-
-class NetworkML(object):
-
-    def __init__(self, nml_params):
-        self.populationDict = dict()
-        self.libraryPath = config.libraryPath
-        moose.Neutral(self.libraryPath)
-        self.cellPath = self.libraryPath
-        moose.Neutral(self.cellPath)
-        moose.Neutral(self.libraryPath)
-        self.cellDictBySegmentId={}
-        self.cellDictByCableId={}
-        self.nml_params = nml_params
-        self.modelDir = nml_params['model_dir']
-        self.elecPath = config.elecPath
-        self.dt = 1e-3 # In seconds.
-        self.simTime = 1000e-3
-        self.plotPaths = 'figs'
-
-    def connectWrapper(self, src, srcF, dest, destF, messageType='Single'):
-        """
-        Wrapper around moose.connect 
-        """
-        utils.dump("INFO"
-                , "Connecting ({4})`\n\t{0},{1}`\n\t`{2},{3}".format(
-                    src.path
-                    , srcF
-                    , dest.path
-                    , destF
-                    , messageType
-                    )
-                , frame = inspect.currentframe()
-                )
-        try:
-            res = moose.connect(src, srcF, dest, destF, messageType)
-            assert res, "Failed to connect"
-        except Exception as e:
-            utils.dump("ERROR", "Failed to connect.")
-            raise e
-
-    def plotVector(self, vector, plotname):
-        ''' Saving input vector to a file '''
-        name = plotname.replace('/', '_')
-        fileName = os.path.join(self.plotPaths, name)+'.eps'
-        utils.dump("DEBUG"
-                , "Saving vector to a file {}".format(fileName)
-                )
-        plt.vlines(vector, 0, 1)
-        plt.savefig(fileName)
-
-
-    def readNetworkMLFromFile(self, filename, cellSegmentDict, params={}):
-    
-
-        """ readNetworkML
-
-        specify tweak
-        params = {
-            'excludePopulations':[popname1,...]
-            , 'excludeProjections':[projname1,...]
-            , 'onlyInclude':{'includePopulation':(popname,[id1,...])
-            ,'includeProjections':(projname1,...)
-            }
-        }
-
-        If excludePopulations is present, then excludeProjections must also be
-        present. Thus if you exclude some populations, ensure that you exclude
-        projections that refer to those populations also!  Though for
-        onlyInclude, you may specify only included cells and this reader will
-        also keep cells connected to those in onlyInclude.  This reader first
-        prunes the exclude-s, then keeps the onlyInclude-s and those that are
-        connected.  Use 'includeProjections' if you want to keep some
-        projections not connected to the primary 'includePopulation' cells but
-        connected to secondary cells that connected to the primary ones: e.g.
-        baseline synapses on granule cells connected to 'includePopulation'
-        mitrals; these synapses receive file based pre-synaptic events, not
-        presynaptically connected to a cell.
-
-        """
-
-        utils.dump("INFO", "reading file %s ... " % filename)
-        tree = ET.parse(filename)
-        root_element = tree.getroot()
-        utils.dump("INFO", "Tweaking model ... ")
-        utils.tweak_model(root_element, params)
-        utils.dump("INFO", "Loading model into MOOSE ... ")
-        return self.readNetworkML(
-                root_element
-               , cellSegmentDict
-               , params
-               , root_element.attrib['lengthUnits']
-               )
-
-    def readNetworkML(self, network, cellSegmentDict , params={}
-        , lengthUnits="micrometer"):
-
-        """
-        This returns
-         populationDict = {
-           'populationName1':(cellname
-           , {int(instanceid1):moosecell, ...F}) , ...
-           }
-
-         projectionDict = {
-            'projectionName1':(source,target
-            ,[(syn_name1,pre_seg_path,post_seg_path),...])
-            , ...
-            }
-        """
-
-        if lengthUnits in ['micrometer','micron']:
-            self.length_factor = 1e-6
-        else:
-            self.length_factor = 1.0
-        self.network = network
-        self.cellSegmentDict = cellSegmentDict
-        self.params = params
-        utils.dump("STEP", "Creating populations ... ")
-        self.createPopulations() 
-
-        utils.dump("STEP", "Creating connections ... ")
-        self.createProjections() 
-
-        # create connections
-        utils.dump("STEP", "Creating inputs in %s .. " % self.elecPath)
-
-        # create inputs (only current pulse supported)
-        self.createInputs() 
-        return (self.populationDict, self.projectionDict)
-
-    def createInputs(self):
-
-        """ createInputs
-
-        Create inputs as given in NML file and attach them to moose.
-        """
-
-        for inputs in self.network.findall(".//{"+nmu.nml_ns+"}inputs"):
-            units = inputs.attrib['units']
-
-            # This dict is to be passed to function which attach an input
-            # element to moose.
-            factors = {}
-
-            # see pg 219 (sec 13.2) of Book of Genesis
-            if units == 'Physiological Units':
-                factors['Vfactor'] = 1e-3 # V from mV
-                factors['Tfactor'] = 1e-3 # s from ms
-                factors['Ifactor'] = 1e-6 # A from microA
-            else:
-                utils.dump("NOTE", "We got {0}".format(units))
-                factors['Vfactor'] = 1.0
-                factors['Tfactor'] = 1.0
-                factors['Ifactor'] = 1.0
-
-            for inputElem in inputs.findall(".//{"+nmu.nml_ns+"}input"):
-                self.attachInputToMoose(inputElem, factors) 
-    def attachInputToMoose(self, inElemXml, factors, savePlot=True):
-
-        """attachInputToMoose
-        This function create StimulousTable in moose
-
-        There can be two type of stimulous: random_stim or pulse_input.
-        """
-
-        # If /elec doesn't exists it creates /elec and returns a reference to
-        # it. If it does, it just returns its reference.
-        moose.Neutral(self.elecPath)
-        inputName = inElemXml.get('name')
-
-        random_stim = inElemXml.find('.//{'+nmu.nml_ns+'}random_stim')
-        pulse_stim = inElemXml.find('.//{'+nmu.nml_ns+'}pulse_input')
-
-        if random_stim is not None:
-            utils.dump("INFO", "Generating random stimulous")
-            utils.dump("TODO", "Test this Poission spike train table")
-    
-            # Get the frequency of stimulus
-            frequency = moose_methods.toFloat(
-                    random_stim.get('frequency', '1.0')
-                    ) / factors['Tfactor']
-            amplitude = random_stim.get('amplitude', 1.0)
-            synpMechanism = random_stim.get('synaptic_mechanism')
-
-            # Create random stimulus
-            vec = stimulus.generateSpikeTrainPoission(frequency
-                    , dt=self.dt
-                    , simTime=self.simTime
-                    )
-            # Stimulus table
-            tablePath = os.path.join(self.elecPath, "Stimulus")
-            moose.Neutral(tablePath)
-            stimPath = os.path.join(tablePath, inputName)
-            stim = moose.TimeTable(stimPath)
-            stim.vec = vec
-
-            if savePlot:
-                self.plotVector(vec, tablePath)
-
-            target = inElemXml.find(".//{"+nmu.nml_ns+"}target")
-            population = target.get('population')
-            for site in target.findall(".//{"+nmu.nml_ns+"}site"):
-               cell_id = site.attrib['cell_id']
-               if 'segment_id' in site.attrib:
-                   segment_id = site.attrib['segment_id']
-               else:
-                   # default segment_id is specified to be 0
-                   segment_id = 0 
-
-               # To find the cell name fetch the first element of tuple.
-               cell_name = self.populationDict[population][0]
-               if cell_name == 'LIF':
-                   utils.dump("NOTE",
-                           "LIF cell_name. Partial implementation"
-                           , frame = inspect.currentframe()
-                           )
-
-                   LIF = self.populationDict[population][1][int(cell_id)]
-                   m = self.connectSynapse(stim, LIF)
-               else:
-                    segId = '{0}'.format(segment_id)
-                    segment_path = self.populationDict[population][1]\
-                           [int(cell_id)].path + '/' + \
-                            self.cellSegmentDict[cell_name][segId][0]
-                    compartment = moose.Compartment(segment_path)
-                    synchan = moose.SynChan(
-                        os.path.join(compartment.path , '/synchan')
-                        )
-                    synchan.Gbar = 1e-6
-                    synchan.Ek = 0.0
-                    self.connectWrapper(synchan, 'channel', compartment, 'channel')
-                    synchan.numSynapses = 1
-                    m = self.connectSynapse(stim, moose.element(synchan.path+'/synapse'))
-
-        elif pulse_stim is not None:
-
-            Ifactor = factors['Ifactor']
-            Tfactor = factors['Tfactor']
-            pulseinput = inElemXml.find(".//{"+nmu.nml_ns+"}pulse_input")
-            if pulseinput is None:
-                utils.dump("WARN"
-                        , "This type of stimulous is not supported."
-                        , frame = inspect.currentframe()
-                        )
-                return 
-
-            self.pulseGenPath = self.elecPath + '/PulseGen'
-            moose.Neutral(self.pulseGenPath)
-            pulseGenPath = '{}/{}'.format(self.pulseGenPath, inputName)
-            pulsegen = moose.PulseGen(pulseGenPath)
-            icClampPath = '{}/{}'.format(self.elecPath, 'iClamp')
-            moose.Neutral(icClampPath)
-            iclamp = moose.DiffAmp('{}/{}'.format(icClampPath, inputName))
-            iclamp.saturation = 1e6
-            iclamp.gain = 1.0
-
-            # free run
-            pulsegen.trigMode = 0 
-            pulsegen.baseLevel = 0.0
-            pulsegen.firstDelay = float(pulseinput.attrib['delay'])*Tfactor
-            pulsegen.firstWidth = float(pulseinput.attrib['duration'])*Tfactor
-            pulsegen.firstLevel = float(pulseinput.attrib['amplitude'])*Ifactor
-
-            # to avoid repeat
-            pulsegen.secondDelay = 1e6 
-            pulsegen.secondLevel = 0.0
-            pulsegen.secondWidth = 0.0
-
-            # do not set count to 1, let it be at 2 by default else it will
-            # set secondDelay to 0.0 and repeat the first pulse!
-            #pulsegen.count = 1
-            self.connectWrapper(pulsegen,'output', iclamp, 'plusIn')
-
-            # Attach targets
-            target = inElemXml.find(".//{"+nmu.nml_ns+"}target")
-            population = target.attrib['population']
-            for site in target.findall(".//{"+nmu.nml_ns+"}site"):
-                cell_id = site.attrib['cell_id']
-                if 'segment_id' in site.attrib: 
-                    segment_id = site.attrib['segment_id']
-                else: 
-                    # default segment_id is specified to be 0
-                    segment_id = 0 
-
-                # population is populationName,
-                # self.populationDict[population][0] is cellname
-                cell_name = self.populationDict[population][0]
-                if cell_name == 'LIF':
-                    debug.printDebut("TODO"
-                            , "Rewrite this section"
-                            , frame = inspect.currentframe()
-                            )
-                    continue
-                    LIF = self.populationDict[population][1][int(cell_id)]
-                    self.connectWrapper(iclamp,'output',LIF,'injectMsg')
-                else:
-                    segment_path = self.populationDict[population][1]\
-                            [int(cell_id)].path+'/'+\
-                             self.cellSegmentDict[cell_name][segment_id][0]
-                    compartment = moose.Compartment(segment_path)
-
-                    self.connectWrapper(iclamp
-                            ,'output'
-                            , compartment
-                            ,'injectMsg'
-                            )
-            
-    def createPopulations(self):
-        """
-        Create population dictionary.
-        """
-        populations =  self.network.findall(".//{"+nmu.nml_ns+"}population")
-        if not populations:
-            utils.dump("WARN"
-                    , [ 
-                        "No population find in model"
-                        , "Searching in namespace {}".format(nmu.nml_ns)
-                        ]
-                    , frame = inspect.currentframe()
-                    )
-
-        for population in populations:
-            cellname = population.attrib["cell_type"]
-            populationName = population.attrib["name"]
-            utils.dump("INFO"
-                    , "Loading population `{0}`".format(populationName)
-                    )
-            # if cell does not exist in library load it from xml file
-            if not moose.exists(self.libraryPath+'/'+cellname):
-                utils.dump("DEBUG"
-                        , "Searching in subdirectories for cell types" + 
-                        " in `{0}.xml` and `{0}.morph.xml` ".format(cellname)
-                        )
-                mmlR = MorphML.MorphML(self.nml_params)
-                model_filenames = (cellname+'.xml', cellname+'.morph.xml')
-                success = False
-                for modelFile in model_filenames:
-                    model_path = nmu.find_first_file(modelFile
-                            , self.modelDir
-                            )
-                    if model_path is not None:
-                        cellDict = mmlR.readMorphMLFromFile(model_path)
-                        success = True
-                        break
-                if not success:
-                    raise IOError(
-                        'For cell {0}: files {1} not found under {2}.'.format(
-                            cellname, model_filenames, self.modelDir
-                        )
-                    )
-                self.cellSegmentDict.update(cellDict)
-            if cellname == 'LIF':
-                cellid = moose.LeakyIaF(self.libraryPath+'/'+cellname)
-            else:
-                # added cells as a Neuron class.
-                cellid = moose.Neuron(self.libraryPath+'/'+cellname) 
-
-            self.populationDict[populationName] = (cellname,{})
-
-            for instance in population.findall(".//{"+nmu.nml_ns+"}instance"):
-                instanceid = instance.attrib['id']
-                location = instance.find('./{'+nmu.nml_ns+'}location')
-                rotationnote = instance.find('./{'+nmu.meta_ns+'}notes')
-                if rotationnote is not None:
-                    # the text in rotationnote is zrotation=xxxxxxx
-                    zrotation = float(rotationnote.text.split('=')[1])
-                else:
-                    zrotation = 0
-                if cellname == 'LIF':
-                    cell = moose.LeakyIaF(cellid)
-                    self.populationDict[populationName][1][int(instanceid)] = cell
-                else:
-                    # No Cell class in MOOSE anymore! :( addded Neuron class -
-                    # Chaitanya
-                    cell = moose.Neuron(cellid) 
-                    self.populationDict[populationName][1][int(instanceid)] = cell
-                    x = float(location.attrib['x']) * self.length_factor
-                    y = float(location.attrib['y']) * self.length_factor
-                    z = float(location.attrib['z']) * self.length_factor
-                    self.translate_rotate(cell, x, y, z, zrotation)
-
-    # recursively translate all compartments under obj
-    def translate_rotate(self,obj,x,y,z,ztheta): 
-        for childId in obj.children:
-            childobj = moose.Neutral(childId)
-            # if childobj is a compartment or symcompartment translate, else
-            # skip it
-            if childobj.className in ['Compartment','SymCompartment']:
-                # SymCompartment inherits from Compartment, so below wrapping by
-                # Compartment() is fine for both Compartment and SymCompartment
-                child = moose.Compartment(childId)
-                x0 = child.x0
-                y0 = child.y0
-                x0new = x0 * cos(ztheta) - y0 * sin(ztheta)
-                y0new = x0 * sin(ztheta) + y0 * cos(ztheta)
-                child.x0 = x0new + x
-                child.y0 = y0new + y
-                child.z0 += z
-                x1 = child.x
-                y1 = child.y
-                x1new = x1 * cos(ztheta) - y1 * sin(ztheta)
-                y1new = x1 * sin(ztheta) + y1 * cos(ztheta)
-                child.x = x1new + x
-                child.y = y1new + y
-                child.z += z
-            if len(childobj.children)>0:
-                # recursive translation+rotation
-                self.translate_rotate(childobj
-                        , x
-                        , y
-                        , z
-                        , ztheta
-                        )
-
-    def getCellPath(self, populationType, instanceId):
-        ''' Given a population type and instanceId, return its path '''
-        try:
-            path = self.populationDict[populationType][1]
-        except KeyError as e:
-            utils.dump("ERROR"
-                    , [ "Population type `{0}` not found".format(populationType)
-                        , "Availale population in network are "
-                        , self.populationDict.keys()
-                    ]
-                    )
-            raise KeyError("Missing population type : {}".format(populationType))
-        except Exception as e:
-            raise e
-
-        try:
-            path = path[instanceId]
-        except KeyError as e:
-            msg = "Population type {} has no instance {}".format(
-                    populationType
-                    , instanceId
-                    )
-            utils.dump("ERROR"
-                    , [msg , "Available instances are" , path.keys() ]
-                    )
-            raise KeyError(msg)
-
-        # Now get the path from moose path
-        path = path.path
-        if not re.match(r'(\/\w+)+', path):
-            raise UserWarning("{} is not a valid path".format(path))
-        return path 
-
-
-    def addConnection(self, connection, projection, options):
-
-        """
-        This function adds connection
-        """
-        synName = options['syn_name']
-        source = options['source']
-        target = options['target']
-        weight = options['weight']
-        threshold = options['threshold']
-        propDelay = options['prop_delay']
-        projectionName = projection.attrib['name']
-
-        pre_cell_id = connection.attrib['pre_cell_id']
-        post_cell_id = connection.attrib['post_cell_id']
-
-        if 'file' not in pre_cell_id:
-            # source could be 'mitrals', self.populationDict[source][0] would be
-            # 'mitral'
-            pre_cell_id = int(pre_cell_id)
-            post_cell_id = int(post_cell_id)
-            pre_cell_name = self.populationDict[source][0]
-            pre_segment_id = connection.attrib.get('pre_segment_id', 0)
-            pre_segment_path = "{0}/{1}".format(
-                    self.getCellPath(source, pre_cell_id)
-                    , self.cellSegmentDict[pre_cell_name][pre_segment_id][0]
-                    )
-        else:
-            # I've removed extra excitation provided via files, so below comment
-            # doesn't apply.  'file[+<glomnum>]_<filenumber>' # glomnum is for
-            # mitral_granule extra excitation from unmodelled sisters.
-            pre_segment_path = "{}_{}".format(
-                    pre_cell_id 
-                    , connection.attrib['pre_segment_id']
-                    )
-
-        # target could be 'PGs', self.populationDict[target][0] would be 'PG'
-        post_cell_name = self.populationDict[target][0]
-        post_segment_id = connection.attrib.get('post_segment_id', '0')
-
-        post_segment_path = "{}/{}".format(
-                self.getCellPath(target, post_cell_id)
-                , self.cellSegmentDict[post_cell_name][post_segment_id][0]
-                )
-
-        try:
-            self.projectionDict[projectionName][2].append(
-                    (synName , pre_segment_path, post_segment_path)
-                    )
-        except KeyError as e:
-            utils.dump("ERR", "Failed find key {0}".format(e)
-                    , frame = inspect.currentframe())
-            print(self.projectionDict.keys())
-            sys.exit(0)
-
-        properties = connection.findall('./{'+nmu.nml_ns+'}properties')
-        if len(properties) == 0:
-            self.connectUsingSynChan(synName, pre_segment_path, post_segment_path
-                    , weight, threshold, propDelay
-                    )
-        else:
-            [self.addProperties(pre_segment_path, post_segment_path, p, options) 
-                    for p in properties]
-
-    def addProperties(self, pre_segment_path, post_segment_path, props, options):
-        '''Add properties 
-        '''
-        synName = options['syn_name']
-        source = options['source']
-        target = options['target']
-        weight = options['weight']
-        threshold = options['threshold']
-        propDelay = options['prop_delay']
-
-        synapse = props.attrib.get('synapse_type', None)
-        if not synapse: 
-            utils.dump("WARN"
-                    , "Synapse type {} not found.".format(synapse)
-                    , frame = inspect.currentframe()
-                    )
-            raise UserWarning("Missing parameter synapse_type")
-
-        synName = synapse
-        weight_override = float(props.attrib['weight'])
-        if 'internal_delay' in props.attrib:
-            delay_override = float(props.attrib['internal_delay'])
-        else: delay_override = propDelay
-        if weight_override != 0.0:
-            self.connectUsingSynChan(synName
-                    , pre_segment_path
-                    , post_segment_path
-                    , weight_override
-                    , threshold, delay_override
-                    )
-        else: pass
-
-
-    def createProjections(self):
-        self.projectionDict={}
-        projections = self.network.find(".//{"+nmu.nml_ns+"}projections")
-        if projections is not None:
-            if projections.attrib["units"] == 'Physiological Units':
-                # see pg 219 (sec 13.2) of Book of Genesis
-                self.Efactor = 1e-3 # V from mV
-                self.Tfactor = 1e-3 # s from ms
-            else:
-                self.Efactor = 1.0
-                self.Tfactor = 1.0
-        [self.createProjection(p) for p in
-                self.network.findall(".//{"+nmu.nml_ns+"}projection")]
-
-
-    def createProjection(self, projection):
-        projectionName = projection.attrib["name"]
-        utils.dump("INFO", "Projection {0}".format(projectionName))
-        source = projection.attrib["source"]
-        target = projection.attrib["target"]
-        self.projectionDict[projectionName] = (source,target,[])
-
-        # TODO: Assuming that only one element <synapse_props> under
-        # <projection> element.
-        synProps = projection.find(".//{"+nmu.nml_ns+"}synapse_props")
-        options = self.addSyapseProperties(projection, synProps, source, target)
-
-        connections = projection.findall(".//{"+nmu.nml_ns+"}connection")
-        [self.addConnection(c, projection, options) for c in connections]
-
-    def addSyapseProperties(self, projection,  syn_props, source, target):
-        '''Add Synapse properties'''
-        synName = syn_props.attrib['synapse_type']
-        ## if synapse does not exist in library load it from xml file
-        if not moose.exists(os.path.join(self.libraryPath, synName)):
-            cmlR = ChannelML.ChannelML(self.nml_params)
-            modelFileName = synName+'.xml'
-            model_path = nmu.find_first_file(modelFileName
-                    , self.modelDir
-                    )
-            if model_path is not None:
-                cmlR.readChannelMLFromFile(model_path)
-            else:
-                msg = 'For mechanism {0}: files {1} not found under {2}.'.format(
-                        synName, modelFileName, self.modelDir
-                    )
-                raise UserWarning(msg)
-
-        weight = float(syn_props.attrib['weight'])
-        threshold = float(syn_props.attrib['threshold']) * self.Efactor
-        if 'prop_delay' in syn_props.attrib:
-            propDelay = float(syn_props.attrib['prop_delay']) * self.Tfactor
-        elif 'internal_delay' in syn_props.attrib:
-            propDelay = float(syn_props.attrib['internal_delay']) * self.Tfactor
-        else:
-            propDelay = 0.0
-
-        options = { 'syn_name' : synName , 'weight' : weight
-                   , 'source' : source , 'target' : target
-                   , 'threshold' : threshold , 'prop_delay' : propDelay 
-                   }
-        return options
-
-    def connectSynapse(self, spikegen, synapse):
-        ''' Add synapse. '''
-
-        assert isinstance(synapse, moose.SynChan), type(synapse)
-
-        #utils.dump("INFO"
-        #        , "Connecting ({})\n\t`{}`\n\t`{}`".format(
-        #                "Sparse"
-        #                , spikegen.path
-        #                , synapse.vec.path
-        #                )
-        #        , frame = inspect.currentframe()
-        #        )
-
-        # Following 6 lines are from snippet Izhikevich_with_synapse.py file. I
-        # am not sure whether this is the right way to make a synpase. However,
-        # let's try this till we get a non-zero result after simulation.
-        spikeStim = moose.PulseGen('%s/spike_stim' % (synapse.parent.path))
-        spikeStim.delay[0] = 50.0
-        spikeStim.level[0] = 1.0
-        spikeStim.width[0] = 100.0
-        moose.connect(spikeStim, 'output', spikegen, 'Vm')
-        m = moose.connect(spikegen, "spikeOut"
-                , synapse.synapse.vec, "addSpike"
-                , "Sparse"
-                )
-        m.setRandomConnectivity(1.0, 1)
-        return m
-
-    def connectUsingSynChan(self, synName, prePath, post_path
-            , weight, threshold, delay
-            ):
-        """
-        Connect two compartments using SynChan
-        """
-
-        postcomp = moose.Compartment(post_path)
-
-        # We usually try to reuse an existing SynChan - event based SynChans
-        # have an array of weights and delays and can represent multiple
-        # synapses i.e.  a new element of the weights and delays array is
-        # created every time a 'synapse' message connects to the SynChan (from
-        # 'event' of spikegen) BUT for a graded synapse with a lookup table
-        # output connected to 'activation' message, not to 'synapse' message, we
-        # make a new synapse everytime ALSO for a saturating synapse i.e.
-        # KinSynChan, we always make a new synapse as KinSynChan is not meant to
-        # represent multiple synapses
-        libsyn = moose.SynChan(self.libraryPath+'/'+synName)
-        gradedchild = utils.get_child_Mstring(libsyn, 'graded')
-
-        # create a new synapse
-        if libsyn.className == 'KinSynChan' or gradedchild.value == 'True': 
-            synNameFull = moose_methods.moosePath(synName
-                    , utils.underscorize(prePath)
-                    )
-            synObj = self.makeNewSynapse(synName, postcomp, synNameFull)
-        else:
-            # See debug/bugs for more details.
-            # NOTE: Change the debug/bugs to enable/disable this bug.
-            if bugs.BUG_NetworkML_500:
-                utils.dump("INFO"
-                        , "See the code. There might be a bug here"
-                        , frame = inspect.currentframe()
-                        )
-                synNameFull = moose_methods.moosePath(synName
-                        , utils.underscorize(prePath)
-                        )
-                synObj = self.makeNewSynapse(synName, postcomp, synNameFull)
-
-            else: # If the above bug is fixed.
-                synNameFull = synName
-                if not moose.exists(post_path+'/'+synNameFull):
-                    synObj = self.makeNewSynapse(synName, postcomp, synNameFull)
-
-        # wrap the synapse in this compartment
-        synPath = moose_methods.moosePath(post_path, synNameFull)
-        syn = moose.SynChan(synPath)
-
-        gradedchild = utils.get_child_Mstring(syn, 'graded')
-
-        # weights are set at the end according to whether the synapse is graded
-        # or event-based
-
-
-        # connect pre-comp Vm (if graded) OR spikegen/timetable (if event-based)
-        # to the synapse
-
-        # graded synapse
-        if gradedchild.value=='True': 
-            table = moose.Table(syn.path+"/graded_table")
-            # always connect source to input - else 'cannot create message'
-            # error.
-            precomp = moose.Compartment(prePath)
-            self.connectWrapper(precomp, "VmOut", table, "msgInput")
-
-            # since there is no weight field for a graded synapse
-            # (no 'synapse' message connected),
-            # I set the Gbar to weight*Gbar
-            syn.Gbar = weight * syn.Gbar
-
-        # Event based synapse
-        else: 
-            # synapse could be connected to spikegen at pre-compartment OR a
-            # file!
-            if 'file' not in prePath:
-                precomp = moose.Compartment(prePath)
-                if not moose.exists(prePath+'/IaF_spikegen'):
-                    # if spikegen for this synapse doesn't exist in this
-                    # compartment, create it spikegens for different synapse_types
-                    # can have different thresholds
-                    if not moose.exists(prePath+'/'+synName+'_spikegen'):
-                        spikegen = moose.SpikeGen(prePath+'/'+synName+'_spikegen')
-                        # spikegens for different synapse_types can have different
-                        # thresholds
-                        spikegen.threshold = threshold
-                        # This ensures that spike is generated only on leading edge.
-                        spikegen.edgeTriggered = 1 
-
-                        # usually events are raised at every time step that Vm >
-                        # Threshold, can set either edgeTriggered as above or
-                        # refractT
-                        #spikegen.refractT = 0.25e-3 
-
-
-                    # wrap the spikegen in this compartment
-                    spikegen = moose.SpikeGen(prePath+'/'+synName+'_spikegen') 
-                else:
-                    spikegen = moose.SpikeGen(prePath+'/IaF_spikegen')
-
-                # connect the spikegen to the synapse note that you need to use
-                # Synapse (auto-created) under SynChan to get/set weights ,
-                # addSpike-s etc.  can get the Synapse element by
-                # moose.Synapse(syn.path+'/synapse') or syn.synapse Synpase is
-                # an array element, first add to it, to addSpike-s, get/set
-                # weights, etc.
-
-
-                syn.numSynapses += 1
-                m = self.connectSynapse(spikegen, syn)
-
-            else:
-                # if connected to a file, create a timetable,
-                # put in a field specifying the connected filenumbers to this segment,
-                # and leave it for simulation-time connection
-                ## prePath is 'file[+<glomnum>]_<filenum1>[_<filenum2>...]' i.e. glomnum could be present
-                filesplit = prePath.split('+')
-                if len(filesplit) == 2:
-                    glomsplit = filesplit[1].split('_', 1)
-                    glomstr = '_'+glomsplit[0]
-                    filenums = glomsplit[1]
-                else:
-                    glomstr = ''
-                    filenums = prePath.split('_', 1)[1]
-                tt_path = postcomp.path+'/'+synNameFull+glomstr+'_tt'
-                if not moose.exists(tt_path):
-                    # if timetable for this synapse doesn't exist in this
-                    # compartment, create it, and add the field 'fileNumbers'
-                    tt = moose.TimeTable(tt_path)
-                    tt.addField('fileNumbers')
-                    tt.setField('fileNumbers',filenums)
-
-                    # Be careful to connect the timetable only once while
-                    # creating it as below: note that you need to use Synapse
-                    # (auto-created) under SynChan to get/set weights ,
-                    # addSpike-s etc.  can get the Synapse element by
-                    # moose.Synapse(syn.path+'/synapse') or syn.synapse Synpase
-                    # is an array element, first add to it, to addSpike-s,
-                    # get/set weights, etc.
-                    syn.numSynapses += 1
-                    m = self.connectSynapse(spikegen, syn.synapse)
-                else:
-                    # if it exists, append file number to the field 'fileNumbers'
-                    tt = moose.TimeTable(tt_path)
-                    # append filenumbers from
-                    # 'file[+<glomnum>]_<filenumber1>[_<filenumber2>...]'
-                    filenums = moose_methods.moosePath(tt.getField('fileNumbers')
-                            , filenums)
-                    tt.setField('fileNumbers', filenums)
-
-            # syn.Gbar remains the same, but we play with the weight which is a
-            # factor to Gbar The delay and weight can be set only after
-            # connecting a spike event generator.  delay and weight are arrays:
-            # multiple event messages can be connected to a single synapse first
-            # argument below is the array index, we connect to the latest
-            # synapse created above But KinSynChan ignores weight of the
-            # synapse, so set the Gbar for it
-            if libsyn.className == 'KinSynChan':
-                syn.Gbar = weight*syn.Gbar
-            else:
-                # note that you need to use Synapse (auto-created) under SynChan
-                # to get/set weights , addSpike-s etc.  can get the Synpase
-                # element by moose.Synapse(syn.path+'/synapse') or syn.synapse
-                syn.synapse[-1].weight = weight
-            syn.synapse[-1].delay = delay # seconds
-            #print 'len = ',len(syn.synapse)
-            #for i,syn_syn in enumerate(syn.synapse):
-            #    print i,'th weight =',syn_syn.weight,'\n'
-
-    def makeNewSynapse(self, synName, postcomp, synNameFull):
-        '''This function creates a new synapses onto postcomp.
-
-        SpikeGen is spikeGenerator (presynaptic). SpikeGen connects to SynChan,
-        a synaptic channel which connects to post-synaptic compartment.
-
-        SpikeGen models the pre-synaptic events.
-        '''
-        synPath = "%s/%s" % (self.libraryPath, synName)
-        utils.dump("SYNAPSE"
-                , "Creating {} with path {} onto compartment {}".format(
-                    synName
-                    , synPath
-                    , postcomp.path
-                    )
-                )
-        # if channel does not exist in library load it from xml file
-        if not moose.exists(synPath):
-            utils.dump("SYNAPSE"
-                    , "Synaptic Channel {} does not exists. {}".format(
-                        synPath, "Loading is from XML file"
-                        )
-                    )
-            cmlR = ChannelML.ChannelML(self.nml_params)
-            cmlR.readChannelMLFromFile(synName+'.xml')
-
-        # deep copies the library synapse to an instance under postcomp named as
-        # <arg3>
-        if config.disbleCopyingOfObject:
-            utils.dump("WARN"
-                    , "Copying existing SynChan ({}) to {}".format(
-                        synPath
-                        , postcomp
-                        )
-                    )
-            synid = moose.copy(moose.Neutral(synPath), postcomp, synNameFull)
-        else:
-            synid = synPath
-        
-        syn = moose.SynChan(synid)
-        syn = self.configureSynChan(syn, synParams={})
-        childmgblock = utils.get_child_Mstring(syn,'mgblock')
-
-        # connect the post compartment to the synapse
-        # If NMDA synapse based on mgblock, connect to mgblock
-        if childmgblock.value == 'True': 
-            mgblock = moose.Mg_block(syn.path+'/mgblock')
-            self.connectWrapper(postcomp, "channel", mgblock, "channel")
-        # if SynChan or even NMDAChan, connect normally
-        else: 
-            self.connectWrapper(postcomp,"channel", syn, "channel")
-
-    def configureSynChan(self, synObj, synParams={}):
-        '''Configure synapse. If no parameters are given then use the default
-        values. 
-
-        '''
-        assert(isinstance(synObj, moose.SynChan))
-        utils.dump("SYNAPSE"
-                , "Configuring SynChan"
-                )
-        synObj.tau1 = synParams.get('tau1', 5.0)
-        synObj.tau2 = synParams.get('tau2', 1.0)
-        synObj.Gk = synParams.get('Gk', 1.0)
-        synObj.Ek = synParams.get('Ek', 0.0)
-        synObj.synapse.num = synParams.get('synapse_num', 1)
-        synObj.synapse.delay = synParams.get('delay', 1.0)
-        synObj.synapse.weight = synParams.get('weight', 1.0)
-        return synObj
diff --git a/python/libmumbl/nml_parser/NeuroML.py b/python/libmumbl/nml_parser/NeuroML.py
deleted file mode 100644
index 5e56fe34185f2b9edb1e935f77322867408c1e5b..0000000000000000000000000000000000000000
--- a/python/libmumbl/nml_parser/NeuroML.py
+++ /dev/null
@@ -1,153 +0,0 @@
-"""
-NeuroML.py is the preferred interface to read NeuroML files.
-
-    Instantiate NeuroML class, and thence use method: readNeuroMLFromFile(...)
-    to load NeuroML from a file:
-
- - The file could contain all required levels 1, 2 and 3 - Network , Morph and
- Channel.
-
- - The file could have only L3 (network) with L1 (channels/synapses) and L2
- (cells) spread over multiple files; these multiple files should be in the same
- directory named as <chan/syn_name>.xml or <cell_name>.xml or
- <cell_name>.morph.xml (essentially as generated by neuroConstruct's export).
-
- - But, if your lower level L1 and L2 xml files are elsewise, use the separate
- Channel, Morph and NetworkML loaders in moose.neuroml.<...> .
-
-For testing, you can also call this from the command line with a neuroML file
-as argument.
-
-CHANGE LOG:
-
- Description: class NeuroML for loading NeuroML from single file into MOOSE
-
- Version 1.0 by Aditya Gilra, NCBS, Bangalore, India, 2011 for serial MOOSE
-
- Version 1.5 by Niraj Dudani, NCBS, Bangalore, India, 2012, ported to parallel
-
- MOOSE Version 1.6 by Aditya Gilra, NCBS, Bangalore, India, 2012, further
- changes for parallel MOOSE.
-
- Dilawar Singh; Fixed parsing errors when parsing some standard models.
-
-"""
-
-from xml.etree import cElementTree as ET
-import sys
-import MorphML
-import NetworkML
-import ChannelML
-import moose
-import moose.utils as utils
-import moose.neuroml.utils as mnu
-import core.config as config
-import logging
-from os import path
-
-current_version = sys.version_info
-if current_version < (2, 6):
-    pythonLessThan26 = True
-else:
-    pythonLessThan26 = False
-
-class NeuroML(object):
-
-    """
-    This class parses neuroml models and build moose-data structures.
-
-    """
-    def __init__(self):
-        self.lengthUnits = ""
-        self.temperature = 25
-        self._CELSIUS_default = ""
-        self.temperature_default = True
-        self.nml_params = None
-        self.channelUnits = "Physiological Units"
-        moose.Neutral('/neuroml')
-        self.libraryPath = config.libraryPath
-        self.cellPath = config.cellPath
-
-    def readNeuroMLFromFile(self, filename, params=dict()):
-
-        """
-        For the format of params required to tweak what cells are loaded,
-        refer to the doc string of NetworkML.readNetworkMLFromFile().
-        Returns (populationDict,projectionDict),
-        see doc string of NetworkML.readNetworkML() for details.
-        """
-
-        utils.dump("STEP"
-                , "Loading neuroml file `{0}` ... ".format(filename)
-                )
-        # creates /library in MOOSE tree; elif present, wraps
-        tree = ET.parse(filename)
-        root_element = tree.getroot()
-        self.modelDir = path.dirname(path.abspath(filename))
-        try:
-            self.lengthUnits = root_element.attrib['lengthUnits']
-        except KeyError:
-            self.lengthUnits = root_element.attrib['length_units']
-        except:
-            utils.dump("WARN"
-                    , "Failed to get length_unit"
-                    , sys.exec_info()[0]
-                    )
-            raise
-
-        # gets replaced below if tag for temperature is present
-        self.temperature = self._CELSIUS_default
-
-        for mp in root_element.findall('.//{'+mnu.meta_ns+'}property'):
-            tagname = mp.attrib['tag']
-            if 'temperature' in tagname:
-                self.temperature = float(mp.attrib['value'])
-                self.temperature_default = False
-        if self.temperature_default:
-            logging.debug(
-                    "Using default temperature of %s C".format(self.temperature)
-                    )
-        self.nml_params = {
-                'temperature': self.temperature
-                , 'model_dir': self.modelDir
-        }
-
-        mmlR = MorphML.MorphML(self.nml_params)
-        self.cellsDict = {}
-        for cells in root_element.findall('.//{'+mnu.neuroml_ns+'}cells'):
-            for cell in cells.findall('.//{'+mnu.neuroml_ns+'}cell'):
-                cellDict = mmlR.readMorphML(
-                        cell
-                        , params={}
-                        , lengthUnits=self.lengthUnits
-                        )
-                self.cellsDict.update(cellDict)
-
-        nmlR = NetworkML.NetworkML(self.nml_params)
-        populationDict, projectionDict = nmlR.readNetworkML(
-                root_element
-                , self.cellsDict
-                , params=params
-                , lengthUnits=self.lengthUnits
-                )
-
-        # Loading channels and synapses into MOOSE into neuroml library
-        cmlR = ChannelML.ChannelML(self.nml_params)
-        return populationDict, projectionDict
-
-    def channelToMoose(self, cmlR, channels):
-        for channel in channels.findall('.//{'+mnu.cml_ns+'}channel_type'):
-            # ideally I should read in extra params
-            # from within the channel_type element and put those in also.
-            # Global params should override local ones.
-            cmlR.readChannelML(channel, params={}, units=self.channelUnits)
-        for synapse in channels.findall('.//{'+mnu.cml_ns+'}synapse_type'):
-            cmlR.readSynapseML(synapse, units=self.channelUnits)
-        for ionConc in channels.findall('.//{'+mnu.cml_ns+'}ion_concentration'):
-            cmlR.readIonConcML(ionConc, units=self.channelUnits)
-
-
-    def loadNML(self, nml):
-        neuromlR = NeuroML()
-        xml, filename = nml
-        return neuromlR.readNeuroMLFromFile(filename)
diff --git a/python/libmumbl/nml_parser/__init__.py b/python/libmumbl/nml_parser/__init__.py
deleted file mode 100644
index 8b137891791fe96927ad78e64b0aad7bded08bdc..0000000000000000000000000000000000000000
--- a/python/libmumbl/nml_parser/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/python/libmumbl/nml_parser/importer.py b/python/libmumbl/nml_parser/importer.py
deleted file mode 100644
index 186f6a0a2f9dfb14eb0d673ccf2485b1a1085b45..0000000000000000000000000000000000000000
--- a/python/libmumbl/nml_parser/importer.py
+++ /dev/null
@@ -1,64 +0,0 @@
-
-
-__author__  = "Dilawar Singh <dilawars@ncbs.res.in>"
-__date__    = "Mon 21 Oct 2013 11:37:01 PM IST"
-__version__ = "1.0"
-__credits__ = "NCBS"
-
-__log__     = """
-
-
-"""
-# Basic imports
-import os 
-import sys 
-import logging 
-import debug 
-
-logger = logging.getLogger('multiscale')
-try:
-    import cElementTree as etree
-    debug.printDebug("DEBUG", "running with lxml.etree")
-except ImportError:
-    try:
-        # Python 2.5
-        import xml.etree.cElementTree as etree
-        debug.printDebug("DEBUG", "running with cElementTree")
-    except ImportError:
-        try:
-            # Python 2.5
-            import xml.etree.cElementTree as etree
-            debug.printDebug("DEBUG", "running with ElementTree")
-        except ImportError:
-            try:
-              # normal cElementTree install
-              import cElementTree as etree
-              debug.printDebug("DEBUG", "running with cElementTree")
-            except ImportError:
-                try:
-                    # normal ElementTree install
-                    import elementtree.ElementTree as etree
-                    debug.printDebug("DEBUG", "running with ElementTree")
-                except ImportError:
-                    try : 
-                      import lxml.etree as etree
-                    except ImportError :
-                        debug.prefix("FATAL", "Failed to import ElementTree")
-                        os._exit(1)
-
-def ifPathsAreValid(paths) :
-  ''' Verify if path exists and are readable. '''
-  if paths.nml :
-    if os.path.isfile(paths.nml) : pass
-    else :
-      debug.printDebug("ERROR", "Filepath {0} is not valid".format(paths.nml))
-      return False
-  if paths.sbml :
-    if os.path.isfile(paths.sbml) : pass 
-    else :
-      debug.printDebug("ERROR", "Filepath {0} is not valid".format(paths.sbml))
-      return False
-  return True
-
-
-
diff --git a/python/libmumbl/nml_parser/parser.py b/python/libmumbl/nml_parser/parser.py
deleted file mode 100644
index 4e0c4aa846571a674563f4b2421821e951714ef5..0000000000000000000000000000000000000000
--- a/python/libmumbl/nml_parser/parser.py
+++ /dev/null
@@ -1,62 +0,0 @@
-# Basic imports
-import os
-import sys
-import logging
-import debug.debug as debug
-import inspect
-
-logger = logging.getLogger('multiscale')
-from lxml import etree
-
-import collections
-def parseAndValidateWithSchema(modelName, modelPath) :
-
-    prefixPath = ''
-    if modelName == 'xml' :
-        schemaPath = os.path.join(prefixPath, 'schema/moose/moose.xsd')
-        if not os.path.isfile(schemaPath) :
-            debug.printDebug("WARN", "Schema {0} does not exists..".format(schemaPath))
-
-    try :
-        schemaH = open(schemaPath, "r")
-        schemaText = schemaH.read()
-        schemaH.close()
-    except Exception as e :
-        debug.printDebug("WARN", "Error reading schema for validation."+
-          " Falling back to validation-disabled parser."
-          + " Failed with error {0}".format(e))
-        return parseWithoutValidation(modelName, modelPath)
-        # Now we have the schema text
-    schema = etree.XMLSchema(etree.XML(schemaText))
-    xmlParser = etree.XMLParser(schema=schema, remove_comments=True)
-    with open(modelPath, "r") as xmlTextFile :
-        return etree.parse(xmlTextFile, xmlParser)
-
-def parseWithoutValidation(modelName, modelPath) :
-    xmlParser = etree.XMLParser(remove_comments=True)
-    try :
-        xmlRootElem = etree.parse(modelPath, xmlParser)
-    except Exception as e :
-        debug.printDebug("ERROR", "Parsing of {0} failed.".format(modelPath))
-        debug.printDebug("DEBUG", "Error: {0}".format(e))
-        raise RuntimeError, "Failed to parse XML"
-    return xmlRootElem
-
-def parseXMLs(commandLineArgs, validate=False) :
-    xmlRootElemDict = collections.defaultdict(list)
-    models = vars(commandLineArgs)
-    for model in models :
-        if models[model] :
-            for modelPath in models[model] :
-                debug.printDebug("INFO", "Parsing {0}".format(models[model]))
-                if validate :
-                    # parse model and valid it with schama
-                    modelXMLRootElem = parseAndValidateWithSchema(model, modelPath)
-                else :
-                    # Simple parse the model without validating it with schema.
-                    modelXMLRootElem = parseWithoutValidation(model, modelPath)
-                if modelXMLRootElem :
-                    xmlRootElemDict[model].append((modelXMLRootElem, modelPath))
-    assert len(xmlRootElemDict) > 0
-    return xmlRootElemDict
-
diff --git a/python/libmumbl/nml_parser/utils.py b/python/libmumbl/nml_parser/utils.py
deleted file mode 100644
index ad9f05159876e1ef1b41e3c7e5017562c522c597..0000000000000000000000000000000000000000
--- a/python/libmumbl/nml_parser/utils.py
+++ /dev/null
@@ -1,274 +0,0 @@
-## Description: utility functions used while loading NeuroML L1,2,3 files.
-## Version 1.0 by Aditya Gilra, NCBS, Bangalore, India, 2011 for serial MOOSE
-## Version 1.5 by Niraj Dudani, NCBS, Bangalore, India, 2012, modified for parallel MOOSE
-## Version 1.6 by Aditya Gilra, NCBS, Bangalore, India, 2012, minor changes for parallel MOOSE
-
-"""
-Some useful constants like namespaces are defined.
-And they can be set in ElementTree root element via set_neuroml_namespaces_attribs(neuromlroot).
-Use tweak_model(root_element, params) to exclude certain populations and projections
-while still including certain others.
-indent(...) is an in-place prettyprint formatter copied from http://effbot.org/zone/element-lib.htm
-"""
-
-from xml.etree import cElementTree as ET
-from xml.etree import ElementTree as slowET
-from math import *
-import moose
-import os
-
-neuroml_debug = False
-
-neuroml_ns='http://morphml.org/neuroml/schema'
-nml_ns='http://morphml.org/networkml/schema'
-mml_ns='http://morphml.org/morphml/schema'
-bio_ns='http://morphml.org/biophysics/schema'
-cml_ns='http://morphml.org/channelml/schema'
-meta_ns='http://morphml.org/metadata/schema'
-xsi_ns='http://www.w3.org/2001/XMLSchema-instance'
-
-### ElementTree parse works an order of magnitude or more faster than minidom
-### BUT it doesn't keep the original namespaces,
-## from http://effbot.org/zone/element-namespaces.htm , I got _namespace_map
-## neuroml_ns, bio_ns, mml_ns, etc are defined above
-slowET._namespace_map[neuroml_ns] = 'neuroml'
-slowET._namespace_map[nml_ns] = 'nml'
-slowET._namespace_map[mml_ns] = 'mml'
-slowET._namespace_map[bio_ns] = 'bio'
-slowET._namespace_map[cml_ns] = 'cml'
-slowET._namespace_map[meta_ns] = 'meta'
-slowET._namespace_map[xsi_ns] = 'xsi'
-
-### cElementTree is much faster than ElementTree and is API compatible with the latter,
-### but instead of _namespace_map above, use register_namespace below ...
-### but this works only with python2.7 onwards, so stick to above,
-### with import elementtree.ElementTree alongwith importing cElementTree as at
-### http://dev.blogs.nuxeo.com/2006/02/elementtree-serialization-namespace-prefixes.html
-#ET.register_namespace('neuroml',neuroml_ns)
-#ET.register_namespace('nml',nml_ns)
-#ET.register_namespace('mml',mml_ns)
-#ET.register_namespace('bio',bio_ns)
-#ET.register_namespace('cml',cml_ns)
-#ET.register_namespace('meta',meta_ns)
-#ET.register_namespace('xsi',xsi_ns)
-
-CELSIUS_default = 32.0 # deg C # default temperature if meta:property tag for temperature is not present
-ZeroCKelvin = 273.15 # zero dec C in Kelvin
-VMIN = -0.1 # Volts
-VMAX = 0.1 # Volts
-NDIVS = 200 # number
-dv = ( VMAX - VMIN ) / NDIVS # Volts
-
-def set_neuroml_namespaces_attribs(neuromlroot):
-    set_attrib_if_not_found(neuromlroot,"xmlns",neuroml_ns)
-    set_attrib_if_not_found(neuromlroot,"xmlns:nml",nml_ns)
-    set_attrib_if_not_found(neuromlroot,"xmlns:mml",mml_ns)
-    set_attrib_if_not_found(neuromlroot,"xmlns:bio",bio_ns)
-    set_attrib_if_not_found(neuromlroot,"xmlns:cml",cml_ns)
-    set_attrib_if_not_found(neuromlroot,"xmlns:meta",meta_ns)
-    ## later doc.write() assigns the xsi namespace a second time
-    ## causing double definition and problem with xsltproc,
-    ## hence commenting it out here.
-    #set_attrib_if_not_found(neuromlroot,"xmlns:xsi",xsi_ns)
-
-def set_attrib_if_not_found(elem, name, value):
-    if elem.get(name) is None:
-        elem.set(name,value)
-
-def tweak_model(root_element, params):
-    if 'excludePopulations' in params: # if params has key 'excludePopulations'
-        ## both excludePopulations and excludeProjections must be present together
-        pruneExcludes(root_element,params['excludePopulations'],params['excludeProjections'])
-    if 'onlyInclude' in params: # if params has key 'onlyInclude'
-        keepOnlyInclude(root_element,params['onlyInclude'])
-
-def pruneExcludes(network, excludepops, excludeprojs):
-    """
-    remove the populations in the excludepops list
-    remove the projections in the excludeprojs list
-    """
-    populations = network.find(".//{"+nml_ns+"}populations")
-    pop_remove_list = []
-    for population in populations.findall(".//{"+nml_ns+"}population"):
-        populationname = population.attrib["name"]
-        ## if any of the name-s in exclude_list are a SUBSTRING
-        ## of the name of the neuroml population, mark it for removal
-        for name in excludepops:
-            if name in populationname: # substring
-                pop_remove_list.append(population)
-    ## remove only unique names,
-    ## else you could end up trying to remove same population twice
-    for population in set(pop_remove_list):
-        populations.remove(population)
-
-    projections = network.find(".//{"+nml_ns+"}projections")
-    proj_remove_list = []
-    for projection in projections.findall(".//{"+nml_ns+"}projection"):
-        projectionname = projection.attrib["name"]
-        ## if any of the name-s in exclude_list are a SUBSTRING
-        ## of the name of the neuroml projection, mark it for removal
-        for name in excludeprojs:
-            if name in projectionname: # substring
-                proj_remove_list.append(projection)
-    ## remove only unique names,
-    ## else you could end up trying to remove same projection twice
-    for projection in set(proj_remove_list):
-        projections.remove(projection)
-
-def keepOnlyInclude(network, onlyInclude):
-    """
-    Keep only the cells that are in onlyInclude['includePopulation']
-    and also keep cells that are connected to cells in onlyInclude['includePopulation']
-    and keep connections to any of the cells in onlyInclude['includePopulation'].
-    Prune the extraneous connections
-    but keep those connections in onlyInclude['includeProjections']
-    on cells connected to those in onlyInclude['includePopulation']
-    """
-    ### Remove the connections that do not connect to cells in onlyInclude.
-    ### Simultaneously build up a list of cells 'includeCellsDict' that connect to cells in onlyInclude.
-    ### Of course this includeCellDict must have the originally included cells!
-    ### At the end of this pruning, even if some population-s / projection-s have no elements,
-    ### it doesn't matter, as this findall() returns an empty list and not None - so no error.
-    ### Further I am not changing the 'size' attrib in <instances> and <connections>,
-    ### as it's not used by this reader and I'm not saving the network after pruning.
-    ### Do not prune 'includeProjections' immediately;
-    ### prune them later avoiding second order cells in includeCellsDict.
-    includepopname = onlyInclude['includePopulation'][0]
-    includecellids = onlyInclude['includePopulation'][1]
-    ## first of all, include those primary cells that the user instructs.
-    includeCellsDict = {includepopname:includecellids}
-    ## projections 'includeProjs' will be pruned later, keeping connections to second order cells.
-    includeProjs = []
-    print("removing obviously extra connections in ... ")
-    for projection in network.findall(".//{"+nml_ns+"}projection"):
-        projname = projection.attrib['name']
-        includeProj = False
-        ## check if any of the given includeprojname is a substring of this projname
-        for includeprojname in onlyInclude['includeProjections']:
-            if includeprojname in projname:
-                includeProj = True
-        ## if it is a substring, add this projection
-        ## to the list of projections to be pruned later
-        if includeProj:
-            includeProjs.append(projection)
-        source = projection.attrib["source"]
-        target = projection.attrib["target"]
-        print(projname, source, target)
-        connections = projection.find(".//{"+nml_ns+"}connections")
-        if connections is not None:
-            for connection in connections.findall(".//{"+nml_ns+"}connection"):
-                pre_cell_id = connection.attrib['pre_cell_id']
-                ## is the user-included cell a source cell of the connection?
-                includecellinsource = (pre_cell_id in includecellids and includepopname==source)
-                post_cell_id = connection.attrib['post_cell_id']
-                ## is the user-included cell a target cell of the connection?
-                includecellintarget = (post_cell_id in includecellids and includepopname==target)
-                ## the second-order cell connected to the user-included cell must also be kept
-                if includecellinsource:
-                    ## since source is included, include the target also
-                    ## there can be self connections between the same population i.e. same source and target
-                    try:
-                        includeCellsDict[target].append(post_cell_id)
-                    except KeyError: # create this population entry in the dictionary if not present
-                        includeCellsDict[target] = [post_cell_id]
-                elif includecellintarget:
-                    ## since target is included, include the source also, except if source is a file
-                    if 'file' not in source:
-                        try:
-                            includeCellsDict[source].append(pre_cell_id)
-                        except KeyError: # create this population entry in the dictionary if not present
-                            includeCellsDict[source] = [pre_cell_id]
-                else:
-                    ## this connection is extraneous
-                    ## but remove this connection only if
-                    ## it is not part of the projections to be pruned later
-                    if not includeProj:
-                        connections.remove(connection)
-
-    ## convert includeCellsDict elements to set-s rather than lists
-    ## to have only unique cell_ids and save time below.
-    for key in includeCellsDict:
-        includeCellsDict[key] = set(includeCellsDict[key])
-    
-    print("removing extra cells ... ")
-    ### remove the cells that are not in includeCellsDict
-    populations = network.find(".//{"+nml_ns+"}populations")
-    for population in network.findall(".//{"+nml_ns+"}population"):
-        popname = population.attrib["name"]
-        if popname in list(includeCellsDict.keys()):
-            includecellids = includeCellsDict[popname]
-            instances = population.find(".//{"+nml_ns+"}instances")
-            for instance in instances.findall(".//{"+nml_ns+"}instance"):
-                ## not a connected cell, so remove
-                if instance.attrib['id'] not in includecellids:
-                    instances.remove(instance)
-        else: ## this whole population is not required!
-            populations.remove(population)
-
-    ### Prune the 'includeProjections' that we skipped pruning before,
-    ### while keeping connections to second order cells!
-    for projection in includeProjs:
-        print("removing projection",projection.attrib['name'],\
-            "keeping second-order connections.")
-        source = projection.attrib["source"]
-        target = projection.attrib["target"]
-        ## boolean: True if includeCellsDict has key source
-        source_in_includeCellsDict = source in includeCellsDict
-        ## boolean: True if the word 'file' occurs in str source
-        file_in_source = 'file' in source
-        ## boolean: True if includeCellsDict has key target
-        target_in_includeCellsDict = target in includeCellsDict
-        connections = projection.find(".//{"+nml_ns+"}connections")
-        for connection in connections.findall(".//{"+nml_ns+"}connection"):
-            ## is the included cell a source cell of the connection?
-            ## keep 'file' as source also.
-            if file_in_source:
-                includecellinsource = True
-            elif source_in_includeCellsDict and \
-                    connection.attrib['pre_cell_id'] in includeCellsDict[source]:
-                includecellinsource = True
-            else: includecellinsource = False
-            ## is the included cell a target cell of the connection?
-            if target_in_includeCellsDict and \
-                    connection.attrib['post_cell_id'] in includeCellsDict[target]:
-                includecellintarget = True
-            else: includecellintarget= False
-            ## this connection is extraneous
-            ## if either sourcecell or targetcell is not included.
-            if not includecellinsource or not includecellintarget:
-                ## remove is a very slow operation!
-                connections.remove(connection)
-
-def indent(elem, level=0):
-    """ in-place prettyprint formatter copied from http://effbot.org/zone/element-lib.htm
-    first call indent(root, level=0), and then doc.write(filename) ."""
-    i = "\n" + level*"  "
-    if len(elem):
-        if not elem.text or not elem.text.strip():
-            elem.text = i + "  "
-        if not elem.tail or not elem.tail.strip():
-            elem.tail = i
-        for elem in elem:
-            indent(elem, level+1)
-        if not elem.tail or not elem.tail.strip():
-            elem.tail = i
-    else:
-        if level and (not elem.tail or not elem.tail.strip()):
-            elem.tail = i
-
-## make a list of safe functions possible to be used safely in eval()
-safe_list = ['acos', 'asin', 'atan', 'atan2', 'ceil',
-    'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor',
-    'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf',
-    'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
-## use the list to filter the local namespace
-safe_dict = dict([ (k, locals().get(k, None)) for k in safe_list ])
-## add any needed builtins back in.
-safe_dict['abs'] = abs
-
-def find_first_file(name, path):
-    """ Finds and returns the first occurence of the filename in the directory tree under a given path.
-    If nothing is returned, return value defaults to None.  """
-    for root, dirs, files in os.walk(path):
-        if name in files:
-            return os.path.join(root, name)
diff --git a/python/libmumbl/run_granule98_hsolve.sh b/python/libmumbl/run_granule98_hsolve.sh
deleted file mode 100755
index 21ba7492a3f4fa468372715cfcc4f21c31969481..0000000000000000000000000000000000000000
--- a/python/libmumbl/run_granule98_hsolve.sh
+++ /dev/null
@@ -1,37 +0,0 @@
-#!/bin/bash
-set +e
-
-# Set pythonpath
-# If first argument is not "d" then normal execution else run inside python
-# debugger.
-
-function runCode 
-{
-  $PYC main.py \
-    --nml ./models/neuroml/v1.8/GranuleCell/GranuleCell.net.xml \
-    --mumbl ./models/mumbl.xml \
-    --config ./models/neuroml/v1.8/GranuleCell/config.xml
-  #twopi -Teps graphs/moose.dot > graphs/topology.eps
-}
-
-function testPythonCode 
-{
-    pf=$1
-    echo "Checking .... $pf"
-    pylint -E $pf
-}
-
-PYC=python2.7
-if [ "$1" == "d" ]; then
-  PYC=pydb
-  runCode
-elif [ "$1" == "c" ]; then 
-    FILES=$(find . -name "*.py" -type f)
-    for pf in $FILES; do
-        testPythonCode $pf
-    done
-else
-  PYC=python2.7
-  runCode
-fi
-
diff --git a/python/libmumbl/schemas/NetworkML_v1.8.1.xsd b/python/libmumbl/schemas/NetworkML_v1.8.1.xsd
deleted file mode 100644
index 231e62569a4d1542fad18c7d15b096dc8c97792c..0000000000000000000000000000000000000000
--- a/python/libmumbl/schemas/NetworkML_v1.8.1.xsd
+++ /dev/null
@@ -1,976 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<xs:schema targetNamespace="http://morphml.org/networkml/schema"
-    xmlns:xs="http://www.w3.org/2001/XMLSchema"
-    xmlns="http://morphml.org/networkml/schema"
-    xmlns:meta="http://morphml.org/metadata/schema"
-    xmlns:mml="http://morphml.org/morphml/schema"
-    xmlns:bio="http://morphml.org/biophysics/schema"
-    elementFormDefault="qualified" attributeFormDefault="unqualified">
-
-<!--
-    This file specifies a number of elements needed by NeuroML Level 3 compliant files
-
-    Funding for this work has been received from the Medical Research Council and the 
-    Wellcome Trust. This file was initially developed as part of the neuroConstruct project
-    
-    Author: Padraig Gleeson
-    Copyright 2009 University College London
-    
-    This program is free software; you can redistribute it and/or modify
-    it under the terms of the GNU General Public License as published by
-    the Free Software Foundation; either version 2 of the License, or
-    (at your option) any later version.
-    
-    This program is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-    GNU General Public License for more details.
-
--->
-
-    <xs:import namespace="http://morphml.org/metadata/schema"
-    schemaLocation="../Level1/Metadata_v1.8.1.xsd"/>
-    
-
-    <xs:import namespace="http://morphml.org/biophysics/schema"
-    schemaLocation="../Level2/Biophysics_v1.8.1.xsd"/>
-
-
-      <xs:annotation>
-        <xs:documentation>The specification of populations and projections which allows network connections to be encoded in NeuroML</xs:documentation>
-         </xs:annotation>
-
-        <xs:element name="networkml" type="NetworkML">
-            <xs:annotation>
-                    <xs:documentation>The root element. 
-                    Note: this element will only be present in a standalone NetworkML file (i.e. no cells or channels defined in the file).
-                    For files covering many levels, neuroml will be the root element</xs:documentation>
-            </xs:annotation>
-        </xs:element>
-
-        <xs:complexType name="NetworkML">
-            <xs:annotation>
-                    <xs:documentation>The main elements which make up a NetworkML compliant document. </xs:documentation>
-            </xs:annotation>
-
-            <xs:sequence>
-                <xs:group ref="meta:metadata"/>
-                <xs:group ref="CoreNetworkElements"/>
-            </xs:sequence>
-
-            <xs:attribute name="name" type="xs:string" use="optional"/> 
-
-        
-        <xs:attribute name="lengthUnits" type="meta:LengthUnits" use="optional">
-            <xs:annotation>
-                <xs:documentation>Unit of all length measurements. Usually has the value &lt;b&gt;micrometer&lt;/b&gt;. Note: length_units will be the preferred form in v2.0</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>
-        
-        <xs:attribute name="length_units" type="meta:LengthUnits" use="optional">
-            <xs:annotation>
-                <xs:documentation>Unit of all length measurements. Usually has the value &lt;b&gt;micrometer&lt;/b&gt;. Note: length_units will be the preferred form in v2.0</xs:documentation>
-            </xs:annotation>
-        </xs:attribute>
-
-            <xs:attribute name="volumeUnits" type="meta:VolumeUnits" use="optional" default="cubic_millimeter">  <!-- Note: changed to the American English spelling in v1.8.1...-->
-                    <xs:annotation>
-                            <xs:documentation>Unit of all volume measurements.</xs:documentation>
-                    </xs:annotation>
-            </xs:attribute>
-
-        </xs:complexType>
-
-
-
-
-        <xs:group name="CoreNetworkElements">
-            <xs:annotation>
-                <xs:documentation>The elements needed to specify a network connection</xs:documentation>
-            </xs:annotation>
-
-            <xs:sequence>
-
-                 <xs:element name="populations" type="Populations">
-                    <xs:annotation>
-                        <xs:documentation>The least that's needed in a network is a population of cells...</xs:documentation>
-                    </xs:annotation>
-                </xs:element>
-
-                <xs:element name="projections" type="Projections" minOccurs="0">
-                    <xs:annotation>
-                        <xs:documentation>In theory there can be no projections, if the file is intended only to specify positions</xs:documentation>
-                    </xs:annotation>
-                </xs:element>
-
-                <xs:element name="inputs" type="Inputs" minOccurs="0">
-                    <xs:annotation>
-                        <xs:documentation>No inputs need be specified</xs:documentation>
-                    </xs:annotation>
-                </xs:element>
-
-            </xs:sequence>
-            
-        </xs:group>
-
-
-         <xs:complexType name="Populations">
-            <xs:annotation>
-                <xs:documentation>The list of cell populations</xs:documentation>
-            </xs:annotation>
-            <xs:sequence>
-                <xs:group ref="meta:metadata"/>
-                <xs:element name="population" type="Population" maxOccurs="unbounded"/>
-            </xs:sequence>
-        </xs:complexType>
-
-
-         <xs:complexType name="Projections">
-            <xs:annotation>
-                <xs:documentation>The list of projections from one cell population to another</xs:documentation>
-            </xs:annotation>
-            <xs:sequence>
-                <xs:group ref="meta:metadata"/>
-                <xs:element name="projection" type="Projection" minOccurs="1" maxOccurs="unbounded"/>
-            </xs:sequence>
-
-            <xs:attribute name="units" type="meta:Units" use="required">
-                <xs:annotation>
-                    <xs:documentation>Unit system of all quantities in the projection descriptions, e.g. synaptic time constants</xs:documentation>
-                </xs:annotation>
-            </xs:attribute>
-
-        </xs:complexType>
-        
-        
-
-         <xs:complexType name="Inputs">
-            <xs:annotation>
-                <xs:documentation>The list of electrical inputs into the cells. This should be extended to allow voltage clamp inputs...</xs:documentation>
-            </xs:annotation>
-            <xs:sequence>
-                <xs:group ref="meta:metadata"/>
-                <xs:element name="input" type="Input" minOccurs="1" maxOccurs="unbounded"/>
-            </xs:sequence>
-
-            <xs:attribute name="units" type="meta:Units" use="required">
-                <xs:annotation>
-                    <xs:documentation>Unit system of all quantities in the input description, e.g. input current amplitudes</xs:documentation>
-                </xs:annotation>
-            </xs:attribute>
-
-        </xs:complexType>
-        
-
-        <xs:complexType name="Input">
-            <xs:annotation>
-                <xs:documentation>Description of a single electrical input to a number of cells</xs:documentation>
-            </xs:annotation>
-
-            <xs:sequence>
-                <xs:group ref="meta:metadata"/>
-
-                <xs:choice>
-                    <xs:annotation>
-                        <xs:documentation>Currently either a pulse input or a random spiking input are allowed</xs:documentation>
-                    </xs:annotation>
-                    <xs:element name="pulse_input" type="PulseInput"/>
-                    <xs:element name="random_stim" type="RandomStim"/>
-                </xs:choice>
-                
-                  <xs:element name="target" type="InputTarget"/>
-                
-            </xs:sequence>
-
-
-            <xs:attribute name="name" type="xs:string" use="required"/>
-
-        </xs:complexType>
-
-        <xs:complexType name="PulseInput">
-            <xs:annotation>
-                <xs:documentation>A single input pulse. Note: this should be changed to allow easier specifications of
-                                  pulse trains, input protocols, etc.</xs:documentation>
-                </xs:annotation>    
-                
-                <xs:attribute name="delay" type="bio:TimeValue" use="required"/>
-                <xs:attribute name="duration" type="bio:TimeValue" use="required"/>
-                <xs:attribute name="amplitude" type="bio:CurrentValue" use="required"/>
-                
-        </xs:complexType>
-
-        <xs:complexType name="RandomStim">
-            <xs:annotation>
-                <xs:documentation>A random stimulation at a specific frequency. Note: can be interpreted differently by different simulators!!</xs:documentation>
-                </xs:annotation>
-
-                <xs:attribute name="frequency" type="bio:FrequencyValue" use="required"/>
-                <xs:attribute name="synaptic_mechanism" type="xs:string" use="required">
-                    <xs:annotation>
-                        <xs:documentation>The name of a synaptic mechanism which will provides the conductance change.
-                        This will be fired once every 'spike' at the given frequency</xs:documentation>
-                    </xs:annotation>
-                </xs:attribute>
-
-        </xs:complexType>
-
-        <xs:complexType name="RandomStimInstance">
-            <xs:annotation>
-                <xs:documentation>Instance/site specific random stimulation at a specific frequency. Note: can be interpreted differently by different simulators!!</xs:documentation>
-                </xs:annotation>
-
-                <xs:attribute name="frequency" type="bio:FrequencyValue" use="required"/>
-               
-        </xs:complexType>
-
-        <xs:complexType name="InputTarget">
-            <xs:annotation>
-                <xs:documentation>Specifies the cell group and which cells/segments to apply the stimulation</xs:documentation>
-            </xs:annotation>    
-                
- 
-            <xs:sequence>
-                <xs:group ref="meta:metadata"/>
-                <xs:choice>
-                    <xs:annotation>
-                        <xs:documentation>As with populations/projections, there are two ways to specify the locations of the 
-                                          stimulations: a list of cell location instances and a template for choosing the cells.</xs:documentation>
-                    </xs:annotation>
-
-                    <xs:element name="sites" type="InputSites"/>
-                    <xs:element name="site_pattern" type="InputSitePattern"/>
-
-                </xs:choice>
-            </xs:sequence>
-            
-           <xs:attribute name="cell_group" type="xs:string" use="optional">
-                <xs:annotation>
-                    <xs:documentation>The cell group to which to apply the stimulation. Note for v2.0 population is the preferred name of this attribute (not cell_group).</xs:documentation>
-                
-                </xs:annotation>
-            </xs:attribute>
-            
-            
-           <xs:attribute name="population" type="xs:string" use="optional">
-                <xs:annotation>
-                    <xs:documentation>The cell group to which to apply the stimulation. Note for v2.0 population is the preferred name of this attribute (not cell_group).</xs:documentation>
-                </xs:annotation>
-            </xs:attribute>
-                
-        </xs:complexType>
-        
-        
-
-        <xs:complexType name="InputSitePattern">
-            <xs:annotation>
-                <xs:documentation>Information on the number of cells on which to apply inputs. 
-                Currently only two, but could be expanded to include other scenarios, e.g. all cells in 3d region.</xs:documentation>
-            </xs:annotation>
-
-            <xs:choice>
-                <!-- Lots more scenarios could be described here... -->
-                <xs:element name="all_cells">
-                    <xs:annotation>
-                        <xs:documentation>Apply input on all cells in group</xs:documentation>
-                    </xs:annotation>
-                    <xs:complexType/>
-                </xs:element>
-                <xs:element name="percentage_cells">
-                    <xs:annotation>
-                        <xs:documentation>Apply input to a certain percentage of cells in a group</xs:documentation>
-                    </xs:annotation>
-                    <xs:complexType>
-                        <xs:attribute name="percentage" type="meta:Percentage"/>
-                    </xs:complexType>
-                </xs:element>
-
-            </xs:choice>
-
-        </xs:complexType>
-        
-        
-        
-
-        <xs:complexType name="InputSites">
-            <xs:annotation>
-                <xs:documentation>The list of input sites</xs:documentation>
-            </xs:annotation>
-
-            <xs:sequence>
-                <xs:group ref="meta:metadata"/>
-                <xs:element name="site" type="InputSite" maxOccurs="unbounded"/>
-            </xs:sequence>
-            
-            <xs:attribute name="size" type="xs:nonNegativeInteger" use="optional">
-                <xs:annotation>
-                    <xs:documentation>The number of instances of inputs. 
-                    This is redundant information, but can be useful when the file is being parsed to allocate memory for an array of cells. 
-                    NOTE: likely to be required from v2.0</xs:documentation>
-                </xs:annotation>
-            </xs:attribute>
-
-        </xs:complexType>
-        
-        <xs:complexType name="InputSite">
-            <xs:annotation>
-                <xs:documentation>Specifies a location on a cell where input is received</xs:documentation>
-            </xs:annotation>
-
-
-                <xs:choice>
-                    <xs:annotation>
-                        <xs:documentation>Overrides global settings if there is a different value of pulse amplitude/rate, etc. for this site</xs:documentation>
-                    </xs:annotation>
-                    <xs:element name="pulse_input_instance" type="PulseInput" minOccurs="0"/>
-                    <xs:element name="random_stim_instance" type="RandomStimInstance" minOccurs="0"/>
-                </xs:choice>
-            
-            <xs:attribute name="cell_id" type="CellIdInNetwork" use="required"/>
-            <xs:attribute name="segment_id" type="meta:SegmentIdInCell" use="optional" default="0"/>
-            <xs:attribute name="fraction_along" type="meta:ZeroToOne" use="optional" default="0.5"/>
-                
-        </xs:complexType>
-
-
-        <xs:complexType name="Population">
-            <xs:annotation>
-                <xs:documentation>Description of a cell population of the same type</xs:documentation>
-            </xs:annotation>
-
-            <xs:sequence>
-                <xs:group ref="meta:metadata"/>
-               
-                <xs:element name="cell_type" type="xs:string" minOccurs="0">
-                    <xs:annotation>
-                        <xs:documentation>The cell type for this population. NOTE: an attribute value for cell_type WILL BE PREFERRED FORMAT IN v2.0. The option for this element will be removed!</xs:documentation>
-                    </xs:annotation>
-                </xs:element>
-
-                <xs:choice>
-                    <xs:annotation>
-                        <xs:documentation>Either instances or a specification of the location</xs:documentation>
-                    </xs:annotation>
-                    <xs:element name="instances" type="Instances"/>
-                    <xs:element name="pop_location" type="PopulationLocation"/>
-                </xs:choice>
-            </xs:sequence>
-
-
-            <xs:attribute name="name" type="xs:string" use="required">
-                <xs:annotation>
-                    <xs:documentation>The name of the population</xs:documentation>
-                </xs:annotation>
-            </xs:attribute>
-            <xs:attribute name="cell_type" type="xs:string" use="optional">
-                <xs:annotation>
-                    <xs:documentation>The cell type for this population. Optional now, but WILL BE PREFERRED FORMAT IN v2.0</xs:documentation>
-                </xs:annotation>
-            </xs:attribute>
-
-        </xs:complexType>
-
-
-
-
-        <xs:complexType name="Instances">
-            <xs:annotation>
-                <xs:documentation>Cell Instance position information</xs:documentation>
-            </xs:annotation>
-            <xs:sequence>
-                <xs:group ref="meta:metadata"/>
-                <xs:element name="instance" type="CellInstance" maxOccurs="unbounded"/>
-            </xs:sequence>
-            
-            
-            <xs:attribute name="size" type="xs:nonNegativeInteger" use="required">
-                <xs:annotation>
-                    <xs:documentation>The number of instances of cells for this population. 
-                    This is redundant information, but can be useful when the file is being parsed to allocate memory for an array of cells. 
-                    NOTE: required from v1.7.3</xs:documentation>
-                </xs:annotation>
-            </xs:attribute>
-            
-        </xs:complexType>
-
-
-        <xs:complexType name="Projection">
-            <xs:annotation>
-                <xs:documentation>Description of how one cell population makes synaptic connections with another</xs:documentation>
-            </xs:annotation>
-
-            <xs:sequence>
-                <xs:group ref="meta:metadata"/>
-                
-                <xs:element name="source" type="xs:string" minOccurs="0">
-                    <xs:annotation>
-                        <xs:documentation>Cell population where synaptic connection begins. NOTE: attribute values for source and target WILL BE THE PREFERRED FORMAT IN v2.0. The option for this element will be removed!</xs:documentation>
-                    </xs:annotation>
-                </xs:element>
-                <xs:element name="target" type="xs:string" minOccurs="0">
-                    <xs:annotation>
-                        <xs:documentation>Cell population where synaptic connection terminates. NOTE: attribute values for source and target WILL BE THE PREFERRED FORMAT IN v2.0. The option for this element will be removed!</xs:documentation>
-                    </xs:annotation>
-                </xs:element>
-
-                <xs:element name="synapse_props" type="GlobalSynapticProperties" maxOccurs="unbounded">
-                    <xs:annotation>
-                        <xs:documentation>Properties of a synapse associated with this connection.</xs:documentation>
-                    </xs:annotation>
-                </xs:element>
-
-                <xs:choice>
-                    <xs:annotation>
-                        <xs:documentation>Either an explicit list of the connections or a description of how to create the connections</xs:documentation>
-                    </xs:annotation>
-
-                    <xs:element name="connections" type="Connections"/>
-                    <xs:element name="connectivity_pattern" type="ConnectivityPattern"/>
-
-                </xs:choice>
-
-            </xs:sequence>
-
-            <xs:attribute name="name" type="xs:string" use="required">
-                <xs:annotation>
-                    <xs:documentation>String reference for the projection</xs:documentation>
-                </xs:annotation>
-            </xs:attribute>
-            <xs:attribute name="source" type="xs:string" use="optional">
-                <xs:annotation>
-                    <xs:documentation>Cell population where synaptic connection begins. Optional now, but WILL BE PREFERRED FORMAT IN v2.0</xs:documentation>
-                </xs:annotation>
-            </xs:attribute>
-            <xs:attribute name="target" type="xs:string" use="optional">
-                <xs:annotation>
-                    <xs:documentation>Cell population where synaptic connection terminates. Optional now, but WILL BE PREFERRED FORMAT IN v2.0</xs:documentation>
-                </xs:annotation>
-            </xs:attribute>
-        </xs:complexType>
-
-
-
-        <xs:complexType name="SynapseProperties">
-            <xs:annotation>
-                <xs:documentation>Pre v1.7.1 format for global synapse properties. Preferred format is GlobalSynapticProperties. This option will be disabled in v2.0</xs:documentation>
-            </xs:annotation>
-
-            <xs:sequence>
-
-                <xs:group ref="meta:metadata"/>
-
-                <xs:element name="synapse_type" type="xs:string"/>
-                <xs:element name="default_values" type="SynapseInternalProperties"/>
-            </xs:sequence>
-
-        </xs:complexType>
-
-
-
-        <xs:complexType name="GlobalSynapticProperties">
-            <xs:annotation>
-                <xs:documentation>Information on synapse type and default values for weight, delay, threshold, etc.</xs:documentation>
-            </xs:annotation>
-
-            <xs:complexContent>
-                <xs:extension base="SynapseInternalProperties">  
-                    
-                <xs:sequence>
-                    <xs:element name="synapse_type" type="xs:string" minOccurs="0">
-                        <xs:annotation>
-                            <xs:documentation>For compatability to pre v1.7.1. Will be removed in v2.0.</xs:documentation>
-                        </xs:annotation>
-                    </xs:element>
-                    <xs:element name="default_values" type="SynapseInternalProperties" minOccurs="0">
-                        <xs:annotation>
-                            <xs:documentation>For compatability to pre v1.7.1. Will be removed in v2.0.</xs:documentation>
-                        </xs:annotation>
-                    </xs:element>
-                </xs:sequence>
-            
-                    <xs:attribute name="synapse_type" type="xs:string"  use="optional">
-                        <xs:annotation>
-                            <xs:documentation>Including synapse_type as attribute in synapse_props will be required in v2.0</xs:documentation>
-                        </xs:annotation>
-                    </xs:attribute>
-
-                </xs:extension>
-            </xs:complexContent>  
-
-        </xs:complexType>
-        
-        
-        
-
-        <xs:complexType name="LocalSynapticProperties">
-            <xs:annotation>
-                <xs:documentation>Variables specifying a single synapse</xs:documentation>
-            </xs:annotation>
-
-            <xs:complexContent>
-                <xs:extension base="SynapseInternalProperties">
-
-                    <xs:attribute name="synapse_type" type="xs:string"  use="optional">
-                        <xs:annotation>
-                            <xs:documentation>Optional for a single synaptic connection. Only needed in the case where multiple synapses are 
-                            present at one connection and there are non default values for each synapse's weights, etc. This field gives the 
-                            name of the synapse type referred to.</xs:documentation>
-                        </xs:annotation>
-                    </xs:attribute>
-
-                </xs:extension>
-            </xs:complexContent>  
-
-        </xs:complexType>
-
-
-
-        <xs:complexType name="SynapseInternalProperties">
-            <xs:annotation>
-                <xs:documentation>Variables specifying a single synapse or default values for a set of connections</xs:documentation>
-            </xs:annotation>
-            
-            <xs:sequence>
-                <xs:group ref="meta:metadata"/>
-            </xs:sequence>
-
-            <xs:attribute name="internal_delay" type="bio:SynapticDelayValue"  use="optional" default ="0">
-                <xs:annotation>
-                    <xs:documentation>Delay due to diffusion across the synaptic cleft. If only one delay value is known, this can be used</xs:documentation>
-                </xs:annotation>
-            </xs:attribute>
-            <xs:attribute name="pre_delay" type="bio:SynapticDelayValue"  use="optional" default ="0">
-                <xs:annotation>
-                    <xs:documentation>Delay due to presynaptic mechanism</xs:documentation>
-                </xs:annotation>
-            </xs:attribute>
-            <xs:attribute name="post_delay" type="bio:SynapticDelayValue"  use="optional" default ="0">
-                <xs:annotation>
-                    <xs:documentation>Delay due to postsynaptic mechanism</xs:documentation>
-                </xs:annotation>
-            </xs:attribute>
-            <xs:attribute name="prop_delay" type="bio:SynapticDelayValue"  use="optional" default ="0">
-                <xs:annotation>
-                    <xs:documentation>Delay due to simulated AP propagation along an axon</xs:documentation>
-                </xs:annotation>
-            </xs:attribute>
-            <xs:attribute name="weight" type="meta:NonNegativeDouble" use="optional"  default ="1">
-                <xs:annotation>
-                    <xs:documentation>Multiplicative weighting factor for the synapse</xs:documentation>
-                </xs:annotation>
-            </xs:attribute>
-            <xs:attribute name="threshold" use="optional"  type="bio:VoltageValue"  default ="0">
-                <xs:annotation>
-                    <xs:documentation>Presynaptic membrane potential level above which the synapse fires</xs:documentation>
-                </xs:annotation>
-            </xs:attribute>
-        </xs:complexType>
-
-
-
-        <xs:complexType name="ConnectivityPattern">
-            <xs:annotation>
-                <xs:documentation>Information on the number of target cells connected to source cells, etc.</xs:documentation>
-            </xs:annotation>
-
-            <xs:choice>
-                <!-- Lots more scenarios could be described here... -->
-                <xs:element name="all_to_all">
-                    <xs:annotation>
-                        <xs:documentation>Connect every pre cell to every post cell</xs:documentation>
-                    </xs:annotation>
-                    <xs:complexType/>
-                </xs:element>
-                <xs:element name="fixed_probability">
-                    <xs:annotation>
-                        <xs:documentation>For each pre - post pair, there is a fixed probability of connection</xs:documentation>
-                    </xs:annotation>
-                    <xs:complexType>
-                        <xs:attribute name="probability" type="meta:ZeroToOne"/>
-                    </xs:complexType>
-                </xs:element>
-                <xs:element name="per_cell_connection" type="PerCellConnection">
-                    <xs:annotation>
-                        <xs:documentation>Connection built iteratively from each pre (or post) cell based on a number of parameters</xs:documentation>
-                    </xs:annotation>
-                </xs:element>
-
-            </xs:choice>
-
-        </xs:complexType>
-        
-
-        <xs:complexType name="PerCellConnection">
-            <xs:annotation>
-                <xs:documentation>Connection built iteratively from each pre (or post) cell based on a number of parameters</xs:documentation>
-            </xs:annotation>
-
-                <xs:attribute name="direction" default="PreToPost">
-                    <xs:annotation>
-                        <xs:documentation>Whether the settings below (e.g. number per source cell) refer to PreToPost or PostToPre connections.
-                        Note more info could be known about numbers of connections on post synaptic cells, so this possibility should be allowed.</xs:documentation>
-                    </xs:annotation>
-
-                    <xs:simpleType>
-                        <xs:restriction base="xs:string">
-                            <xs:enumeration value="PreToPost"/>
-                            <xs:enumeration value="PostToPre"/>
-                        </xs:restriction>
-                    </xs:simpleType>
-                </xs:attribute>
-                <xs:attribute name="num_per_source" type="meta:PositiveDouble" use="required" />
-                <xs:attribute name="max_per_target" type="xs:positiveInteger"  use="optional"/>
-                <!-- More settings can be put here, e.g. distance dependence of connections-->
-
-        </xs:complexType>
-
-
-
-        <xs:complexType name="Connections">
-            <xs:annotation>
-                <xs:documentation>The list of cell connections</xs:documentation>
-            </xs:annotation>
-
-            <xs:sequence>
-                <xs:group ref="meta:metadata"/>
-                <xs:element name="connection" type="Connection" maxOccurs="unbounded"/>
-            </xs:sequence>
-            
-            
-            <xs:attribute name="size" type="xs:nonNegativeInteger" use="optional">
-                <xs:annotation>
-                    <xs:documentation>The number of instances of connections. 
-                    This is redundant information, but can be useful when the file is being parsed to allocate memory for an array of cells. 
-                    NOTE: likely to be required from v2.0</xs:documentation>
-                </xs:annotation>
-            </xs:attribute>
-
-        </xs:complexType>
-
-        <xs:complexType name="CellInstance">
-            <xs:annotation>
-                <xs:documentation>An instance of a cell at a the specified location</xs:documentation>
-            </xs:annotation>
-
-            <xs:sequence>
-                <xs:group ref="meta:metadata"/>
-                <xs:element name="location" type="meta:Point3D"/>
-            </xs:sequence>
-
-            <xs:attribute name="id" type="xs:nonNegativeInteger" use="required">
-                <xs:annotation>
-                    <xs:documentation>A unique non negative integer id for the cell instance</xs:documentation>
-                </xs:annotation>
-            </xs:attribute>
-            
-            <xs:attribute name="node_id" type="xs:nonNegativeInteger" use="optional">
-                <xs:annotation>
-                    <xs:documentation>An optional specification of the node id on which this cell should run. This can be used
-                    to allow exchange of neuronal networks partitioned for execution in
-                    distributed computing environments. A parsing appliction can ignore this inforation and create its own partition.</xs:documentation>
-                </xs:annotation>
-            </xs:attribute>
-
-        </xs:complexType>
-
-
-        <xs:complexType name="Connection">
-            <xs:annotation>
-                <xs:documentation>A single synaptic connection</xs:documentation>
-            </xs:annotation>
-
-            <xs:sequence>
-                <xs:group ref="meta:metadata"/>
-                
-                <xs:element name="pre" type="SynapticLocation" minOccurs="0">
-                    <xs:annotation>
-                        <xs:documentation>NOTE: Attributes pre_cell_id etc. for WILL BE PREFERRED FORMAT IN v2.0</xs:documentation>
-                    </xs:annotation>
-                 </xs:element>
-                <xs:element name="post" type="SynapticLocation" minOccurs="0">
-                    <xs:annotation>
-                        <xs:documentation>NOTE: Attributes post_cell_id etc. for WILL BE PREFERRED FORMAT IN v2.0</xs:documentation>
-                    </xs:annotation>
-                 </xs:element>
-                <xs:element name="properties" type="LocalSynapticProperties" minOccurs="0" maxOccurs="unbounded"/>
-
-            </xs:sequence>
-
-
-                <xs:attribute name="id" type="xs:integer" use="required">
-                    <xs:annotation>
-                        <xs:documentation>The unique ID of the single synaptic connection.</xs:documentation>
-                    </xs:annotation>
-                </xs:attribute>
-                
-                <xs:attribute name="pre_cell_id" type="xs:integer" use="optional">
-                    <xs:annotation>
-                        <xs:documentation>The ID of the presynaptic cell. Must be listed in populations, so that too must list instances.
-                        Optional now, but attributes pre_cell_id, etc. WILL BE PREFERRED FORMAT IN v2.0</xs:documentation>
-                    </xs:annotation>
-                </xs:attribute>
-                <xs:attribute name="pre_segment_id" type="xs:integer" use="optional"  default="0">
-                    <xs:annotation>
-                        <xs:documentation>The segment on the presynaptic cell where the synapse is located.
-                        Attributes pre_cell_id, etc. WILL BE PREFERRED FORMAT IN v2.0</xs:documentation>
-                    </xs:annotation>
-                </xs:attribute>
-                <xs:attribute name="pre_fraction_along" type="meta:ZeroToOne" use="optional" default="0.5">
-                    <xs:annotation>
-                        <xs:documentation>The fraction along the length of the specified segment on the presynaptic cell where the synapse is located.
-                        Attributes pre_cell_id, etc. WILL BE PREFERRED FORMAT IN v2.0</xs:documentation>
-                    </xs:annotation>
-                </xs:attribute>
-                
-                <xs:attribute name="post_cell_id" type="xs:integer" use="optional">
-                    <xs:annotation>
-                        <xs:documentation>The ID of the postsynaptic cell. Must be listed in populations, so that too must list instances.
-                        Optional now, but attributes pre_cell_id, etc. WILL BE PREFERRED FORMAT IN v2.0</xs:documentation>
-                    </xs:annotation>
-                </xs:attribute>
-                <xs:attribute name="post_segment_id" type="xs:integer" use="optional"  default="0">
-                    <xs:annotation>
-                        <xs:documentation>The segment on the postsynaptic cell where the synapse is located.
-                        Attributes pre_cell_id, etc. WILL BE PREFERRED FORMAT IN v2.0</xs:documentation>
-                    </xs:annotation>
-                </xs:attribute>
-                <xs:attribute name="post_fraction_along" type="meta:ZeroToOne" use="optional" default="0.5">
-                    <xs:annotation>
-                        <xs:documentation>The fraction along the length of the specified segment on the postsynaptic cell where the synapse is located.
-                        Attributes pre_cell_id, etc. WILL BE PREFERRED FORMAT IN v2.0</xs:documentation>
-                    </xs:annotation>
-                </xs:attribute>
-
-        </xs:complexType>
-
-
-        <xs:complexType name="SynapticLocation">
-
-            <xs:attribute name="cell_id" type="xs:integer" use="required">
-                <xs:annotation>
-                    <xs:documentation>The ID of the cell. Must be listed in populations, so that too must list instances</xs:documentation>
-                </xs:annotation>
-            </xs:attribute>
-            <xs:attribute name="segment_id" type="xs:integer" use="optional"  default="0">
-                <xs:annotation>
-                    <xs:documentation>The segment where the synapse is located.</xs:documentation>
-                </xs:annotation>
-            </xs:attribute>
-            <xs:attribute name="fraction_along" type="meta:ZeroToOne" use="optional" default="0.5">
-                <xs:annotation>
-                    <xs:documentation>The fraction along the length of the specified segment where the synapse is located.</xs:documentation>
-                </xs:annotation>
-            </xs:attribute>
-        </xs:complexType>
-        
-        
-        
-
-
-
-
-        <xs:complexType name="PopulationLocation">
-            <xs:annotation>
-                <xs:documentation>Description of the 3D positioning of cells in the population, in place of giving explicit locations for each cell</xs:documentation>
-            </xs:annotation>
-
-            <xs:sequence>
-                <xs:group ref="meta:metadata"/>
-                <xs:choice>
-                    <xs:element name="random_arrangement" type="RandomArrangement"/>
-                    <xs:element name="grid_arrangement" type="GridArrangement"/>
-                    <!-- More should be included... -->
-                </xs:choice>
-            </xs:sequence>
-
-
-            <xs:attribute name="reference" type="xs:string"/>
-
-        </xs:complexType>
-
-
-        <xs:complexType name="RandomArrangement">
-            <xs:annotation>
-                <xs:documentation>A random arrangement of cells in a 3D location. Note other 3D regions besides spheres and rectangles can be added if required.</xs:documentation>
-            </xs:annotation>
-            <xs:sequence>
-                <xs:group ref="meta:metadata"/>
-                <xs:element name="population_size" type="xs:nonNegativeInteger">
-                    <xs:annotation>
-                        <xs:documentation>Number of cells to place randomly in the specified 3D location</xs:documentation>
-                    </xs:annotation>
-                </xs:element>
-                <xs:choice>
-                    <xs:element name="spherical_location" type="meta:Sphere"/>
-                    <xs:element name="rectangular_location" type="meta:RectangularBox"/>
-                </xs:choice>
-            </xs:sequence>
-        </xs:complexType>
-
-
-        <xs:complexType name="GridArrangement">
-            <xs:annotation>
-                <xs:documentation>A regular placement of the cells in a number of dimensions</xs:documentation>
-            </xs:annotation>
-            <xs:sequence>
-                <xs:group ref="meta:metadata"/>
-                
-                <xs:choice>
-                
-                    <xs:group ref="SpatialLayout"/>
-
-                    <xs:element name="non_spatial_grid" type="meta:NonSpatialGrid">
-                        <xs:annotation>
-                            <xs:documentation>Specifying this means the precise spatial location of the cells is irrelvant</xs:documentation>
-                        </xs:annotation>
-                    </xs:element>
-
-                </xs:choice>
-                
-            </xs:sequence>
-            
-        </xs:complexType>
-
-
-        
-        <xs:group name="SpatialLayout">
-            <xs:annotation>
-                <xs:documentation>Layout of the cells according to x,y,z spatial coordinates</xs:documentation>
-            </xs:annotation>
-            
-            <xs:sequence>
-                <xs:element name="rectangular_location" type="meta:RectangularBox">
-                    <xs:annotation>
-                        <xs:documentation>3D box in which the cells are regularly packed. Note if one or two of dimensions of the box is zero it can be a 2D or 1D grid (respectively).</xs:documentation>
-                    </xs:annotation>
-                </xs:element>
-
-
-                <xs:element name="spacing" >
-                    <xs:annotation>
-                        <xs:documentation>Separation of the cells in each dimension</xs:documentation>
-                    </xs:annotation>
-                    <xs:complexType>
-                        <xs:attribute name="x" type="xs:double"/>
-                        <xs:attribute name="y" type="xs:double"/>
-                        <xs:attribute name="z" type="xs:double"/>
-                    </xs:complexType>
-                </xs:element>
-            </xs:sequence>
-        </xs:group>
-
-        
-        <xs:complexType name="Level3Connectivity">
-            <xs:annotation>
-                    <xs:documentation>Biophysics of Level3 cell, including specification for allowable synaptic locations.
-                Note: from v1.7.1 the preferred way to specify a potential synaptic location is with a potential_syn_loc element under connectivity under cell, as
-                opposed to the potentialSynapticLocation under biophysics under cell. The former will be the only option from v2.0</xs:documentation>
-            </xs:annotation>
-            <xs:sequence>
-                <xs:element name="potential_syn_loc" type="PotentialSynLoc" minOccurs="0" maxOccurs="unbounded"/>
-            </xs:sequence>
-        </xs:complexType>
-
-        
-
-        <xs:complexType name="PotentialSynLoc">
-            <xs:annotation>
-                <xs:documentation>Subset of sections on cell where synaptic connection of a particular type is allowed.
-                Note: from v1.7.1 the preferred way to specify a potential synaptic location is with a potential_syn_loc element under connectivity under cell, as
-            opposed to the potentialSynapticLocation under biophysics under cell. The former will be the only option from v2.0</xs:documentation>
-            </xs:annotation>
-
-            <xs:sequence>
-                <xs:group ref="meta:metadata"/>
-                <xs:sequence>
-                    <xs:element name="group" type="xs:string" minOccurs="1" maxOccurs="unbounded">
-                        <xs:annotation>
-                            <xs:documentation>List of groups of sections allowing the synapse</xs:documentation>
-                        </xs:annotation>
-                    </xs:element>
-                </xs:sequence>
-            </xs:sequence>
-            
-            <xs:attribute name="synapse_type" type="xs:string" use="required">
-                <xs:annotation>
-                    <xs:documentation>Which of the synaptic mechanisms can be present</xs:documentation>
-                </xs:annotation>
-            </xs:attribute> 
-            <xs:attribute name="synapse_direction" type="SynapseDirection" use="optional" default="preAndOrPost">
-                <xs:annotation>
-                    <xs:documentation>Whether this synapse location allows a presynaptic connection, a postsynaptic
-                        connection or either</xs:documentation>
-                </xs:annotation>
-            </xs:attribute>
-        </xs:complexType>
-        
-
-        <xs:complexType name="PotentialSynapticLocation">
-            <xs:annotation>
-                <xs:documentation>Subset of sections on cell where synaptic connection of a particular type is allowed. 
-                Note: from v1.7.1 the preferred way to specify a potential synaptic location is with a potential_syn_loc element under connectivity under cell, as
-            opposed to the potentialSynapticLocation under biophysics under cell. The former will be the only option from v2.0</xs:documentation>
-            </xs:annotation>
-
-            <xs:sequence>
-                <xs:group ref="meta:metadata"/>
-                <xs:sequence>
-                    <xs:element name="synapse_type" type="xs:string">
-                        <xs:annotation>
-                            <xs:documentation>Which of the synaptic mechanisms can be present</xs:documentation>
-                        </xs:annotation>
-                    </xs:element>
-                    <xs:element name="synapse_direction" type="SynapseDirection" minOccurs="0">
-                        <xs:annotation>
-                            <xs:documentation>Whether this synapse location allows a presynaptic connection, a postsynaptic
-                                connection or either</xs:documentation>
-                        </xs:annotation>
-                    </xs:element>
-                    <xs:element name="group" type="xs:string" maxOccurs="unbounded">
-                        <xs:annotation>
-                            <xs:documentation>List of groups of sections allowing the synapse</xs:documentation>
-                        </xs:annotation>
-                    </xs:element>
-                </xs:sequence>
-            </xs:sequence>
-        </xs:complexType>
-
-
-
-        <xs:simpleType name="SynapseDirection">
-            <xs:annotation>
-                <xs:documentation>Indicated whether a potential synapse location allows a presynaptic connection
-                of the specified type, a postsynaptic connection or either. </xs:documentation>
-            </xs:annotation>
-            <xs:restriction base="xs:string">
-                <xs:enumeration value="pre"/>
-                <xs:enumeration value="post"/>
-                <xs:enumeration value="preAndOrPost"/>
-            </xs:restriction>
-        </xs:simpleType>
-        
-        
-
-        <xs:simpleType name="CellIdInNetwork">
-            <xs:annotation>
-                <xs:documentation>Id of individual cell in a network</xs:documentation>
-            </xs:annotation>
-            <xs:restriction base="xs:nonNegativeInteger">
-            </xs:restriction>
-        </xs:simpleType>
-
-
-        <xs:group name="BiophysicsNetworkElements">
-            <xs:annotation>
-                <xs:documentation>The elements in biophysics needed to specify a network connection. 
-                Note: from v1.7.1 the preferred way to specify a potential synaptic location is with a potential_syn_loc element under connectivity under cell, as
-            opposed to the potentialSynapticLocation under biophysics under cell. The former will be the only option from v2.0</xs:documentation>
-            </xs:annotation>
-
-            <xs:sequence>
-                <xs:element name="potentialSynapticLocation" type="PotentialSynapticLocation" minOccurs="0" maxOccurs="unbounded" />
-            </xs:sequence>
-        </xs:group>
-
-
-</xs:schema>
diff --git a/python/libmumbl/svn_add.sh b/python/libmumbl/svn_add.sh
deleted file mode 100755
index 74ffbf40bed3c8c08f3e4eb9bd0a44d884e643d3..0000000000000000000000000000000000000000
--- a/python/libmumbl/svn_add.sh
+++ /dev/null
@@ -1,8 +0,0 @@
-#!/bin/bash
-to="../../moose_svn1.7/moose/branches/buildQ/python/moose/multiscale/"
-find . -type f -regex ".*\.\(sh\|py\|Make*\|xml\|xsd\|txt\|log\)" -print0 |\
-     xargs -0 -I file cp --parents file $to
-#cd $to && \
-#    findAsciiTextFiles.sh -print0 | xargs -I file svn add file && svn ci
-cd $to && \
-    findAsciiTextFiles.sh -print0 | xargs -I file svn add file && svn ci
diff --git a/python/libmumbl/test/adaptor.py b/python/libmumbl/test/adaptor.py
deleted file mode 100644
index 51a55eb542754724086677f83aef2e6752dc0572..0000000000000000000000000000000000000000
--- a/python/libmumbl/test/adaptor.py
+++ /dev/null
@@ -1,128 +0,0 @@
-
-
-"""adaptor.py: 
-
-    This file is a minimal example on how to setup two compartment and pass
-    message from one to other.
-
-Last modified: Mon Jan 06, 2014  04:11PM
-
-"""
-    
-__author__           = "Dilawar Singh"
-__copyright__        = "Copyright 2013, NCBS Bangalore"
-__credits__          = ["NCBS Bangalore", "Bhalla Lab"]
-__license__          = "GPL"
-__version__          = "1.0.0"
-__maintainer__       = "Dilawar Singh"
-__email__            = "dilawars@ncbs.res.in"
-__status__           = "Development"
-
-import moose
-import matplotlib.pyplot as plt
-
-def makeModel():
-        # create container for model
-        model = moose.Neutral( 'model' )
-        compartment = moose.CubeMesh( '/model/compartment' )
-        compartment.volume = 1e-15
-        # the mesh is created automatically by the compartment
-        mesh = moose.element( '/model/compartment/mesh' ) 
-
-        # create molecules and reactions
-        a = moose.Pool( '/model/compartment/a' )
-        b = moose.Pool( '/model/compartment/b' )
-        c = moose.Pool( '/model/compartment/c' )
-        enz1 = moose.Enz( '/model/compartment/b/enz1' )
-        enz2 = moose.Enz( '/model/compartment/c/enz2' )
-        cplx1 = moose.Pool( '/model/compartment/b/enz1/cplx' )
-        cplx2 = moose.Pool( '/model/compartment/c/enz2/cplx' )
-        reac = moose.Reac( '/model/compartment/reac' )
-
-        # Connect them up throught adaptors.
-        moose.Neutral('/model/adaptor')
-        adapt1 = moose.Adaptor('/model/adaptor/a1')
-        adapt1.setField('inputOffset', 0)
-        adapt1.setField('scale', 1)
-        moose.connect(adapt1, 'requestField', a, 'getConc')
-        moose.connect(adapt1, 'output', b, 'setConc')
-
-
-        # connect them up for reactions
-        moose.connect( enz1, 'sub', a, 'reac' )
-        moose.connect( enz1, 'prd', b, 'reac' )
-        moose.connect( enz1, 'enz', b, 'reac' )
-        moose.connect( enz1, 'cplx', cplx1, 'reac' )
-
-        moose.connect( enz2, 'sub', b, 'reac' )
-        moose.connect( enz2, 'prd', a, 'reac' )
-        moose.connect( enz2, 'enz', c, 'reac' )
-        moose.connect( enz2, 'cplx', cplx2, 'reac' )
-
-        moose.connect( reac, 'sub', a, 'reac' )
-        moose.connect( reac, 'prd', b, 'reac' )
-
-        # connect them up to the compartment for volumes
-        for x in ( a, b, c, cplx1, cplx2 ):
-            moose.connect( x, 'mesh', mesh, 'mesh' )
-
-        # Assign parameters
-        a.concInit = 1
-        b.concInit = 0
-        c.concInit = 0.01
-        enz1.kcat = 0.4
-        enz1.Km = 4
-        enz2.kcat = 0.6
-        enz2.Km = 0.01
-        reac.Kf = 0.001
-        reac.Kb = 0.01
-
-        # Create the output tables
-        graphs = moose.Neutral( '/model/graphs' )
-        outputA = moose.Table ( '/model/graphs/concA' )
-        outputB = moose.Table ( '/model/graphs/concB' )
-
-        # connect up the tables
-        moose.connect( outputA, 'requestData', a, 'get_conc' );
-        moose.connect( outputB, 'requestData', b, 'get_conc' );
-
-        # Schedule the whole lot
-        moose.setClock( 4, 0.001 ) # for the computational objects
-        moose.setClock( 8, 1.0 ) # for the plots
-        moose.setClock( 9, 10 ) # for the plots
-        # The wildcard uses # for single level, and ## for recursive.
-        moose.useClock( 4, '/model/compartment/##', 'process' )
-        moose.useClock( 8, '/model/graphs/#', 'process' )
-        moose.useClock( 8, '/model/adaptor/#', 'process' )
-
-
-def main():
-        makeModel()
-
-        moose.reinit()
-        moose.start( 100.0 ) # Run the model for 100 seconds.
-
-        a = moose.element( '/model/compartment/a' )
-        b = moose.element( '/model/compartment/b' )
-
-        # move most molecules over to b
-        b.conc = b.conc + a.conc * 0.9
-        a.conc = a.conc * 0.1
-        moose.start( 100.0 ) # Run the model for 100 seconds.
-
-        # move most molecules back to a
-        a.conc = a.conc + b.conc * 0.99
-        b.conc = b.conc * 0.01
-        moose.start( 100.0 ) # Run the model for 100 seconds.
-
-        # Iterate through all plots, dump their contents to data.plot.
-        for x in moose.wildcardFind( '/model/graphs/conc#' ):
-            #moose.element(x[0]).xplot('scriptKineticModel.plot', x[0].name)
-            filename = (x.path+'.eps').replace('/', '_')
-            plt.plot(x[0].vec)
-            plt.savefig(filename)
-        quit()
-
-# Run the 'main' if this script is executed standalone.
-if __name__ == '__main__':
-    main()
diff --git a/python/libmumbl/test/pool_and_adaptor.py b/python/libmumbl/test/pool_and_adaptor.py
deleted file mode 100644
index 5db6bc2b1d849b815a3df78a447ceb3b665d435e..0000000000000000000000000000000000000000
--- a/python/libmumbl/test/pool_and_adaptor.py
+++ /dev/null
@@ -1,45 +0,0 @@
-# This file is part of MOOSE simulator: http://moose.ncbs.res.in.
-
-# MOOSE is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-
-# MOOSE is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-# You should have received a copy of the GNU General Public License
-# along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
-
-
-"""pool_and_adaptor.py: 
-    
-    A simple script which connects Pool and an Adaptor.
-
-Last modified: Sat Jan 18, 2014  05:01PM
-
-"""
-    
-__author__           = "Dilawar Singh"
-__copyright__        = "Copyright 2013, NCBS Bangalore"
-__credits__          = ["NCBS Bangalore", "Bhalla Lab"]
-__license__          = "GNU GPL"
-__version__          = "1.0.0"
-__maintainer__       = "Dilawar Singh"
-__email__            = "dilawars@ncbs.res.in"
-__status__           = "Development"
-
-
-import os
-import sys
-sys.path.append('../../../python')
-import moose
-
-def main():
-    p = moose.Pool('/ca')
-    a = moose.Adaptor('/a')
-    moose.connect(a, 'requestField', p, 'getConc')
-
-if __name__ == '__main__':
-    main()
diff --git a/python/libmumbl/test/test1.py b/python/libmumbl/test/test1.py
deleted file mode 100644
index abc1bd5696fcf10483a28152c04b59a85f8ad08d..0000000000000000000000000000000000000000
--- a/python/libmumbl/test/test1.py
+++ /dev/null
@@ -1,7 +0,0 @@
-import moose
-from IPython import embed
-# Try to connect pool to species
-pool = moose.Pool('/pool')
-species = moose.Species('/species')
-embed()
-species.pool = pool
diff --git a/python/libmumbl/util.py b/python/libmumbl/util.py
deleted file mode 100644
index 9b37ec96d617cf08aa81f57027908222caffde01..0000000000000000000000000000000000000000
--- a/python/libmumbl/util.py
+++ /dev/null
@@ -1,25 +0,0 @@
-"""
-Copyright (C) 2014 Dilawar Singh
-
-This program is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program; if not, see <http://www.gnu.org/licenses/>.
-"""
-
-import os
-import sys
-import helper
-
-def parseMumbl(mublFilePath):
-    """Parse MUMBL are return the ElementTree """
-    
-
diff --git a/python/libmumbl/utility/__init__.py b/python/libmumbl/utility/__init__.py
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/python/libmumbl/utility/debug.py b/python/libmumbl/utility/debug.py
deleted file mode 100644
index f99de0219ba393c4cd74dc2fae5f363b3e7be1c5..0000000000000000000000000000000000000000
--- a/python/libmumbl/utility/debug.py
+++ /dev/null
@@ -1,104 +0,0 @@
-
-
-"""print_utils.py: A library with some print functions. Very useful during
-development.
-
-Last modified: Sat Jan 18, 2014  05:01PM
-
-"""
-    
-__author__           = "Dilawar Singh"
-__copyright__        = "Copyright 2013, NCBS Bangalore"
-__credits__          = ["NCBS Bangalore", "Bhalla Lab"]
-__license__          = "GPL"
-__version__          = "1.0.0"
-__maintainer__       = "Dilawar Singh"
-__email__            = "dilawars@ncbs.res.in"
-__status__           = "Development"
-
-import inspect
-import sys
-
-HEADER = '\033[95m'
-OKBLUE = '\033[94m'
-OKGREEN = '\033[92m'
-WARNING = '\033[90m'
-ERR = '\033[31m'
-ENDC = '\033[0m'
-RED = ERR
-WARN = WARNING
-INFO = OKGREEN
-TODO = OKBLUE
-DEBUG = HEADER
-ERROR = ERR
-
-prefixDict = dict(
-    ERR = ERR
-    , ERROR = ERR
-    , WARN = WARN
-    , FATAL = ERR
-    , INFO = INFO
-    , TODO = TODO
-    , NOTE = HEADER
-    , DEBUG = DEBUG
-    , STEP = INFO
-    , FAIL = ERR
-    , FAILED = ERR
-    )
-
-def colored(msg, label="INFO") :
-    """
-    Return a colored string. Formatting is optional.
-
-    At each ` we toggle the color.
-    
-    """
-    global prefixDict
-    if label in prefixDict :
-        color = prefixDict[label]
-    else :
-        color = ""
-    txt = ''
-    newMsg = msg.split('`')
-    i = 0
-    for m in newMsg:
-        if i % 2 == 0:
-            txt += color + m
-        else:
-            txt += ENDC + m
-        i += 1
-    return "{0} {1}".format(txt, ENDC)
-
-def cl(msg, label="INFO"):
-    return colored(msg, label)
-
-def dump(label, msg, frame=None, exception=None):
-    ''' If msg is a list then first msg in list is the main message. Rest are
-    sub message which should be printed prefixed by \n\t.
-    '''
-
-    prefix = '[{0}] '.format(label)
-
-    ''' Enable it if you want indented messages 
-    stackLength = len(inspect.stack()) - 1
-    if stackLength == 1:
-        prefix = '\n[{}] '.format(label)
-    else:
-        prefix = ' '.join(['' for x in range(stackLength)])
-    '''
-
-    if type(msg) == list:
-        if len(msg) > 1:
-            msg = [msg[0]] + ["`|- {0}`".format(x) for x in msg[1:]] 
-        msg ="\n\t".join(msg)
-
-
-    if not frame :
-        print(prefix+"{0}".format(colored(msg,label)))
-    else :
-        filename = frame.f_code.co_filename
-        filename = "/".join(filename.split("/")[-2:])
-        print(prefix+"@{0}:{1} {2}".format(filename, frame.f_lineno, colored(msg, label)))
-    if exception:
-        print(" [Expcetion] {0}".format(exception))
-
diff --git a/python/libmumbl/utility/helper.py b/python/libmumbl/utility/helper.py
deleted file mode 100644
index 59de2f8d57f83bec041ca2debc2cebbe4f4a3aff..0000000000000000000000000000000000000000
--- a/python/libmumbl/utility/helper.py
+++ /dev/null
@@ -1,51 +0,0 @@
-# This file is part of libmumbl simulator: http://moose.ncbs.res.in.
-
-# libmumbl is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-
-# libmumbl is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-# You should have received a copy of the GNU General Public License
-# along with libmumbl.  If not, see <http://www.gnu.org/licenses/>.
-
-
-"""helper.py: 
-
-Last modified: Sat Jan 18, 2014  05:01PM
-
-"""
-    
-__author__           = "Dilawar Singh"
-__copyright__        = "Copyright 2013, Dilawar Singh"
-__credits__          = ["NCBS Bangalore"]
-__license__          = "GNU GPL"
-__version__          = "1.0.0"
-__maintainer__       = "Dilawar Singh"
-__email__            = "dilawars@ncbs.res.in"
-__status__           = "Development"
-
-import debug 
-
-def ifPathsAreValid(paths) :
-    ''' Verify if path exists and are readable. '''
-    if paths :
-        for p in paths :
-            if not paths[p] : continue
-            for path in paths[p] :
-                if not path : continue
-                if os.path.isfile(path) : pass
-                else :
-                    debug.printDebug("ERROR"
-                        , "Filepath {0} does not exists".format(path))
-                    return False
-            # check if file is readable
-            if not os.access(path, os.R_OK) :
-              debug.dump("ERROR", "File {0} is not readable".format(path))
-              return False
-    return True
-
-
diff --git a/python/libmumbl/utility/nml.py b/python/libmumbl/utility/nml.py
deleted file mode 100644
index d4c66ebf4bd119cc475d961fd9518632ac249f42..0000000000000000000000000000000000000000
--- a/python/libmumbl/utility/nml.py
+++ /dev/null
@@ -1,38 +0,0 @@
-# This file is part of MOOSE simulator: http://moose.ncbs.res.in.
-
-# MOOSE is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-
-# MOOSE is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-# You should have received a copy of the GNU General Public License
-# along with MOOSE.  If not, see <http://www.gnu.org/licenses/>.
-
-
-"""nml_utils.py: 
-
-    Utility function to parse and load neuroml files into moose.
-
-Last modified: Sat Jan 18, 2014  05:01PM
-
-"""
-    
-__author__           = "Dilawar Singh"
-__copyright__        = "Copyright 2013, NCBS Bangalore"
-__credits__          = ["NCBS Bangalore", "Bhalla Lab"]
-__license__          = "GNU GPL"
-__version__          = "1.0.0"
-__maintainer__       = "Dilawar Singh"
-__email__            = "dilawars@ncbs.res.in"
-__status__           = "Development"
-
-import parser.NeuroML as NeuroML
-
-def loadNeuroML(nmlFile):
-    """ Wrapper around the library function which loads neuroml into MOOSE"""
-    nmlParser = NeuroML.NeuroML()
-    return nmlParser.loadNML(nmlFile)
diff --git a/python/libmumbl/utility/xml_parser.py b/python/libmumbl/utility/xml_parser.py
deleted file mode 100644
index bd67d45d826b13f7622a86a99b641ec2e3155145..0000000000000000000000000000000000000000
--- a/python/libmumbl/utility/xml_parser.py
+++ /dev/null
@@ -1,60 +0,0 @@
-# Basic imports
-import os
-import sys
-import inspect
-import debug
-
-from lxml import etree
-
-import collections
-def parseAndValidateWithSchema(modelName, modelPath) :
-
-    prefixPath = ''
-    if modelName == 'xml' :
-        schemaPath = os.path.join(prefixPath, 'schema/moose/moose.xsd')
-        if not os.path.isfile(schemaPath) :
-            debug.dump("WARN", "Schema {0} does not exists..".format(schemaPath))
-
-    try :
-        schemaH = open(schemaPath, "r")
-        schemaText = schemaH.read()
-        schemaH.close()
-    except Exception as e :
-        debug.dump("WARN", "Error reading schema for validation."+
-          " Falling back to validation-disabled parser."
-          + " Failed with error {0}".format(e))
-        return parseWithoutValidation(modelName, modelPath)
-        # Now we have the schema text
-    schema = etree.XMLSchema(etree.XML(schemaText))
-    xmlParser = etree.XMLParser(schema=schema, remove_comments=True)
-    with open(modelPath, "r") as xmlTextFile :
-        return etree.parse(xmlTextFile, xmlParser)
-
-def parseWithoutValidation(modelName, modelPath) :
-    xmlParser = etree.XMLParser(remove_comments=True)
-    try :
-        xmlRootElem = etree.parse(modelPath, xmlParser)
-    except Exception as e :
-        debug.dump("ERROR", "Parsing of {0} failed.".format(modelPath))
-        debug.dump("DEBUG", "Error: {0}".format(e))
-        raise RuntimeError, "Failed to parse XML"
-    return xmlRootElem
-
-def parseXMLs(commandLineArgs, validate=False) :
-    xmlRootElemDict = collections.defaultdict(list)
-    models = vars(commandLineArgs)
-    for model in models :
-        if models[model] :
-            for modelPath in models[model] :
-                debug.dump("INFO", "Parsing {0}".format(models[model]))
-                if validate :
-                    # parse model and valid it with schama
-                    modelXMLRootElem = parseAndValidateWithSchema(model, modelPath)
-                else :
-                    # Simple parse the model without validating it with schema.
-                    modelXMLRootElem = parseWithoutValidation(model, modelPath)
-                if modelXMLRootElem :
-                    xmlRootElemDict[model].append((modelXMLRootElem, modelPath))
-    assert len(xmlRootElemDict) > 0
-    return xmlRootElemDict
-
diff --git a/python/libmumbl/xmml/.gitignore b/python/libmumbl/xmml/.gitignore
deleted file mode 100644
index 306b2a9486f1028f78b3150abb6e6fe4a6a71025..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/.gitignore
+++ /dev/null
@@ -1,7 +0,0 @@
-release/*
-!.gitignore
-/nbproject
-/build
-manifest.mf
-.project
-/build.xml
diff --git a/python/libmumbl/xmml/CHANGELOG.txt b/python/libmumbl/xmml/CHANGELOG.txt
deleted file mode 100644
index e0789e8b6c91c239fb12e2e8f6b6e773126b0b5a..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/CHANGELOG.txt
+++ /dev/null
@@ -1,55 +0,0 @@
-xMML version 0.4
-==================
-Date: 2012-04-20.
-
-Changes since version 0.3.3
-* Added a terminal (source and sink)
-* Added an extends attribute to datatype
-* Added a fan-in-out mapper type
-* Added a format to specify parameters in, by name of xmml_param.xsd
-* Added a path property to implementation and library
-* Removed DTD version, we've fully switched to XSD.
-
-Changes since version 0.3.2
-* Changed the main description to W3C XML Schema Description.
-* Added a schema for the MAD tool
-
-Changes since version 0.3.1
-* Changed the 'max' attribute in scale to 'total'
-
-Changes since version 0.3
-* Fixed accidental merge in xmml.dtd
-* Changed examples to the right version
-
-Changes since version 0.2
-* Replaced the junction element with the mapper element
-* Replaced the mapper element with the instance element
-* Replaced the converter element with the filter element, and added
-  dimension, factor and implementation information to it
-* Replaced the filter element with the apply element
-* Added the extra element to each computational element for any information
-  not captured by other tags.
-* Added a optional version to each computational element
-
-Changes since version 0.1.2
-* Added a junction element in definitions, describing a generic
-  fan-in or fan-out junction
-* Added a mapper element in topology, instantiating a junction
-* Added a multiplicity attribute to the instance element, allowing
-  a static number of instances to be created, which can be accessed
-  through mappers.
-* A converter may not have requirements anymore; a fan-in junction
-  mapper can be used instead.
-* Filter type has become mandatory
-* Added a possible characteristic scale
-* Added a release, validation and dtd2xsd conversion script
-  to the bin directory
-
-Changes since version 0.1.1
-* Fixed version numbers in examples
-
-Changes since version 0.1
-* Added an interactive attribute to submodel, instance and coupling
-* Added a stateful attribute to instance
-* Removed version from description
-* Added converter to filter type
diff --git a/python/libmumbl/xmml/README.md b/python/libmumbl/xmml/README.md
deleted file mode 100644
index 9936674c703be5cf247ac42049b812a431c70dfb..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/README.md
+++ /dev/null
@@ -1,18 +0,0 @@
-The xMML format, version 0.4
-==============================
-
-The xMML format is documented in xmml.xsd, and a brief introducion
-was presented at eScience 2011 [1]. An older documentation is
-available of xmml.dtd. Two examples implementing the specification
-are given: isr\_xmml.xml and canal.xml.
-
-With the scripts in the bin directory certain tasks are eased.
-* bin/validate: call to validate an xmml file, which must be in the
-  same directory as xmml.dtd. With two arguments, it performes
-  XInclude and saves the result in the second file.
-* bin/mkrelease: call with a version number to have a release of that
-  version put in the release directory
-* bin/dtd2xsd.pl: call to convert xmml.dtd to xmml.xsd
-* bin/xsd2dtd.xsl: XML Transformation to convert xmml.xsd to xmml.dtd
-
-[1] J. Borgdorff, J.-L. Falcone, E. Lorenz, B. Chopard, A.G. Hoekstra, "A principled approach to Distributed Multiscale Computing, from formalization to execution," In Proceedings of The Seventh IEEE International Conference on e-Science Workshops, Stockholm, Sweden, December 5-8, pp 97-104, 2011 [doi:10.1109/eScienceW.2011.9](http://dx.doi.org/10.1109/eScienceW.2011.9).
diff --git a/python/libmumbl/xmml/bin/dtd2xsd.pl b/python/libmumbl/xmml/bin/dtd2xsd.pl
deleted file mode 100755
index 79ce5a4cad2372ef20ee4337570d0b143f595f05..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/bin/dtd2xsd.pl
+++ /dev/null
@@ -1,836 +0,0 @@
-#!/usr/bin/perl
-#
-# by Dan Connolly http://www.w3.org/People/Connolly/ connolly@w3.org
-#    Bert Bos http://www.w3.org/People/Bos/ <bert@w3.org>
-#    Yuichi Koike
-#    Mary Holstege (holstege@mathling.com)
-# initial hack by DC Apr 2000, based on dtd2bnf by BB Mar 1998;
-# major revision to Apr 2000 make it actually usable by YK;
-# tweaks by DC; major update Jan 2001 by MH
-#
-# see Log since then at end.
-# $Id: dtd2xsd.pl,v 1.17 2001/01/19 05:59:12 connolly Exp $
-
-use strict;
-
-# Handling command line argument
-my $targetNS = "http://www.w3.org/namespace/";
-my $prefix = "t";
-my $alias = 0;
-my $file = "";
-my %SimpleTypes;
-my @AttrGroupPatterns;
-my @ModelGroupPatterns;
-my @SubstitutionGroupPatterns;
-my %SubstitutionGroup;
-
-my %Mixed;
-my %ModelGroup;
-my $mapping_file;
-my $pcdata_flag = 0;
-my $pcdata_simpletype = "string";
-my $debug = 0;
-
-while ($#ARGV >= 0) {
-	 my $para = shift(@ARGV);
-	 if ($para eq "-ns") {
-		  $targetNS = shift(@ARGV);
-	 } elsif ($para eq "-prefix") {
-		  $prefix = shift(@ARGV);
-	 } elsif ($para eq "-alias") {
-		  $alias = 1;
-	 } elsif ($para eq "-pcdata") {
-		  # Treat #PCDATA by itself as being string (or other simple type
-		  # if so designated in the mapping file)
-		  $pcdata_flag = 1;
-	 } elsif ($para eq "-mapfile") {
-		  $mapping_file = shift(@ARGV);
-	 } elsif ($para eq "-simpletype") {
-		  my($pat) = shift(@ARGV);
-		  my($b) = shift(@ARGV);
-		  $SimpleTypes{$pat} = $b;
-	 } elsif ($para eq "-attrgroup") {
-		  push(@AttrGroupPatterns, shift(@ARGV));
-	 } elsif ($para eq "-modelgroup") {
-		  push(@ModelGroupPatterns, shift(@ARGV));
-	 } elsif ($para eq "-substgroup") {
-		  push(@SubstitutionGroupPatterns, shift(@ARGV));
-	 } elsif ($para eq "-debug") {
-		  $debug = 1;
-	 } else {
-		  $file = $para;
-	 }
-}
-
-# Alias dictionary: defaults
-my %alias_dic;
-$alias_dic{"URI"} = "uriReference";
-$alias_dic{"LANG"} = "language";
-$alias_dic{"NUMBER"} = "nonNegativeInteger";
-$alias_dic{"Date"} = "date";
-$alias_dic{"Boolean"} = "boolean";
-
-if ( $mapping_file )
-{
-	 print STDERR "Open mapping $mapping_file ";
-	 if ( !open( MAPPINGS, "<$mapping_file" ) )
-	 {
-		  print STDERR "unsuccessful.\n";
-	 }
-	 else {
-		  print STDERR "successful.\n";
-		  while ( <MAPPINGS> ) {
-				chop;
-				if ( /^alias\s+([^ \t]+)\s*=\s*([^ \t]+)\s*/i ) {
-					 $alias_dic{$1} = $2;
-				}
-				elsif ( /^simpletype\s+([^ \t]+)\s*=\s*([^ \t]+)\s*/i ) {
-					 $SimpleTypes{$1} = $2;
-				}
-				elsif ( /^attrgroup\s+([^ \t]+)\s*/i ) {
-					 push( @AttrGroupPatterns, $1 );
-				}
-				elsif ( /^modelgroup\s+([^ \t]+)\s*/i ) {
-					 push( @ModelGroupPatterns, $1 );
-				}
-				elsif ( /^substgroup\s+([^ \t]+)\s*/i ) {
-					 push( @SubstitutionGroupPatterns, $1 );
-				}
-				elsif ( /^pcdata\s+([^ \t]+)\s*/i ) {
-					 ## BUGLET: doesn't pay attention to prefix; just a special alias
-					 $pcdata_simpletype = $1;
-				}
-		  }
-	 }
-
-	 foreach my $key (keys(%alias_dic)) 
-	 {
-		  print STDERR "Alias \%$key to $alias_dic{$key}\n"
-		  }
-}
-
-# Variable declaration
-my $linelen = 72;
-
-my $PROG = substr($0, rindex($0, "/") + 1);
-my $USAGE = "Usage: $PROG file\n";
-
-my $str = "(?:\"([^\"]*)\"|\'([^\']*)\')";
-my %pent;				# Parameter entities
-my %attributes;			# Attribute lists
-my @element;			# Elements in source order
-my %model;				# Content models
-
-# Main
-$/ = undef;
-
-# Open file, remove comment and include external entity
-my $buf = openFile($file);
-
-# Alias treatment
-my $alias_ident = "_alias_";
-if ($alias eq 1) {
-	 foreach my $key (keys(%alias_dic)) {
-		  my $aliaskey = sprintf("%s%s%s", $alias_ident, $key, $alias_ident);
-		  $buf =~ s/\%$key;/$aliaskey/gsie;
-	 }
-}
-
-
-# store all parameter entities
-while ($buf =~ s/<!ENTITY\s+%\s+(\S+)\s+$str\s*>//sie) {
-    my($n, $repltext) = ($1, $2.$3);
-    my ($pat);
-
-    next if $pent{$n}; # only the first declaration of an entity counts
-
-    foreach $pat (keys %SimpleTypes){
-		  if ($n =~ /^$pat$/){
-				$buf .= " <!_DATATYPE $n $SimpleTypes{$pat} $repltext> ";
-				$pent{$n} = "#DATATYPEREF $n";
-				undef $n;
-				last;
-		  }
-    }
-
-    foreach $pat (@AttrGroupPatterns){
-		  if ($n =~ /^$pat$/){
-				$buf .= " <!_ATTRGROUP $n $repltext> ";
-				$pent{$n} = "#ATTRGROUPREF $n";
-				undef $n;
-				last;
-		  }
-    }
-
-    foreach $pat (@ModelGroupPatterns){
-		  if ($n =~ /^$pat$/){
-				$buf .= " <!_MODELGROUP $n $repltext> ";
-				$pent{$n} = "#MODELGROUPREF $n";
-				undef $n;
-				last;
-		  }
-    }
-
-    foreach $pat (@SubstitutionGroupPatterns){
-		  if ($n =~ /^$pat$/){
-				$buf .= " <!_SUBSTGROUP $n $repltext> ";
-				$pent{$n} = "#SUBSTGROUPREF $n";
-				undef $n;
-				last;
-		  }
-
-    }
-
-    $pent{$n}=$repltext if $n;
-}
-
-# remove all general entities
-$buf =~ s/<!ENTITY\s+.*?>//gsie;
-
-# loop until parameter entities fully expanded
-my $i;
-do {
-	 # count # of substitutions
-	 $i = 0;
-	 # expand parameter entities
-	 $buf =~ s/%([a-zA-Z0-9_\.-]+);?/$i++,$pent{$1}/gse;
-} while ($i != 0);
-
-# treat conditional sections
-while($buf =~ s/<!\[\s*?INCLUDE\s*?\[(.*)\]\]>/\1/gsie) {};
-while($buf =~ s/<!\[\s*?IGNORE\s*?\[.*\]\]>//gsie) {};
-
-# store attribute lists
-$buf =~ s/<!ATTLIST\s+(\S+)\s+(.*?)>/store_att($1, $2)/gsie;
-
-# store content models
-$buf =~ s/<!ELEMENT\s+(\S+)\s+(.+?)>/store_elt($1, $2)/gsie;
-
-#print "<?xml version='1.0'?>\n";
-print "<schema
-  xmlns='http://www.w3.org/2000/10/XMLSchema'
-  targetNamespace='$targetNS'
-  xmlns:$prefix='$targetNS'>\n";
-
-# find maximum length of non-terminals
-#my $maxlen = max(map(length, @element)) + 4;
-
-# write simple type declarations
-$buf =~ s/<!_DATATYPE\s+(\S+)\s+(\S+)\s+(.+?)>/write_simpleType($1, $2, $3)/gsie;
-
-# write attribute groups
-$buf =~ s/<!_ATTRGROUP\s+(\S+)\s+(.+?)>/write_attrGroup($1, $2)/gsie;
-
-# write model groups
-$buf =~ s/<!_MODELGROUP\s+(\S+)\s+(.+?)>/write_modelGroup($1, $2)/gsie;
-
-# write subsitution groups
-$buf =~ s/<!_SUBSTGROUP\s+(\S+)\s+(.+?)>/write_substitutionGroup($1, $2)/gsie;
-
-
-my($e);
-
-# loop over elements, writing XML schema
-foreach $e (@element) {
-	 my $h = $model{$e};
-	 my $h2 = $attributes{$e};
-	 my @model = @$h;
-	 my $isSimple = ($pcdata_flag eq 1) && ($model[1] eq '#PCDATA') &&
-		  ( ($#model eq 2) || 
-			 ( ($#model eq 3) && ($model[3] eq '*') ) );
-
-	 my $substGroup = $SubstitutionGroup{$e};
-	 if ( $substGroup )
-	 {
-		  $substGroup = " substitutionGroup='$substGroup'";
-	 }
-
-	 # print rule for element $e
-	 if ( $isSimple && ! $h2 )
-	 {
-		  # Assume (#PCDATA) is string
-		  print "\n <element name='$e' type='$pcdata_simpletype'$substGroup>\n";
-	 }
-	 else {
-		  print "\n <element name='$e'$substGroup>\n";
-	 }
-
-	 if ( $isSimple )
-	 {
-		  # Assume (#PCDATA) is string
-		  if ( $h2 ) 
-		  {
-				print "  <complexType>\n";
-				print "  <simpleContent>\n";
-				print "  <extension base='string'>\n";
-		  }
-	 }
-
-	 else {
-		  # print rule for $e's content model
-		  print "  <complexType";
-		  if ($model[0] eq 'EMPTY') {
-				if (! $h2 ) {
-					 print "/>\n";
-				} else {
-					 print ">\n";
-				}
-		  } 
-		  elsif ( $model[0] eq 'ANY' )
-		  {
-				print ">\n";
-				print "   <sequence>\n";
-				print "   <any namespace='$targetNS'/>\n";
-				print "   </sequence>\n";
-		  }
-		  else {
-				if ( $debug eq 1 ) {
-					 print STDERR "==mixed? @model\n"; #@@
-				}
-				if (&isMixed(@model)) {
-					 print " mixed='true'>\n";
-				}
-				else {
-					 print ">\n";
-				}
-
-				my @list = &makeChildList('', @model);
-				&printChildList(3, @list);
-		  }
-	 }
-
-	 # print rule for $e's attributes
-	 if (! $h2) {
-		  # nothing
-	 } else {
-		  &printAttrDecls(@$h2);
-		  if ( $isSimple ) {
-				print "   </extension>\n";
-				print "   </simpleContent>\n";
-		  }
-	 }
-
-	 if ( !$h2 && $isSimple ) {
-		  # Do nothing
-	 }
-	 elsif ($h2 || $model[0] ne 'EMPTY') {
-		  print "  </complexType>\n";
-	 }
-
-	 print " </element>\n";
-}
-
-print "</schema>\n";
-exit;
-
-sub printSpace
-{
-	 my ($num) = $_[0];
-	 for (my $i=0; $i<$num; $i++) {
-		  print " ";
-	 }
-}
-
-sub printChildList
-{
-	 my ($num, @list) = @_;
-
-	 my @currentTag = ();
-	 for (my $i=0; $i<= $#list; $i++) {
-		  my $n = $list[$i];
-
-		  if ($n eq 0 || $n eq 1 || $n eq 2 || $n eq 3) {
-				if ( ($pcdata_flag eq 0) && ($n eq 0 || $n eq 1) && $list[$i+1] eq 20)
-				{
-					 # The whole list is 0 20 or 1 20; i.e. (#PCDATA) or (#PCDATA)*. 
-					 # Don't generate a sequence child; mixed handles all this.
-				}
-				else {
-#            my $do_it_flag = 1;
-					 if ( $currentTag[$#currentTag] eq "" && $n eq 0 )
-					 {
-						  push(@currentTag, "");
-#  					 my $n_1 = $list[$i+1];
-#  					 if ( $n_1 eq 10 || $n_1 eq 11 || $n_1 eq 12 || $n_1 eq 13 )
-#  					 {
-#  						  # do nothing: we have a phantom sequence wrapping a choice
-#  						  # that we want to not want to appear. OTOH we want a top 
-#  						  # level sequence in other cases.
-#  						  $do_it_flag = 0;
-#  					 }
-					 }
-
-#  				if ( $do_it_flag eq 1 )
-#  {
-					 printSpace($num); $num++;
-					 print "<sequence";
-					 if ($n eq 1) {
-						  print " minOccurs='0' maxOccurs='unbounded'";
-					 } elsif ($n eq 2) {
-						  print " maxOccurs='unbounded'";
-					 } elsif ($n eq 3) {
-						  print " minOccurs='0' maxOccurs='1'";
-					 }
-					 print ">\n";
-					 push(@currentTag, "sequence");
-				}
-#}
-		  } elsif ($n eq 10 || $n eq 11 || $n eq 12 || $n eq 13) {
-				printSpace($num); $num++;
-				print "<choice";
-				if ($n eq 11) {
-					 print " minOccurs='0' maxOccurs='unbounded'";
-				} elsif ($n eq 12) {
-					 print " maxOccurs='unbounded'";
-				} elsif ($n eq 13) {
-					 print " minOccurs='0' maxOccurs='1'";
-				}
-				print ">\n";
-				push(@currentTag, "choice");
-		  } elsif ($n eq 20) {
-				my $tag = pop(@currentTag);
-				if ($tag ne "") {
-					 $num--; printSpace($num);
-					 print "</", $tag, ">\n";
-				}
-		  } else {
-				printSpace($num);
-				if ($n eq '#MODELGROUPREF') {
-					 print "<group ref='$prefix:$list[++$i]'";
-				}
-				elsif ($n eq '#SUBSTGROUPREF') {
-					 print "<element ref='$prefix:$list[++$i]'";
-				} else {
-					 print "<element ref='$prefix:$n'";
-				}
-
-				if ($currentTag[$#currentTag] ne "choice") {
-					 if ($list[$i+1] eq "+") {
-						  print " maxOccurs='unbounded'";
-						  $i++;
-					 } elsif ($list[$i+1] eq "?") {
-						  print " minOccurs='0' maxOccurs='1'";
-						  $i++;
-					 } elsif ($list[$i+1] eq "*") {
-						  print " minOccurs='0' maxOccurs='unbounded'";
-						  $i++;
-					 }
-				}
-				print "/>\n";
-		  }
-	 }
-}
-
-sub makeChildList {
-	 my ($groupName, @model) = @_;
-	 my @ret = ();
-	 my @brace = ();
-	 for (my $i=0; $i<=$#model; $i++) {
-		  my $n = $model[$i];
-
-		  if ($n eq "(") {
-				push(@ret, 0);
-				push(@brace, $#ret);
-		  } elsif ($n eq ")") {
-				if ($model[$i+1] eq "*") {
-					 $ret[$brace[$#brace]] += 1;
-					 $i++;
-				} elsif ($model[$i+1] eq "+") {
-					 $ret[$brace[$#brace]] += 2;
-					 $i++;
-				} elsif ($model[$i+1] eq "?") {
-					 $ret[$brace[$#brace]] += 3;
-					 $i++;
-				}
-				pop(@brace);
-				push(@ret, 20);
-		  } elsif ($n eq ",") {
-				$ret[$brace[$#brace]] = 0;
-		  } elsif ($n eq "|") {
-				$ret[$brace[$#brace]] = 10;
-		  } elsif ($n eq "#PCDATA") {
-				if ($model[$i+1] eq "|") {
-					 $i++;
-				}
-				if($groupName){
-					 $Mixed{$groupName} = 1;
-				}
-		  } else {
-				push(@ret, $n);
-		  }
-	 }
-
-	 # "( ( a | b | c )* )" gets mapped to "0 10 a b c 20 20" which will generate
-	 # a spurious sequence element. This is not too harmful when this is an
-	 # element content model, but with model groups it is incorrect.
-	 # In general we need to strip off 0 20 from the ends when it is redundant. 
-	 # Redundant means: there is some other group that bounds the whole list. 
-	 # Note that it gets a little tricky:
-	 # ( (a|b),(c|d) ) gets mapped to "0 10 a b 20 10 c d 20 20". If one
-	 # naively chops off the 0 and 20 on the groups that there is a 10 on one
-	 # end and a 20 on the other, one loses the bounding sequence, which is 
-	 # required in this case.
-	 #
-	 if ( $ret[0] eq 0 && $ret[$#ret] eq 20 && $ret[$#ret-1] eq 20 &&
-			( $ret[1] eq 0 || $ret[1] eq 1 || $ret[1] eq 2 || $ret[1] eq 3 ||
-			  $ret[1] eq 10 || $ret[1] eq 11 || $ret[1] eq 12 || $ret[1] eq 13 )
-			)
-	 {
-		  # OK, it is possible that the 0 20 is redundant. Now scan for balance:
-		  # All interim 20 between the proposed new start and the proposed new
-		  # final one should be at level 1 or above. 
-		  my $depth = 0;
-		  my $redundant_paren = 1;  # Assume redundant until proved otherwise
-		  for ( my $i = 1; $i <= $#ret-1; $i++ )
-		  {
-				if ( $ret[$i] eq 20 )
-				{
-					 $depth--;
-					 if ( $i < $#ret-1 && $depth < 1 )
-					 {
-						  $redundant_paren = 0;
-						  print STDERR "i=$i,depth=$depth\n";
-					 }
-				}
-				elsif ( $ret[$i] eq 0 || 
-						  $ret[$i] eq 1 || 
-						  $ret[$i] eq 2 || 
-						  $ret[$i] eq 3 ||
-						  $ret[$i] eq 10 || 
-						  $ret[$i] eq 11 || 
-						  $ret[$i] eq 12 || 
-						  $ret[$i] eq 13 
-						  )
-				{
-					 $depth++;
-				}
-		  }  # for
-
-		  if ( $redundant_paren eq 1 )
-		  {
-				print STDERR "Truncating @ret\n";
-				@ret = @ret[1..$#ret-1];
-		  }
-	 }
-
-	 if ( $debug eq 1 ) {
-		  print STDERR "@model to @ret\n";
-	 }
-	 return @ret;
-}
-
-
-sub printAttrDecls{
-    my @atts = @_;
-
-    for (my $i = 0; $i <= $#atts; $i++) {
-		  if ($atts[$i] eq '#ATTRGROUPREF'){
-				print "   <attributeGroup ref='$prefix:$atts[$i+1]'/>\n";
-				$i ++;
-		  } else {
-				# attribute name
-				print "   <attribute name='$atts[$i]'";
-
-				# attribute type
-				my @enume;
-				$i++;
-				if ($atts[$i] eq "(") {
-					 # like `attname ( yes | no ) #REQUIRED`
-					 $i++;
-					 while ($atts[$i] ne ")") {
-						  if ($atts[$i] ne "|") {
-								push(@enume, $atts[$i]);
-						  }
-						  $i++;
-					 }
-				} elsif ($atts[$i] eq '#DATATYPEREF'){
-					 print " type='$prefix:$atts[++$i]'";
-				} elsif ($alias eq 1 && $atts[$i] =~ s/$alias_ident//gsie) {
-					 # alias special
-					 print " type='$alias_dic{$atts[$i]}'";
-				} elsif ($atts[$i] =~ /ID|IDREF|ENTITY|NOTATION|IDREFS|ENTITIES|NMTOKEN|NMTOKENS/) {
-					 # common type for DTD and Schema
-					 print " type='$atts[$i]'";
-				} else {
-					 # `attname CDATA #REQUIRED`
-					 print " type='string'";
-				}
-
-				$i++;
-
-				# #FIXED
-				if($atts[$i] eq "#FIXED") {
-					 $i++;
-					 print " use='fixed' value='$atts[$i]'/>\n";
-				} else {
-					 # minOccurs
-					 if ($atts[$i] eq "#REQUIRED") {
-						  print " use='required'";
-					 } elsif ($atts[$i] eq "#IMPLIED") {
-						  print " use='optional'";
-					 } else {
-						  print " default='optional' default='$atts[$i]'";
-					 }
-
-					 # enumerate
-					 if ($#enume eq -1) {
-						  print "/>\n";
-					 } else {
-						  print ">\n";
-						  print "    <simpleType>\n";
-						  print "     <restriction base='string'>\n";
-						  &write_enum(@enume);
-						  print "     </restriction>\n";
-						  print "    </simpleType>\n";
-						  print "   </attribute>\n";
-					 }
-				}
-		  }
-    }
-}
-
-sub write_enum{
-    my(@enume) = @_;
-
-    for (my $j = 0; $j <= $#enume; $j++) {
-		  print "      <enumeration value='$enume[$j]'/>\n";
-    }
-}
-
-
-# Parse a string into an array of "words".
-# Words are whitespace-separated sequences of non-whitespace characters,
-# or quoted strings ("" or ''), with the quotes removed.
-# HACK: added () stuff for attlist stuff
-# Parse words for attribute list
-sub parsewords {
-	 my $line = $_[0];
-	 $line =~ s/(\(|\)|\|)/ $1 /g;
-	 my @words = ();
-
-	 while ($line ne '') {
-		  if ($line =~ /^\s+/) {
-				# Skip whitespace
-		  } elsif ($line =~ /^\"((?:[^\"]|\\\")*)\"/) {
-				push(@words, $1);
-		  } elsif ($line =~ /^\'((?:[^\']|\\\')*)\'/) {
-				push(@words, $1);
-		  } elsif ($line =~ /^\S+/) {
-				push(@words, $&);
-		  } else {
-				die "Cannot happen\n";
-		  }
-		  $line = $';
-	 }
-    return @words;
-}
-
-# Store content model, return empty string
-sub store_elt
-{
-	 my ($name, $model) = @_;
-	 $model =~ s/\s+/ /gso;
-	 push(@element, $name);
-
-	 my @words;
-	 while ($model =~ s/^\s*(\(|\)|,|\+|\?|\||[\w_\.-]+|\#\w+|\*)//) {
-		  push(@words, $1);
-	 };
-	 $model{$name} = [ @words ];
-	 return '';
-}
-
-
-# Store attribute list, return empty string
-sub store_att
-{
-	 my ($element, $atts) = @_;
-	 my @words = parsewords($atts);
-	 $attributes{$element} = [ @words ];
-	 return '';
-}
-
-sub write_simpleType{
-    my($n, $b, $stuff) = @_;
-    my @words = parsewords($stuff);
-
-    print "\n  <simpleType name='$n'>\n";
-    print "   <restriction base='$b'>\n";
-#    print STDERR "\n==stuff:\n$stuff \n\n===\n", join('|', @words);
-
-    my $i = 0;
-    my @enume;
-
-    if ($words[$i] eq "(") {
-		  $i++;
-		  while ($words[$i] ne ")") {
-				if ($words[$i] ne "|") {
-					 push(@enume, $words[$i]);
-				}
-				$i++;
-		  }
-		  write_enum(@enume);
-    }
-
-	 print "   </restriction>\n";
-    print "  </simpleType>\n";
-}
-
-sub write_attrGroup{
-    my($n, $stuff) = @_;
-    my @words = parsewords($stuff);
-
-    print "\n  <attributeGroup name='$n'>\n";
-#    print STDERR "\n==stuff:\n$stuff \n\n===\n", join('|', @words);
-    printAttrDecls(@words);
-    print "  </attributeGroup>\n";
-}
-
-sub write_modelGroup{
-    my($n, $stuff) = @_;
-    my @words = parsewords($stuff);
-
-    print "\n  <group name='$n'>\n";
-    print "<!-- $stuff -->\n";
-
-    my @list = &makeChildList($n, '(', @words, ')');
-    &printChildList(3, @list);
-
-    $ModelGroup{$n} = \@list;
-
-    print "  </group>\n";
-}
-
-sub write_substitutionGroup
-{
-    my($n, $stuff) = @_;
-    my @words = parsewords($stuff);
-
-    print "\n  <element name='$n' abstract='true'>\n";
-
-    my @list = &makeChildList($n, '(', @words, ')');
-	 for ( my $i = 0; $i < $#list; $i++ )
-	 {
-		  $SubstitutionGroup{ $list[$i] } = $n;
-	 }
-
-    print "  </element>\n";
-}
-
-sub isMixed{
-    my(@model) = @_;
-	 my $isSimple = ($pcdata_flag eq 1) && ($model[1] eq '#PCDATA') &&
-		  ( ($#model eq 2) || 
-			 ( ($#model eq 3) && ($model[3] eq '*') ) );
-
-	 if ( $debug eq 1 ) {
-		  print STDERR "++ mixed? @model\n"; #@@
-	 }
-
-	 if ( $isSimple )
-	 {
-		  if ( $debug eq 1 ) 
-		  {
-				print STDERR "++ no; simple type. @model\n"; #@@
-		  }
-		  return 0;
-	 }
-
-    my($i);
-
-    for ($i = 0; $i <= $#model; $i++) {
-		  if ( $model[$i] eq '#PCDATA' ||
-				 ($model[$i] eq '#MODELGROUPREF' && $Mixed{$model[$i+1]}) ||
-				 ($model[$i] eq '#SUBSTGROUPREF' && $Mixed{$model[$i+1]}) )
-		  {
-				if ( $debug eq 1 ) {
-					 print STDERR "++ yes! $i @model\n"; #@@
-				}
-				return 1;
-		  }
-    }
-
-	 if ( $debug eq 1 ) {
-		  print STDERR "++ no. @model\n"; #@@
-	 }
-
-    return 0;
-}
-
-# Return maximum value of an array of numbers
-sub max
-{
-	 my $max = $_[0];
-	 foreach my $i (@_) {
-		  if ($i > $max) {$max = $i;}
-	 }
-	 return $max;
-}
-
-
-# 1) Open file
-# 2) Remove comment, processing instructions, and general entities
-# 3) Include external parameter entities recursively
-# 4) Return the contents of opened file
-sub openFile {
-	 my $file = $_[0];
-
-	 my %extent;
-	 my $bufbuf;
-	 if ($file ne "") {
-		  print STDERR "open $file ";
-		  if(! open AAA, $file) {
-				print STDERR " failed!!\n";
-				return "";
-		  }
-		  print STDERR " successful\n";
-		  $bufbuf = <AAA>;
-	 } else {
-		  print STDERR "open STDIN successful\n";
-		  $bufbuf = <>;
-	 }
-
-	 # remove comments
-	 $bufbuf =~ s/<!--.*?-->//gso;
-
-	 # remove processing instructions
-	 $bufbuf =~ s/<\?.*?>//gso;
-
-	 # store external parameter entities
-	 while ($bufbuf =~ s/<!ENTITY\s+%\s+(\S+)\s+PUBLIC\s+$str\s+$str.*?>//sie) {
-		  $extent{$1} = $4.$5;
-	 }
-	 while ($bufbuf =~ s/<!ENTITY\s+%\s+(\S+)\s+SYSTEM\s+$str.*?>//sie) {
-		  $extent{$1} = $2.$3;
-	 }
-
-	 # read external entity files
-	 foreach my $key (keys(%extent)) {
-		  $bufbuf =~ s/%$key;/openFile($extent{$key})/gsie;
-	 }
-
-	 return $bufbuf;
-}
-
-# $Log: dtd2xsd.pl,v $
-# Revision 1.17  2001/01/19 05:59:12  connolly
-# more changelog stuff; link to MH's announcement etc.
-#
-# Revision 1.16  2001/01/19 05:55:56  connolly
-# added Log at end
-#
-# Changes: 2001/01/10
-# Date:      Thu, 11 Jan 2001 14:51:44 -0800
-# From:      Mary Holstege <holstege@mathling.com>
-# To:        xml-dev@lists.xml.org
-# Subject:   [ANN] Updated version of DTD to XML Schema tool
-# http://lists.xml.org/archives/xml-dev/200101/msg00481.html
-# http://www.mathling.com/xmlschema/
-# Switch to CR syntax
-# Support external mapping file for type aliases, simple types, model and
-#    attribute groups
-# Map ANY correctly to wildcard rather than element 'ANY'
-# Support treating lead PCDATA as string or other aliased simple type instead
-# of as mixed content (may be more appropriate for data-oriented DTDs)
-#    e.g. <!ELEMENT title (#PCDATA)> => <element name="title" type="string"/>
-# Support subsitution groups.
diff --git a/python/libmumbl/xmml/bin/mkrelease b/python/libmumbl/xmml/bin/mkrelease
deleted file mode 100755
index b3b462dec78e76dec997f962ddff02ff0d5f23f5..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/bin/mkrelease
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/bin/bash
-# Make a release of the xMML format. Part of the xMML distribution.
-# Author: J.Borgdorff, created 2011-02-21
-# Start in xMML directory
-
-VERSION=$1
-TAG=v$VERSION
-NAME=xmml-$VERSION
-DIR=release/$NAME
-TARDIR=$DIR-tar
-SUCCEED=0
-BRANCH=`git branch | grep \* | sed -e 's/\*//' | sed -e 's/[[:space:]]*//g'`
-
-git checkout -q $TAG 1>/dev/null 2>&1
-
-if [[ $? -ne 0 ]]; then
-  echo "ERROR: can not check out tag of the version specified"
-  exit
-fi
-
-mkdir -p $DIR/doc
-mkdir -p $TARDIR/doc
-if [[ `grep \"$VERSION\" xmml.dtd | wc -l` -gt 0 ]]; then
-	cp xmml.dtd $DIR/xmml-$VERSION.dtd
-	cp xmml.dtd $TARDIR/xmml.dtd
-else
-	echo "WARNING: xMML Document Type Definition does not match version of Git repository"
-	SUCCEED=1
-fi
-
-if [[ `grep \'$VERSION\' xmml.xsd | wc -l` -gt 0 ]]; then
-	cp xmml.xsd $DIR/xmml-$VERSION.xsd
-	cp xmml.xsd $TARDIR/xmml.xsd
-else
-	echo "WARNING: xMML Schema Definition does not match version of Git repository"
-	SUCCEED=1
-fi
-
-
-if [[ `grep \'$VERSION\' xmml_param.xsd | wc -l` -gt 0 ]]; then
-	cp xmml_param.xsd $DIR/xmml_param-$VERSION.xsd
-	cp xmml_param.xsd $TARDIR/xmml_param.xsd
-else
-	echo "WARNING: xMML Param Schema Definition does not match version of Git repository"
-	SUCCEED=1
-fi
-
-
-cp CHANGELOG.txt $DIR/CHANGELOG.txt
-cp CHANGELOG.txt $TARDIR/CHANGELOG.txt
-
-ant
-cp doc/* $DIR/doc
-cp doc/* $TARDIR/doc
-
-mv $DIR $DIR.tmp
-mv $TARDIR $DIR
-cd release
-tar czf ../$DIR.tar.gz $NAME
-rm -r $NAME
-cd ..
-mv $DIR.tmp $DIR
-
-git checkout -q $BRANCH
-
-if [[ $SUCCEED -eq 0 ]]; then
-	echo "Release $VERSION created in directory $DIR"
-fi
-
diff --git a/python/libmumbl/xmml/bin/validate b/python/libmumbl/xmml/bin/validate
deleted file mode 100755
index 807b328641b70dca69eb60cdfe183ef5a84481d2..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/bin/validate
+++ /dev/null
@@ -1,21 +0,0 @@
-#!/bin/bash
-# call: validate XML_IN [ XMML_OUT ]
-
-if [[ $# -eq 0 ]]; then
-  echo "Usage: validate xmml_file [ validated_file ]"
-else
-  # Validate using xmllint, doing any xincludes necessary
-  COMMAND="xmllint --xinclude --schema xmml.xsd --schema xmml_param.xsd"
-  if [[ $# -eq 1 ]]; then
-    EXTRA=""
-    $COMMAND --noout $1
-  else
-    EXTRA="; file '$2' can be used as a xMML file directly"
-    $COMMAND --output $2 $1
-  fi
-
-  if [[ $? -eq 0 ]]; then
-    echo "File '$1' contains valid xMML after performing XInclude$EXTRA."
-  fi
-fi
-
diff --git a/python/libmumbl/xmml/bin/xsd2dtd.xsl b/python/libmumbl/xmml/bin/xsd2dtd.xsl
deleted file mode 100644
index d5ba6b2efaddc9cdc9a1d70586ce2b1b0aaa5634..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/bin/xsd2dtd.xsl
+++ /dev/null
@@ -1,418 +0,0 @@
-<?xml version="1.0"?>
-<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
-  version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
-
-  <xsl:output method="text"/>
-
-  <xsl:strip-space elements="*"/>
-
-  <!-- A few common block-level elements encountered in
-       documentation. -->
-  <xsl:template match="para | title | refpurpose">
-    <xsl:apply-templates/>
-    <xsl:text>&#xa;</xsl:text>
-  </xsl:template>
-
-  <xsl:template match="indexterm"/>
-
-  <xsl:template match="xs:attribute" mode="attributes">
-    <xsl:text>&#xa;  </xsl:text>
-    <xsl:choose>
-      <xsl:when test="@name">
-	<xsl:value-of select="@name"/>
-	<xsl:choose>
-	  <xsl:when test="xs:simpleType">
-	    <xsl:apply-templates select="xs:simpleType"/>
-	  </xsl:when>
-	  <xsl:when test="@type">
-	    <xsl:call-template name="simpleType">
-	      <xsl:with-param name="type" select="@type"/>
-	    </xsl:call-template>
-	  </xsl:when>
-	</xsl:choose>
-      </xsl:when>
-      <xsl:when test="@ref">
-	<xsl:value-of select="substring-after(@ref,':')"/>
-	<xsl:if test="@ref = 'xml:lang'">
-	  <xsl:text> CDATA</xsl:text>
-	</xsl:if>
-      </xsl:when>
-    </xsl:choose>
-    <xsl:choose>
-      <xsl:when test="@use = 'required'">
-        <xsl:text> #REQUIRED</xsl:text>
-      </xsl:when>
-      <xsl:when test="@default">
-        <xsl:text> "</xsl:text>
-        <xsl:value-of select="@default"/>
-        <xsl:text>"</xsl:text>
-      </xsl:when>
-      <xsl:when test="@fixed">
-        <xsl:text> #FIXED "</xsl:text>
-        <xsl:value-of select="@fixed"/>
-        <xsl:text>"</xsl:text>
-      </xsl:when>
-      <xsl:otherwise>
-        <xsl:text> #IMPLIED</xsl:text>
-      </xsl:otherwise>
-    </xsl:choose>
-  </xsl:template>
-
-  <xsl:template match="xs:attribute[@ref][xs:annotation/xs:documentation]" mode="attr-comments">
-    <xsl:text>&#xa;</xsl:text>
-    <xsl:value-of select="substring-after(@ref,':')"/>
-    <xsl:text>: </xsl:text>
-    <xsl:value-of select="xs:annotation/xs:documentation"/>
-    <xsl:text>&#xa;</xsl:text>
-  </xsl:template>
-
-  <xsl:template match="xs:attribute[xs:annotation/xs:documentation]" mode="attr-comments">
-    <xsl:text>&#xa;</xsl:text>
-    <xsl:value-of select="@name"/>
-    <xsl:text>: </xsl:text>
-    <xsl:value-of select="xs:annotation/xs:documentation"/>
-    <xsl:text>&#xa;</xsl:text>
-  </xsl:template>
-
-  <xsl:template match="xs:attribute"/>
-
-  <xsl:template match="xs:attributeGroup[@name]"/>
-
-  <xsl:template match="xs:attributeGroup[@ref]" mode="attributes">
-    <xsl:text>&#xa;  %</xsl:text>
-    <xsl:value-of select="substring-after(@ref,':')"/>
-    <xsl:text>;</xsl:text>
-  </xsl:template>
-
-  <xsl:template match="xs:attributeGroup[@name]" mode="groups">
-    <xsl:text>&#xa;&#xa;&lt;!-- ATTRIBUTE GROUP </xsl:text>
-    <xsl:value-of select="@name"/>
-    <xsl:text> --></xsl:text>
-    <xsl:apply-templates select="xs:annotation"/>
-    <xsl:text>&#xa;&lt;!--</xsl:text>
-    <xsl:apply-templates select="descendant::xs:attribute"
-      mode="attr-comments"/>
-    <xsl:text>-->&#xa;</xsl:text>
-    <xsl:text>&#xa;&lt;!ENTITY % </xsl:text>
-    <xsl:value-of select="@name"/>
-    <xsl:text> "</xsl:text>
-    <xsl:apply-templates select="descendant::xs:attribute"
-      mode="attributes"/>
-    <xsl:text> " ></xsl:text>
-  </xsl:template>
-
-  <xsl:template match="xs:choice">
-    <xsl:if test="not(parent::xs:group)">
-      <xsl:text> (</xsl:text>
-    </xsl:if>
-    <xsl:for-each select="*">
-      <xsl:apply-templates select="."/>
-      <xsl:if test="position() != last()">
-        <xsl:text> |</xsl:text>
-      </xsl:if>
-    </xsl:for-each>
-    <xsl:if test="not(parent::xs:group)">
-      <xsl:text> )</xsl:text>
-    </xsl:if>
-    <xsl:call-template name="occurrence"/>
-  </xsl:template>
-
-  <xsl:template match="xs:complexType">
-    <xsl:choose>
-      <xsl:when test="xs:all">
-        <xsl:text> ANY</xsl:text>
-      </xsl:when>
-      <xsl:when test="xs:choice | xs:complexContent | xs:group |
-                      xs:sequence | xs:simpleContent">
-        <xsl:choose>
-          <xsl:when test="@mixed='true'">
-            <xsl:text> ( #PCDATA </xsl:text>
-            <xsl:for-each select="descendant::xs:group |
-                                  descendant::xs:element">
-              <xsl:text>| </xsl:text>
-              <xsl:if test="self::xs:group">
-                <xsl:text>%</xsl:text>
-              </xsl:if>
-              <xsl:value-of select="substring-after(@ref,':')"/>
-              <xsl:if test="self::xs:group">
-                <xsl:text>;</xsl:text>
-              </xsl:if>
-            </xsl:for-each>
-            <xsl:text> )*</xsl:text>
-          </xsl:when>
-          <xsl:otherwise>
-            <xsl:apply-templates/>            
-          </xsl:otherwise>
-        </xsl:choose>
-      </xsl:when>
-      <xsl:when test="@mixed='true'">
-        <xsl:text> ( #PCDATA )</xsl:text>
-      </xsl:when>
-      <xsl:otherwise>
-        <xsl:text> EMPTY</xsl:text>
-      </xsl:otherwise>
-    </xsl:choose>
-  </xsl:template>
-
-  <xsl:template match="xs:documentation">
-    <xsl:text>&#xa;&lt;!--&#xa;</xsl:text>
-    <xsl:apply-templates/>
-    <xsl:text>&#xa;--></xsl:text>
-  </xsl:template>
-
-  <xsl:template match="xs:element[@name]">
-    <xsl:if test="not(preceding-sibling::xs:element)">
-      <xsl:apply-templates select="../xs:group" mode="groups"/>
-      <xsl:apply-templates select="../xs:attributeGroup"
-        mode="groups"/>
-    </xsl:if>
-    <xsl:text>&#xa;&#xa;&lt;!-- ELEMENT </xsl:text>
-    <xsl:value-of select="@name"/>
-    <xsl:text> --></xsl:text>
-    <xsl:apply-templates select="xs:annotation"/>
-    <xsl:text>&#xa;&lt;!ELEMENT </xsl:text>
-    <xsl:value-of select="@name"/>
-    <xsl:choose>
-      <xsl:when test="xs:complexType">
-        <xsl:apply-templates select="xs:complexType"/>
-      </xsl:when>
-      <xsl:when test="xs:simpleType">
-        <xsl:text> ( #PCDATA )</xsl:text>
-      </xsl:when>
-      <xsl:when test="@type">
-        <xsl:text> ( #PCDATA )</xsl:text>
-      </xsl:when>
-      <xsl:otherwise>
-        <xsl:text> EMPTY</xsl:text>
-      </xsl:otherwise>
-    </xsl:choose>
-    <xsl:text> ></xsl:text>
-    <xsl:if
-      test="descendant::xs:attribute | descendant::xs:attributeGroup">
-      <xsl:text>&#xa;&lt;!--</xsl:text>
-      <xsl:apply-templates
-	select="descendant::xs:attribute |
-		descendant::xs:attributeGroup"
-        mode="attr-comments"/>
-      <xsl:text>-->&#xa;</xsl:text>
-    </xsl:if>
-    <xsl:if test="/xs:schema/@targetNamespace |
-                  descendant::xs:attribute |
-		  descendant::xs:attributeGroup">
-      <xsl:text>&lt;!ATTLIST </xsl:text>
-      <xsl:value-of select="@name"/>
-      <!--<xsl:if test="/xs:schema/@targetNamespace">
-        <xsl:text>&#xa;  xmlns CDATA #FIXED "</xsl:text>
-        <xsl:value-of select="/xs:schema/@targetNamespace"/>
-        <xsl:text>"</xsl:text>
-      </xsl:if>-->
-      <xsl:if
-	test="descendant::xs:attribute |
-	      descendant::xs:attributeGroup">
-        <xsl:apply-templates
-	  select="descendant::xs:attribute |
-		  descendant::xs:attributeGroup"
-          mode="attributes"/>
-      </xsl:if>
-      <xsl:text> ></xsl:text>
-    </xsl:if>
-  </xsl:template>
-
-  <xsl:template match="xs:element[@ref]">
-    <xsl:text> </xsl:text>
-    <xsl:value-of select="substring-after(@ref,':')"/>
-    <xsl:call-template name="occurrence"/>
-  </xsl:template>
-
-  <xsl:template match="xs:group[@name]"/>
-
-  <xsl:template match="xs:group[@name]" mode="groups">
-    <xsl:text>&#xa;&#xa;&lt;!-- GROUP </xsl:text>
-    <xsl:value-of select="@name"/>
-    <xsl:text> --></xsl:text>
-    <xsl:apply-templates select="xs:annotation"/>
-    <xsl:text>&#xa;&lt;!ENTITY % </xsl:text>
-    <xsl:value-of select="@name"/>
-    <xsl:text> "</xsl:text>
-    <xsl:apply-templates select="xs:choice | xs:complexContent |
-                                 xs:group | xs:sequence |
-                                 xs:simpleContent"/>
-    <xsl:text> " ></xsl:text>
-  </xsl:template>
-
-  <xsl:template match="xs:group[@ref]">
-    <xsl:text> (%</xsl:text>
-    <xsl:value-of select="substring-after(@ref,':')"/>
-    <xsl:text>;)</xsl:text>
-    <xsl:call-template name="occurrence"/>
-  </xsl:template>
-
-  <xsl:template match="xs:import">
-    <xsl:text>&#xa;&#xa;&lt;!-- IMPORT:&#xa;</xsl:text>
-    <xsl:text>     namespace: </xsl:text>
-    <xsl:value-of select="@namespace"/>
-    <xsl:text>&#xa;     URI: </xsl:text>
-    <xsl:value-of select="@schemaLocation"/>
-    <xsl:text> --></xsl:text>
-    <xsl:apply-templates select="xs:annotation"/>
-  </xsl:template>
-
-  <xsl:template match="xs:include">
-    <xsl:variable name="sysent-name">
-      <xsl:choose>
-        <xsl:when test="document(@schemaLocation)/xs:schema/@id">
-          <xsl:value-of
-            select="document(@schemaLocation)/xs:schema/@id"/>
-        </xsl:when>
-        <xsl:otherwise>
-          <xsl:value-of select="translate(@schemaLocation, ' ', '')"/>
-        </xsl:otherwise>
-      </xsl:choose>
-    </xsl:variable>
-    <xsl:apply-templates select="xs:annotation"/>
-    <xsl:text>&#xa;&lt;!ENTITY % </xsl:text>
-    <xsl:value-of select="$sysent-name"/>
-    <xsl:text> SYSTEM "</xsl:text>
-    <xsl:value-of
-      select="substring-before(@schemaLocation, '.xsd')"/>
-    <xsl:text>.dtd" >&#xa;</xsl:text>
-    <xsl:text>%</xsl:text>
-    <xsl:value-of select="$sysent-name"/>
-    <xsl:text>;&#xa;</xsl:text>
-  </xsl:template>
-
-  <xsl:template match="xs:restriction">
-    <xsl:choose>
-      <xsl:when test="xs:enumeration">
-        <xsl:text> ( </xsl:text>
-        <xsl:for-each select="xs:enumeration">
-          <xsl:value-of select="@value"/>
-          <xsl:if test="position() != last()">
-            <xsl:text> | </xsl:text>
-          </xsl:if>
-        </xsl:for-each>
-        <xsl:text> )</xsl:text>
-      </xsl:when>
-      <xsl:otherwise>
-        <xsl:call-template name="simpleType">
-          <xsl:with-param name="type" select="@base"/>
-        </xsl:call-template>
-      </xsl:otherwise>
-    </xsl:choose>
-  </xsl:template>
-
-  <xsl:template match="xs:schema">
-    <xsl:text>&lt;!-- Note that the original schema </xsl:text>
-    <xsl:text>declarations may be stricter than&#xa;</xsl:text>
-    <xsl:text>     represented here; please see the </xsl:text>
-    <xsl:text>documentation for each element&#xa;</xsl:text>
-    <xsl:text>     type. -->&#xa;</xsl:text>
-    <xsl:apply-templates/>
-  </xsl:template>
-
-  <xsl:template match="xs:sequence">
-    <xsl:if test="not(parent::xs:group)">
-      <xsl:text> (</xsl:text>
-    </xsl:if>
-    <xsl:for-each select="*">
-      <xsl:apply-templates select="."/>
-      <xsl:if test="position() != last()">
-        <xsl:text>,</xsl:text>
-      </xsl:if>
-    </xsl:for-each>
-    <xsl:if test="not(parent::xs:group)">
-      <xsl:text> )</xsl:text>
-    </xsl:if>
-    <xsl:call-template name="occurrence"/>
-  </xsl:template>
-
-  <xsl:template match="xs:schema/xs:simpleType"/>
-
-  <xsl:template match="xs:simpleType">
-    <xsl:choose>
-      <xsl:when test="xs:restriction/@base='xs:NMTOKEN' and
-                      xs:restriction/xs:enumeration">
-        <xsl:text> ( </xsl:text>
-        <xsl:for-each select="xs:restriction/xs:enumeration">
-          <xsl:value-of select="@value"/>
-          <xsl:if test="position() != last()">
-            <xsl:text> | </xsl:text>
-          </xsl:if>
-        </xsl:for-each>
-        <xsl:text> )</xsl:text>
-      </xsl:when>
-      <xsl:when
-        test="xs:list/@itemType='xs:NMTOKEN' or
-              xs:list/xs:simpleType/xs:restriction/@base='xs:NMTOKEN'">
-        <xs:text> NMTOKENS</xs:text>
-      </xsl:when>
-      <xsl:when
-        test="xs:list/@itemType='xs:IDREF' or
-              xs:list/xs:simpleType/xs:restriction/@base='xs:IDREF'">
-        <xs:text> IDREFS</xs:text>
-      </xsl:when>
-      <xsl:otherwise>
-        <xsl:text> CDATA</xsl:text>
-      </xsl:otherwise>
-    </xsl:choose>
-  </xsl:template>
-
-  <xsl:template name="occurrence">
-    <xsl:variable name="minOccurs">
-      <xsl:choose>
-        <xsl:when test="@minOccurs">
-          <xsl:value-of select="@minOccurs"/>
-        </xsl:when>
-        <xsl:otherwise>
-          <xsl:value-of select="1"/>
-        </xsl:otherwise>
-      </xsl:choose>
-    </xsl:variable>
-    <xsl:variable name="maxOccurs">
-      <xsl:choose>
-        <xsl:when test="@maxOccurs">
-          <xsl:value-of select="@maxOccurs"/>
-        </xsl:when>
-        <xsl:otherwise>
-          <xsl:value-of select="1"/>
-        </xsl:otherwise>
-      </xsl:choose>
-    </xsl:variable>
-    <xsl:choose>
-      <xsl:when test="$minOccurs = 0 and $maxOccurs = 1">
-        <xsl:text>?</xsl:text>
-      </xsl:when>
-      <xsl:when test="$minOccurs = 0">
-        <xsl:text>*</xsl:text>
-      </xsl:when>
-      <xsl:when test="$maxOccurs = 1"/>
-      <xsl:otherwise>
-        <xsl:text>+</xsl:text>
-      </xsl:otherwise>
-    </xsl:choose>
-  </xsl:template>
-
-  <!-- only used by attributes -->
-  <xsl:template name="simpleType">
-    <xsl:param name="type"/>
-    <xsl:choose>
-      <xsl:when test="$type = 'xs:boolean'">
-        <xsl:text> ( true | false )</xsl:text>
-      </xsl:when>
-      <xsl:when test="$type = 'xs:Name' or $type = 'xs:NCName' or
-                      $type = 'xs:NMTOKEN'">
-        <xsl:text> NMTOKEN</xsl:text>
-      </xsl:when>
-      <xsl:when test="$type = 'xs:ID' or $type = 'xs:IDREF' or
-                      $type = 'xs:IDREFS' or $type = 'xs:ENTITY' or
-                      $type = 'xs:ENTITIES' or $type = 'xs:NMTOKENS'">
-        <xsl:text> </xsl:text>
-        <xsl:value-of select="substring-after($type,'xs:')"/>
-      </xsl:when>
-      <xsl:otherwise>
-        <xsl:text> CDATA</xsl:text>
-      </xsl:otherwise>
-    </xsl:choose>
-  </xsl:template>
-
-</xsl:transform>
diff --git a/python/libmumbl/xmml/examples/canal.xml b/python/libmumbl/xmml/examples/canal.xml
deleted file mode 100644
index 5892c1dd5e86bdc493b3c5f4a3b9df035b4791b3..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/examples/canal.xml
+++ /dev/null
@@ -1,76 +0,0 @@
-<?xml version="1.0" standalone="no"?>
-<!DOCTYPE model SYSTEM "xmml.dtd">
-<model id="Canals" name="Canal system" xmml_version="0.4" xmlns="http://www.mapper-project.eu/xmml" xmlns:xi="http://www.w3.org/2001/XInclude">
-    <description>
-      A canal system in France, with possible floods or sedimentation.
-    </description>
-
-    <definitions>
-      <xi:include href="isr_meta.xml#xpointer(/metadata/*)"/>
-
-      <submodel id="C1D" name="Canal1D" init="yes">
-        <timescale delta="10 min" total="1 yr"/>
-        <spacescale id="x" delta="1 m" total="3 km"/>
-
-        <ports>
-          <in id="flow_left_in" operator="S" datatype="double"/>
-          <in id="flow_right_in" operator="S" datatype="double"/>
-          <out id="flow_left_out" operator="Oi" datatype="double"/>
-          <out id="flow_right_out" operator="Oi" datatype="double"/>
-        </ports>
-      </submodel>
-
-      <submodel id="J" name="Junction">
-        <timescale delta="10 min" total="1 yr"/>
-        <spacescale delta="1 dm" total="3 m"/>
-
-        <ports>
-          <in id="flow_left_in" operator="S" datatype="double"/>
-          <in id="flow_right_in" operator="S" datatype="double"/>
-          <in id="flow_top_in" operator="S" datatype="double"/>
-          <out id="flow_left_out" operator="Oi" datatype="double"/>
-          <out id="flow_right_out" operator="Oi" datatype="double"/>
-          <out id="flow_top_out" operator="Oi" datatype="double"/>
-        </ports>
-      </submodel>
-
-      <submodel id="END" name="End point">
-        <timescale delta="10 min" total="1 yr"/>
-        <spacescale delta="1 dm" total="3 m"/>
-
-        <ports>
-          <in id="flow_in" operator="S" datatype="double"/>
-          <out id="flow_out" operator="Oi" datatype="double"/>
-        </ports>
-      </submodel>
-    </definitions>
-  
-  <topology>
-    <instance id="c1" submodel="C1D">
-      <spacescale id="x" total="2 km"/>
-    </instance>
-    <instance id="c2" submodel="C1D"/>
-    <instance id="c3" submodel="C1D">
-      <spacescale id="x" total="1 km"/>
-    </instance>
-    <instance id="src" submodel="END"/>
-    <instance id="sink1" submodel="END"/>
-    <instance id="sink2" submodel="END"/>
-    <instance id="j" submodel="J"/>
-
-    <coupling from="c1.flow_left_out" to="src.flow_in"/>
-    <coupling from="c1.flow_left_in" to="src.flow_out"/>
-    <coupling from="c1.flow_right_out" to="j.flow_left_in"/>
-    <coupling from="c1.flow_right_in" to="j.flow_left_out"/>
-
-    <coupling from="c2.flow_left_out" to="sink1.flow_in"/>
-    <coupling from="c2.flow_left_in" to="sink1.flow_out"/>
-    <coupling from="c2.flow_right_out" to="j.flow_right_in"/>
-    <coupling from="c2.flow_right_in" to="j.flow_right_out"/>
-
-    <coupling from="c3.flow_left_out" to="sink2.flow_in"/>
-    <coupling from="c3.flow_left_in" to="sink2.flow_out"/>
-    <coupling from="c3.flow_right_out" to="j.flow_top_in"/>
-    <coupling from="c3.flow_right_in" to="j.flow_top_out"/>
-  </topology>
-</model>
diff --git a/python/libmumbl/xmml/examples/isr_meta.xml b/python/libmumbl/xmml/examples/isr_meta.xml
deleted file mode 100644
index 2672520a3677cce8dd104371f8a4facc83816503..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/examples/isr_meta.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-<?xml version="1.0"?>
-<metadata>
-  <datatype xmlns="http://www.mapper-project.eu/xmml" id="latticeInt" size_estimate="x*y*sizeof(int)"/>
-  <datatype xmlns="http://www.mapper-project.eu/xmml" id="latticeDouble" size_estimate="x*y*sizeof(double)"/>
-  <datatype xmlns="http://www.mapper-project.eu/xmml" id="agentLocations" size_estimate="4*n*sizeof(double)"/>
-  <datatype xmlns="http://www.mapper-project.eu/xmml" id="agentDouble" size_estimate="n*sizeof(double)"/>
-  <datatype xmlns="http://www.mapper-project.eu/xmml" id="agentFull" size_estimate="4*n*sizeof(double)+n*sizeof(double)"/>
-  <datatype xmlns="http://www.mapper-project.eu/xmml" id="latticeMetadata" size_estimate="2*sizeof(int)+4*sizeof(double)"/>
-  <datatype xmlns="http://www.mapper-project.eu/xmml" id="double" size_estimate="sizeof(double)"/>
-  
-  <filter xmlns="http://www.mapper-project.eu/xmml" type="converter" id="latticeDouble2agents" datatype_in="latticeDouble" datatype_out="agentDouble"/>
-  <filter xmlns="http://www.mapper-project.eu/xmml" type="converter" id="agents2latticeInt" datatype_in="agentLocations" datatype_out="latticeInt"/>
-</metadata>
diff --git a/python/libmumbl/xmml/examples/isr_param.xml b/python/libmumbl/xmml/examples/isr_param.xml
deleted file mode 100644
index 7ad79430ea0b4028876cb4c0d806504fc3752654..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/examples/isr_param.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<!--
-    Document   : isr_param.xml
-    Created on : December 13, 2011, 1:46 PM
-    Author     : Joris Borgdorff
-    Description:
-        Simple parameter file.
--->
-
-<parameters  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
-   xmlns:xmml='http://www.mapper-project.eu/xmml'
-   xmlns='http://www.mapper-project.eu/xmml/param'
-   id="ISR2D" name="Basic parameters" xmml_version="0.4">
-	<parameterGroup submodel="DD">
-		<xmml:param id="dd" value="dd"/>
-	</parameterGroup>
-	
-	<parameterGroup submodel="BF">
-	</parameterGroup>
-</parameters>
diff --git a/python/libmumbl/xmml/examples/isr_xmml.xml b/python/libmumbl/xmml/examples/isr_xmml.xml
deleted file mode 100644
index 0a74a9f373505bf9eb064360e76338db3f78a034..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/examples/isr_xmml.xml
+++ /dev/null
@@ -1,149 +0,0 @@
-<?xml version="1.0" standalone="no"?>
-<model id="ISR2D" name="In-stent restenosis 2D" xmml_version="0.4" xmlns="http://www.mapper-project.eu/xmml" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:mad="http://www.mapper-project.eu/mad">
-  <description>
-    A model of the process that occurs in the artery after stenting.
-  </description>
-  
-  <definitions>
-    <xi:include href="isr_meta.xml#xpointer(/metadata/*)"/>
-
-    <terminal id="agentreader" type="source">
-        <ports>
-            <out id="data" datatype="agentFull"/>
-        </ports>
-    </terminal>
-    <terminal id="latticewriter" type="sink">
-        <ports>
-            <out id="data" datatype="latticeInt"/>
-        </ports>
-    </terminal>
-
-    <mapper id="agents2lattice" type="fan-out">
-	<description>
-           Maps a number of agents or particles to a lattice.
-	</description>
-        <ports>
-          <in id="cell_info" datatype="agentFull"/>
-          <out id="latticeBF" datatype="latticeInt"/>
-          <out id="latticeDD" datatype="latticeInt"/>
-          <out id="cell_positions" datatype="agentLocations"/>
-        </ports>
-    </mapper>
-    <mapper id="latticeBF2agents" type="fan-in">
-        <ports>
-          <in id="cell_positions" datatype="agentLocations"/>
-          <in id="latticeBF" datatype="latticeDouble"/>
-          <out id="cell_bf" datatype="agentDouble"/>
-        </ports>
-    </mapper>
-    <mapper id="latticeDD2agents" type="fan-in">
-        <ports>
-          <in id="cell_positions" datatype="agentLocations"/>
-          <in id="latticeDD" datatype="latticeDouble"/>
-          <out id="cell_dd" datatype="agentDouble"/>
-        </ports>
-    </mapper>
-    
-    <filter id="coarsenGrid" type="reduction" dimension="spatial"/>
-  
-    <submodel id="INIT" name="Initial cell conditions">
-      <timescale delta="1E-3" total="1E-1"/>
-      <spacescale delta="1E-5" total="1E-3"/>
-      <spacescale delta="1E-5" total="1E-3"/>
-
-      <ports>
-        <out id="cells" operator="Of" datatype="agentLocations"/>
-      </ports>
-      <implementation>
-        <interpreter name="muscle2"/>
-        <code language="Java" part="header">
-            import isr3d.data.AgentLocations;
-        </code>
-        <code language="Java" part="Of">
-            int dataSize = getIntProperty("datasize");
-            AgentLocations data = AgentLocations.createRandom(dataSize);
-            out("cells").send(data);
-        </code>
-      </implementation>
-    </submodel>
-  
-    <submodel id="BF" name="Blood flow" stateful="optional" class="nl.computationalscience.uva.isr3d.kernel.bf.BFController">
-	<description>
-           Calculates the blood flow within a lattice.
-
-           At the moment BF keeps a state to ease subsequent flow calculations.
-	</description>
-      <timescale delta="1E-7" total="1"/>
-      <spacescale delta="1E-5" total="1E-3"/>
-      <spacescale delta="1E-5" total="1E-3"/>
-
-      <ports>
-        <in id="state_start" operator="finit" type="state"/>
-        <in id="boundary" operator="finit" datatype="latticeInt"/>
-        <out id="shear_stress" operator="Of" datatype="latticeDouble"/>
-        <out id="state_end" operator="Of" type="state"/>
-      </ports>
-      
-      <implementation size="2 MB" runtime="30 min" memory="30 MB" cores="1024">
-        <platform arch="x84-64" os="linux"/>
-        <library name="intel-fortran-11.1"/>
-        <library name="mpich2-1.4"/>
-      </implementation>
-    </submodel>
-  
-    <submodel id="SMC" name="Smooth muscle cells">
-      <timescale delta="1E3" total="1E7"/>
-      <spacescale delta="1E-5" total="1E-3"/>
-      <spacescale delta="1E-5" total="1E-3"/>
-      <param id="n" value="1000"/>
-    
-      <ports>
-        <in id="initial_positions" operator="finit" datatype="agentLocations"/>
-        <in id="shear_stress" operator="S" datatype="agentDouble"/>
-        <in id="drug_concentration" operator="S" datatype="agentDouble"/>
-        <out id="cell_positions" operator="Oi" datatype="agentFull"/>
-      </ports>
-    </submodel>
-  
-    <submodel id="DD" name="Drug diffusion">
-      <timescale delta="1E3" total="1E7"/>
-      <spacescale delta="1.2E-5" total="1E-3"/>
-      <spacescale delta="1.2E-5" total="1E-3"/>
-    
-      <ports>
-        <in id="boundary" operator="finit" datatype="latticeInt"/>
-        <out id="drug_concentration" operator="Of" datatype="latticeDouble"/>
-      </ports>
-    </submodel>
-  </definitions>
-  
-  <topology>
-    <instance id="ic" submodel="INIT" domain="artery"><extra>
-      <mad:portMapping><mad:portMapping id="005" name="inDistance"/>
-        <mad:portMapping id="006" name="outDistance"/></mad:portMapping>
-    <mad:position x="431" y="587"/>
-    </extra></instance>
-    <instance id="bf" submodel="BF" domain="artery.blood"/>
-    <instance id="dd" submodel="DD" domain="artery.tissue"/>
-    <instance id="smc" submodel="SMC" domain="artery.tissue"/>
-
-    <instance mapper="latticeDD2agents" domain="artery.tissue"/>
-    <instance mapper="latticeBF2agents" domain="artery"/>
-    <instance mapper="agents2lattice" domain="artery"/>
-    
-    <instance terminal="agentreader"/>
-    
-    <coupling mad:fromPortId="005" from="ic.cells" to="smc.initial_positions" size="10 MB"/>
-    <coupling from="smc.cell_positions" to="agents2lattice.cell_info"/>
-    <coupling from="agents2lattice.latticeBF" to="bf.boundary"/>
-    <coupling from="agents2lattice.latticeDD" to="dd.boundary">
-      <apply filter="coarsenGrid" factor="1.2"/>
-    </coupling>
-    <coupling from="agents2lattice.cell_positions" to="latticeDD2agents.cell_positions"/>
-    <coupling from="agents2lattice.cell_positions" to="latticeBF2agents.cell_positions"/>
-    <coupling from="dd.drug_concentration" to="latticeDD2agents.latticeDD"/>
-    <coupling from="latticeDD2agents.cell_dd" to="smc.drug_concentration"/>
-    <coupling from="bf.shear_stress" to="latticeBF2agents.latticeBF"/>
-    <coupling from="latticeBF2agents.cell_bf" to="smc.drug_concentration"/>
-  </topology>
-</model>
diff --git a/python/libmumbl/xmml/external/mad.xsd b/python/libmumbl/xmml/external/mad.xsd
deleted file mode 100644
index a9404cf2ba8095f3123d82c1c8d723812e1cc5fb..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/external/mad.xsd
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<xs:schema targetNamespace="http://www.mapper-project.eu/mad" xmlns:mad="http://www.mapper-project.eu/mad" xmlns:xs="http://www.w3.org/2001/XMLSchema">
-
-  <xs:element name="portMapping" type="mad:portMapper"/>
-
-  <xs:element name="position" type="mad:position"/>
-  
-  <xs:complexType name="portMapper">
-    <xs:sequence/>
-    <xs:attribute name="id" type="xs:string"/>
-    <xs:attribute name="name" type="xs:string"/>
-  </xs:complexType>
-
-  <xs:complexType name="position">
-    <xs:sequence/>
-    <xs:attribute name="x" type="xs:int" use="required"/>
-    <xs:attribute name="y" type="xs:int" use="required"/>
-  </xs:complexType>
-
-  <xs:attribute name="connectionId" type="xs:string"/>
-
-  <xs:attribute name="fromPortId" type="xs:string"/>
-
-  <xs:attribute name="toPortId" type="xs:string"/>
-</xs:schema>
\ No newline at end of file
diff --git a/python/libmumbl/xmml/external/xs3p-1/CHANGES b/python/libmumbl/xmml/external/xs3p-1/CHANGES
deleted file mode 100644
index 18b7a50ad0bf86fc57121acb6b1359f1f498e90e..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/external/xs3p-1/CHANGES
+++ /dev/null
@@ -1,18 +0,0 @@
-xs3p was originally developed by DSTC and was availabe
-through their website at http://titanium.dstc.edu.au/xml/xs3p/
-
-Since the demise of this organization, we at FiForms Solutions
-have decided to host xs3p, since we have been using it in
-documenting the XML used in FiForms. The stylesheet has been
-modified to point to the new xs3p home here at FiForms, while
-still retaining the old (dead) link to the dstc website. The
-xs3p home is http://xml.fiforms.org/xs3p/
-
-Version 1.1.4
-Moved the README.txt documentation online
-Added xs3p_links.xsl file
-
-Version 1.1.5
-Fixed a bug in xs3p's handling of recursive groups
-Thanks to Martin Beran from Trusted Network Solutions 
-for submitting the patch.
diff --git a/python/libmumbl/xmml/external/xs3p-1/LICENSE.html b/python/libmumbl/xmml/external/xs3p-1/LICENSE.html
deleted file mode 100644
index 263e6356161b549046ec23f2b668fdb5bdde61cb..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/external/xs3p-1/LICENSE.html
+++ /dev/null
@@ -1,519 +0,0 @@
-<html>
-
-<head>
-  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
-  <title>DSTC Public License</title>
-</head>
-
-<body>
-<h1>DSTC Public License (DPL)</h1>
-<p>Version 1.1</p>
-
-<h2>1. Definitions.</h2>
-
-<p><b>1.0.1. "Commercial Use" </b>means distribution or otherwise making
-the Covered Code available to a third party.</p>
-
-<p><b>1.1.  "Contributor"</b> means each entity that creates or
-contributes to the creation of Modifications.</p>
-
-<p><b>1.2.  "Contributor Version"</b> means the combination of the
-Original Code, prior Modifications used by a Contributor, and the
-Modifications made by that particular Contributor.</p>
-
-<p><b>1.3.  "Covered Code"</b> means the Original Code or
-Modifications or the combination of the Original Code and Modifications,
-in each case including portions thereof<b>.</b></p>
-
-<p><b>1.4.  "Electronic Distribution Mechanism"</b> means a mechanism
-generally accepted in the software development community for the
-electronic transfer of data.</p>
-
-<p><b>1.5.  "Executable"</b> means Covered Code in any form other than
-Source Code.</p>
-
-<p><b>1.6.  "Initial Developer"</b> means the individual or entity
-identified as the Initial Developer in the Source Code notice required
-by <b>Exhibit A</b>.</p>
-
-<p><b>1.7.  "Larger Work"</b> means a work which combines Covered Code
-or portions thereof with code not governed by the terms of this
-License.</p>
-
-<p><b>1.8.  "License"</b> means this document.</p>
-
-<p><b>1.8.1.  "Licensable"</b> means having the right to grant, to the
-maximum extent possible, whether at the time of the initial grant or
-subsequently acquired, any and all of the rights conveyed herein.</p>
-
-<p><b>1.9.  "Modifications"</b> means any addition to or deletion from
-the substance or structure of either the Original Code or any previous
-Modifications. When Covered Code is released as a series of files, a
-Modification is:</p>
-
-<ul>
-<li><b>A.</b> Any addition to or
-deletion from the contents of a file containing Original Code or previous
-Modifications.</li>
-
-<li><b>B.</b> Any new file that contains any part of the Original Code
-or previous Modifications.</li>
-</ul>
-
-
-<p><b>1.10. "Original Code"</b>
-means Source Code of computer software code which is described in the Source
-Code notice required by <b>Exhibit A</b> as Original Code, and which, at the
-time of its release under this License is not already Covered Code governed by
-this License.</p>
-
-<p><b>1.10.1.  "Patent Claims"</b> means any patent claim(s), now owned
-or hereafter acquired, including without limitation, method, process,
-and apparatus claims, in any patent Licensable by grantor.</p>
-
-<p><b>1.11.  "Source Code"</b> means the preferred form of the Covered
-Code for making modifications to it, including all modules it contains,
-plus any associated interface definition files, scripts used to control
-compilation and installation of an Executable, or source code
-differential comparisons against either the Original Code or another
-well known, available Covered Code of the Contributor's choice. The
-Source Code can be in a compressed or archival form, provided the
-appropriate decompression or de-archiving software is widely available
-for no charge.</p>
-
-<p><b>1.12.  "You" (or "Your")</b> means an individual or a legal
-entity exercising rights under, and complying with all of the terms of,
-this License or a future version of this License issued under Section
-6.1. For legal entities, "You" includes any entity which controls, is
-controlled by, or is under common control with You. For purposes of this
-definition, "control" means (a) the power, direct or indirect, to cause
-the direction or management of such entity, whether by contract or
-otherwise, or (b) ownership of more than fifty percent (50%) of the
-outstanding shares or beneficial ownership of such
-entity.</p>
-
-
-<h2>2. Source Code License.</h2>
-
-<h3>2.1. The Initial Developer Grant.</h3> 
-
-<p>The Initial Developer hereby grants You a world-wide, royalty-free,
-non-exclusive license, subject to third party intellectual property
-claims:</p>
-
-<p><b>(a)</b> under intellectual property rights (other than patent or
-trademark) Licensable by Initial Developer to use, reproduce, modify,
-display, perform, sublicense and distribute the Original Code (or
-portions thereof) with or without Modifications, and/or as part of a
-Larger Work; and</p>
-
-<p><b>(b)</b> under Patents Claims infringed by the making, using or
-selling of Original Code, to make, have made, use, practice, sell, and
-offer for sale, and/or otherwise dispose of the Original Code (or
-portions thereof).</p>
-
-<p><b>(c) </b>the licenses granted in this Section 2.1(a) and (b) are
-effective on the date Initial Developer first distributes Original Code
-under the terms of this License.</p>
-
-<p><b>(d) </b>Notwithstanding Section 2.1(b) above, no patent license is
-granted: 1) for code that You delete from the Original Code; 2) separate
-from the Original Code; or 3) for infringements caused by: i) the
-modification of the Original Code or ii) the combination of the Original
-Code with other software or devices.</p>
-
-<h3>2.2. Contributor Grant.</h3>
-
-<p>Subject to third party intellectual property claims, each Contributor
-hereby grants You a world-wide, royalty-free, non-exclusive license</p>
-
-<p><b>(a)</b> under intellectual property rights (other than patent or
-trademark) Licensable by Contributor, to use, reproduce, modify,
-display, perform, sublicense and distribute the Modifications created by
-such Contributor (or portions thereof) either on an unmodified basis,
-with other Modifications, as Covered Code and/or as part of a Larger
-Work; and</p>
-
-<p><b>(b)</b> under Patent Claims infringed by the making, using, or
-selling of Modifications made by that Contributor either alone and/or in
-combination with its Contributor Version (or portions of such
-combination), to make, use, sell, offer for sale, have made, and/or
-otherwise dispose of: 1) Modifications made by that Contributor (or
-portions thereof); and 2) the combination of Modifications made by that
-Contributor with its Contributor Version (or portions of such
-combination).</p>
-
-<p><b>(c) </b>the licenses granted in Sections 2.2(a) and 2.2(b) are
-effective on the date Contributor first makes Commercial Use of the
-Covered Code.</p>
-
-<p><b>(d)</b> Notwithstanding Section 2.2(b) above, no patent
-license is granted: 1) for any code that Contributor has deleted from
-the Contributor Version; 2) separate from the Contributor Version; 3)
-for infringements caused by: i) third party modifications of Contributor
-Version or ii) the combination of Modifications made by that Contributor
-with other software (except as part of the Contributor Version) or other
-devices; or 4) under Patent Claims infringed by Covered Code in the
-absence of Modifications made by that Contributor.</p>
-
-
-<h2>3. Distribution Obligations</h2>
-
-<h3>3.1. Application of License.</h3>
-
-<p>The Modifications which You create or to which You contribute are
-governed by the terms of this License, including without limitation
-Section <b>2.2</b>. The Source Code version of Covered Code may be
-distributed only under the terms of this License or a future version of
-this License released under Section <b>6.1</b>, and You must include a
-copy of this License with every copy of the Source Code You
-distribute. You may not offer or impose any terms on any Source Code
-version that alters or restricts the applicable version of this License
-or the recipients' rights hereunder. However, You may include an
-additional document offering the additional rights described in Section
-<b>3.5</b>.</p>
-
-<h3>3.2. Availability of Source Code.</h3>
-
-<p>Any Modification which You create or to which You contribute must be
-made available in Source Code form under the terms of this License
-either on the same media as an Executable version or via an accepted
-Electronic Distribution Mechanism to anyone to whom you made an
-Executable version available; and if made available via Electronic
-Distribution Mechanism, must remain available for at least twelve (12)
-months after the date it initially became available, or at least six (6)
-months after a subsequent version of that particular Modification has
-been made available to such recipients. You are responsible for ensuring
-that the Source Code version remains available even if the Electronic
-Distribution Mechanism is maintained by a third party.</p>
-
-<h3>3.3. Description of Modifications.</h3>
-
-<p>You must cause all Covered Code to which You contribute to contain a
-file documenting the changes You made to create that Covered Code and
-the date of any change. You must include a prominent statement that the
-Modification is derived, directly or indirectly, from Original Code
-provided by the Initial Developer and including the name of the Initial
-Developer in (a) the Source Code, and (b) in any notice in an Executable
-version or related documentation in which You describe the origin or
-ownership of the Covered Code.</p>
-
-<h3>3.4. Intellectual Property Matters</h3>
-
-<h4>(a) Third Party Claims.</h4>
-
-<p>If Contributor has knowledge that a license under a third party's
-intellectual property rights is required to exercise the rights granted
-by such Contributor under Sections 2.1 or 2.2, Contributor must include
-a text file with the Source Code distribution titled "LEGAL" which
-describes the claim and the party making the claim in sufficient detail
-that a recipient will know whom to contact. If Contributor obtains such
-knowledge after the Modification is made available as described in
-Section 3.2, Contributor shall promptly modify the LEGAL file in all
-copies Contributor makes available thereafter and shall take other steps
-(such as notifying appropriate mailing lists or newsgroups) reasonably
-calculated to inform those who received the Covered Code that new
-knowledge has been obtained.</p>
-
-<h4>(b) Contributor APIs.</h4>
-
-<p>If Contributor's Modifications include an application programming
-interface and Contributor has knowledge of patent licenses which are
-reasonably necessary to implement that API, Contributor must also
-include this information in the LEGAL file.</p>
-
-<h4>(c) Representations.</h4>
-
-<p>Contributor represents that, except
-as disclosed pursuant to Section 3.4(a) above, Contributor believes that
-Contributor's Modifications are Contributor's original creation(s)
-and/or Contributor has sufficient rights to grant the rights conveyed by
-this License.</p>
-
-<h3>3.5.  Required Notices.</h3> 
-
-<p>You must duplicate the notice in <b>Exhibit A</b> in each file of the
-Source Code. If it is not possible to put such notice in a
-particular Source Code file due to its structure, then You must include
-such notice in a location (such as a relevant directory) where a user
-would be likely to look for such a notice. If You created one or
-more Modification(s) You may add your name as a Contributor to the
-notice described in <b>Exhibit A</b>. You must also duplicate this
-License in any documentation for the Source Code where You describe
-recipients' rights or ownership rights relating to Covered Code.
-You may choose to offer, and to charge a fee for, warranty, support,
-indemnity or liability obligations to one or more recipients of Covered
-Code. However, You may do so only on Your own behalf, and not on behalf
-of the Initial Developer or any Contributor. You must make it absolutely
-clear than any such warranty, support, indemnity or liability obligation
-is offered by You alone, and You hereby agree to indemnify the Initial
-Developer and every Contributor for any liability incurred by the
-Initial Developer or such Contributor as a result of warranty, support,
-indemnity or liability terms You offer.</p>
-
-<h3>3.6.  Distribution of Executable Versions.</h3>
-
-<p>You may distribute Covered Code in Executable form only if the
-requirements of Section <b>3.1-3.5</b> have been met for that Covered
-Code, and if You include a notice stating that the Source Code version
-of the Covered Code is available under the terms of this License,
-including a description of how and where You have fulfilled the
-obligations of Section <b>3.2</b>. The notice must be conspicuously
-included in any notice in an Executable version, related documentation
-or collateral in which You describe recipients' rights relating to the
-Covered Code. You may distribute the Executable version of Covered Code
-or ownership rights under a license of Your choice, which may contain
-terms different from this License, provided that You are in compliance
-with the terms of this License and that the license for the Executable
-version does not attempt to limit or alter the recipient's rights in the
-Source Code version from the rights set forth in this License. If You
-distribute the Executable version under a different license You must
-make it absolutely clear that any terms which differ from this License
-are offered by You alone, not by the Initial Developer or any
-Contributor. You hereby agree to indemnify the Initial Developer and
-every Contributor for any liability incurred by the Initial Developer or
-such Contributor as a result of any such terms You offer.</p>
-
-<h3>3.7. Larger Works.</h3>
-
-<p>You may create a Larger Work by combining Covered Code with other code not
-governed by the terms of this License and distribute the Larger Work as a
-single product. In such a case, You must make sure the requirements of this
-License are fulfilled for the Covered Code.</p>
-
-<h2>4. Inability to Comply Due to Statute or Regulation.</h2>
-
-<p>If it is impossible for You to comply with any of the terms of this
-License with respect to some or all of the Covered Code due to statute,
-judicial order, or regulation then You must: (a) comply with the terms
-of this License to the maximum extent possible; and (b) describe the
-limitations and the code they affect. Such description must be included
-in the LEGAL file described in Section <b>3.4</b> and must be included
-with all distributions of the Source Code. Except to the extent
-prohibited by statute or regulation, such description must be
-sufficiently detailed for a recipient of ordinary skill to be able to
-understand it.</p>
-
-
-<h2>5. Application of this License.</h2>
-
-<p>This License applies to code to which the Initial Developer has
-attached the notice in <b>Exhibit A</b> and to related Covered Code.</p>
-
-
-<h2>6. Versions of the License.</h2>
-
-<h3>6.1. New Versions</h3>
-
-<p>The Distributed Systems Technology Centre ("DSTC") may publish
-revised and/or new versions of the License from time to time. Each
-version will be given a distinguishing version number.</p>
-
-<h3>6.2.  Effect of New Versions</h3>
-
-<p>Once Covered Code has been published under a particular version of
-the License, You may always continue to use it under the terms of that
-version. You may also choose to use such Covered Code under the terms of
-any subsequent version of the License published by DSTC. No one other
-than DSTC has the right to modify the terms applicable to Covered Code
-created under this License.</p>
-
-<h3>6.3.  Derivative Works</h3>
-
-<p>If You create or use a modified version of this License (which you
-may only do in order to apply it to code which is not already Covered
-Code governed by this License), You must (a) rename Your license so that
-the phrases "DSTC", "DPL" or any confusingly similar phrase do not
-appear in your license (except to note that your license differs from
-this License) and (b) otherwise make it clear that Your version of the
-license contains terms which differ from the DSTC Public
-License. (Filling in the name of the Initial Developer, Original Code or
-Contributor in the notice described in <b>Exhibit A</b> shall not of
-themselves be deemed to be modifications of this License.)</p>
-
-<h2>7. Disclaimer of Warranty.</h2>
-
-<p>COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS,
-WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
-WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF DEFECTS,
-MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE
-RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE IS WITH
-YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT
-THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY
-NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY
-CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED
-CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.</p>
-
-
-<h2>8. Termination.</h2>
-
-<p><b>8.1. </b>This License and the rights granted hereunder will
-terminate automatically if You fail to comply with terms herein and fail
-to cure such breach within 30 days of becoming aware of the breach. All
-sublicenses to the Covered Code which are properly granted shall survive
-any termination of this License. Provisions which, by their nature, must
-remain in effect beyond the termination of this License shall
-survive.</p>
-
-<p><b>8.2.
-</b>If You initiate
-litigation by asserting a patent infringement claim (excluding declatory
-judgment actions) against Initial Developer or a Contributor (the Initial
-Developer or Contributor against whom You file such action is referred to as
-'Participant') alleging that:</p>
-
-<p><b>(a) </b>such Participant's Contributor Version directly or
-indirectly infringes any patent, then any and all rights granted by such
-Participant to You under Sections 2.1 and/or 2.2 of this License shall,
-upon 60 days notice from Participant terminate prospectively, unless if
-within 60 days after receipt of notice You either: (i) agree in writing
-to pay Participant a mutually agreeable reasonable royalty for Your past
-and future use of Modifications made by such Participant, or (ii)
-withdraw Your litigation claim with respect to the Contributor Version
-against such Participant. If within 60 days of notice, a reasonable
-royalty and payment arrangement are not mutually agreed upon in writing
-by the parties or the litigation claim is not withdrawn, the rights
-granted by Participant to You under Sections 2.1 and/or 2.2
-automatically terminate at the expiration of the 60 day notice period
-specified above.</p>
-
-<p><b>(b)</b> any software, hardware, or device, other than such
-Participant's Contributor Version, directly or indirectly infringes any
-patent, then any rights granted to You by such Participant under
-Sections 2.1(b) and 2.2(b) are revoked effective as of the date You
-first made, used, sold, distributed, or had made, Modifications made by
-that Participant.</p>
-
-<p><b>8.3.
-</b>If You assert a patent
-infringement claim against Participant alleging that such Participant's
-Contributor Version directly or indirectly infringes any patent where such
-claim is resolved (such as by license or settlement) prior to the initiation of
-patent infringement litigation, then the reasonable value of the licenses
-granted by such Participant under Sections 2.1 or 2.2 shall be taken into
-account in determining the amount or value of any payment or license.</p>
-
-<p><b>8.4.</b> In the event of termination under
-Sections 8.1 or 8.2 above, all end user license agreements (excluding
-distributors and resellers) which have been validly granted by You or any
-distributor hereunder prior to termination shall survive termination.</p>
-
-<h2>9. Limitation of Liability.</h2>
-
-<p>UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT
-(INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL
-DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE, OR
-ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR ANY
-INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER
-INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK
-STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER
-COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN
-INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF
-LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY
-RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT APPLICABLE LAW
-PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION
-OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION
-AND LIMITATION MAY NOT APPLY TO YOU.</p>
-
-<h2>10. U.S. Government End Users.</h2>
-
-<p>The Covered Code is a "commercial item," as that term is defined in
-48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial computer
-software" and "commercial computer software documentation," as such
-terms are used in 48 C.F.R. 12.212 (Sept.  1995). Consistent with 48
-C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995),
-all U.S. Government End Users acquire Covered Code with only those
-rights set forth herein.</p>
-
-
-<h2>11. Miscellaneous.</h2>
-
-<p>This License represents the complete agreement concerning subject
-matter hereof. If any provision of this License is held to be
-unenforceable, such provision shall be reformed only to the extent
-necessary to make it enforceable. This License shall be governed by
-Queensland, Australia law provisions (except to the extent applicable
-law, if any, provides otherwise), excluding its conflict-of-law
-provisions. With respect to disputes in which at least one party is a
-citizen of, or an entity chartered or registered to do business in
-Australia, any litigation relating to this License shall be subject to
-the jurisdiction of Australian Courts, with the losing party responsible
-for costs, including without limitation, court costs and reasonable
-attorneys' fees and expenses. The application of the United Nations
-Convention on Contracts for the International Sale of Goods is expressly
-excluded. Any law or regulation which provides that the language of a
-contract shall be construed against the drafter shall not apply to this
-License.</p>
-
-
-<h2>12. Responsibility for Claims.</h2>
-
-<p>As between Initial Developer and the Contributors, each party is
-responsible for claims and damages arising, directly or indirectly, out
-of its utilization of rights under this License and You agree to work
-with Initial Developer and Contributors to distribute such
-responsibility on an equitable basis. Nothing herein is intended or
-shall be deemed to constitute any admission of liability.</p>
-
-
-<h2>13. Multiple-licensed Code.</h2>
-
-<p>Initial Developer may designate portions of the Covered Code as
-"Multiple-Licensed". "Multiple-Licensed" means that the Initial
-Developer permits you to utilize portions of the Covered Code under Your
-choice of the DPL or the alternative licenses, if any, specified by the
-Initial Developer in the file described in Exhibit A.</p>
-
-
-<h2>14. High Risk Activities.</h2>
-
-<p>The Software is not fault-tolerant and is not designed, manufactured
-or intended for use or resale as on-line control equipment in hazardous
-environments requiring fail-safe performance, such as in the operation
-of nuclear facilities, aircraft navigation or communication systems, air
-traffic control, direct life support machines, or weapons systems, in
-which the failure of the Software could lead directly to death, personal
-injury, or severe physical or environmental damage ("High Risk
-Activities").</p>
-
-
-<h2>EXHIBIT A - DSTC Public License.</h2>
-
-<p>The contents of this file are subject to the DSTC Public License
-Version 1.1 (the 'License'); you may not use this file except in
-compliance with the License.</p>
-
-<p>Software distributed under the License is distributed on an 'AS IS'
-basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-License for the specific language governing rights and limitations under
-the License.</p>
-
-<p>The Original Code is ______________________________________.</p>
-
-<p>The Initial Developer of the Original Code is
-________________________. Portions created by ______________________ are
-Copyright &copy; _____________________________.  All Rights
-Reserved.</p>
-
-<p>Contributor(s): ______________________________________.</p>
-
-<p>Alternatively, the contents of this file may be used under the terms
-of the _____ license (the "[___] License"), in which case the provisions
-of [______] License are applicable instead of those above.  If you wish
-to allow use of your version of this file only under the terms of the
-[____] License and not to allow others to use your version of this file
-under the DPL, indicate your decision by deleting the provisions above
-and replace them with the notice and other provisions required by the
-[___] License.  If you do not delete the provisions above, a recipient
-may use your version of this file under either the DPL or the [___]
-License.'</p>
-
-<p>[NOTE: The text of this Exhibit A may differ slightly from the text
-of the notices in the Source Code files of the Original Code. You should
-use the text of this Exhibit A rather than the text found in the
-Original Code Source Code for Your Modifications.]</p>
-
-</body>
-
-</html>
-
diff --git a/python/libmumbl/xmml/external/xs3p-1/README.txt b/python/libmumbl/xmml/external/xs3p-1/README.txt
deleted file mode 100644
index 140ec7489108ec0146503b2636808274b8235bb5..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/external/xs3p-1/README.txt
+++ /dev/null
@@ -1,29 +0,0 @@
-xs3p - Version 1.1.5
-====================
-
-xs3p is a schema documentation generator. It is an XSLT stylesheet 
-that will output an XHTML document from an XSD schema. Aside from 
-using as much W3C acronyms as possible, the tool makes schemas more 
-readable by providing a view of schema components' constraints as a 
-sample XML instance, links that allow the user to jump to the 
-documentation of schema components that are referenced, and a whole 
-host of neat features. However, most important of all, it makes your  
-schemas look 'pretty in pink'.
-
-The latest documentation for xs3p is maintained on the FiForms
-documentation wiki at:
-
-http://wiki.fiforms.org/index.php/Xs3p
-
-Please refer to this site for complete documentation and usage information.
-
-You can always download the latest version of xs3p from the XS3P
-website:
-
-http://xml.fiforms.org/xs3p/
-
-or for SourceForge: https://sourceforge.net/projects/xs3p/
-
-In order to use xs3p, you will need an XSLT processor, such as
-XALAN, Saxon, MSXML, or xsltproc. 
-
diff --git a/python/libmumbl/xmml/external/xs3p-1/examples/XMLSchema.xsd b/python/libmumbl/xmml/external/xs3p-1/examples/XMLSchema.xsd
deleted file mode 100644
index b8229fd94aed944d7e2f5935faf37cd96ef4106a..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/external/xs3p-1/examples/XMLSchema.xsd
+++ /dev/null
@@ -1,2492 +0,0 @@
-<?xml version='1.0' encoding='UTF-8'?>
-<!-- XML Schema schema for XML Schemas: Part 1: Structures -->
-<!-- Note this schema is NOT the normative structures schema. -->
-<!-- The prose copy in the structures REC is the normative -->
-<!-- version (which shouldn't differ from this one except for -->
-<!-- this comment and entity expansions, but just in case -->
-<!--
-<!DOCTYPE xs:schema PUBLIC "-//W3C//DTD XMLSCHEMA 200102//EN" "http://www.w3.org/2001/XMLSchema.dtd" [
--->
-
-<!-- provide ID type information even for parsers which only read the
-	  internal subset -->
-<!--
-<!ATTLIST xs:schema			  id	ID  #IMPLIED>
-<!ATTLIST xs:complexType	  id	ID  #IMPLIED>
-<!ATTLIST xs:complexContent  id	ID  #IMPLIED>
-<!ATTLIST xs:simpleContent   id	ID  #IMPLIED>
-<!ATTLIST xs:extension		  id	ID  #IMPLIED>
-<!ATTLIST xs:element 		  id	ID  #IMPLIED>
-<!ATTLIST xs:group			  id	ID  #IMPLIED>
-<!ATTLIST xs:all				  id	ID  #IMPLIED>
-<!ATTLIST xs:choice			  id	ID  #IMPLIED>
-<!ATTLIST xs:sequence		  id	ID  #IMPLIED>
-<!ATTLIST xs:any				  id	ID  #IMPLIED>
-<!ATTLIST xs:anyAttribute	  id	ID  #IMPLIED>
-<!ATTLIST xs:attribute		  id	ID  #IMPLIED>
-<!ATTLIST xs:attributeGroup  id	ID  #IMPLIED>
-<!ATTLIST xs:unique			  id	ID  #IMPLIED>
-<!ATTLIST xs:key				  id	ID  #IMPLIED>
-<!ATTLIST xs:keyref			  id	ID  #IMPLIED>
-<!ATTLIST xs:selector		  id	ID  #IMPLIED>
-<!ATTLIST xs:field			  id	ID  #IMPLIED>
-<!ATTLIST xs:include 		  id	ID  #IMPLIED>
-<!ATTLIST xs:import			  id	ID  #IMPLIED>
-<!ATTLIST xs:redefine		  id	ID  #IMPLIED>
-<!ATTLIST xs:notation		  id	ID  #IMPLIED>
--->
-<!--
-	  keep this schema XML1.0 DTD valid
-  -->
-<!--
-		  <!ENTITY % schemaAttrs 'xmlns:hfp CDATA #IMPLIED'>
-
-		  <!ELEMENT hfp:hasFacet EMPTY>
-		  <!ATTLIST hfp:hasFacet
-					 name NMTOKEN #REQUIRED>
-
-		  <!ELEMENT hfp:hasProperty EMPTY>
-		  <!ATTLIST hfp:hasProperty
-					 name NMTOKEN #REQUIRED
-					 value CDATA #REQUIRED>
--->
-<!--
-		  Make sure that processors that do not read the external
-		  subset will know about the various IDs we declare
-  -->
-<!--
-		  <!ATTLIST xs:simpleType id ID #IMPLIED>
-		  <!ATTLIST xs:maxExclusive id ID #IMPLIED>
-		  <!ATTLIST xs:minExclusive id ID #IMPLIED>
-		  <!ATTLIST xs:maxInclusive id ID #IMPLIED>
-		  <!ATTLIST xs:minInclusive id ID #IMPLIED>
-		  <!ATTLIST xs:totalDigits id ID #IMPLIED>
-		  <!ATTLIST xs:fractionDigits id ID #IMPLIED>
-		  <!ATTLIST xs:length id ID #IMPLIED>
-		  <!ATTLIST xs:minLength id ID #IMPLIED>
-		  <!ATTLIST xs:maxLength id ID #IMPLIED>
-		  <!ATTLIST xs:enumeration id ID #IMPLIED>
-		  <!ATTLIST xs:pattern id ID #IMPLIED>
-		  <!ATTLIST xs:appinfo id ID #IMPLIED>
-		  <!ATTLIST xs:documentation id ID #IMPLIED>
-		  <!ATTLIST xs:list id ID #IMPLIED>
-		  <!ATTLIST xs:union id ID #IMPLIED>
-		  ]>
--->
-<xs:schema targetNamespace="http://www.w3.org/2001/XMLSchema" blockDefault="#all" elementFormDefault="qualified" version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" xml:lang="EN" xmlns:hfp="http://www.w3.org/2001/XMLSchema-hasFacetAndProperty">
- <xs:annotation>
-  <xs:documentation>
-	 Part 1 version: Id: XMLSchema.xsd,v 1.50 2002/05/22 09:24:24 ht Exp
-	 Part 2 version: Id: datatypes.xsd,v 1.54 2002/05/27 22:22:50 ht Exp
-  </xs:documentation>
- </xs:annotation>
-
-
- <xs:annotation>
-	<xs:documentation source="http://www.w3.org/TR/2001/REC-xmlschema-1-20010502/structures.html">
-	The schema corresponding to this document is normative,
-	with respect to the syntactic constraints it expresses in the
-	XML Schema language.  The documentation (within &lt;documentation> elements)
-	below, is not normative, but rather highlights important aspects of
-	the W3C Recommendation of which this is a part</xs:documentation>
- </xs:annotation>
-
- <xs:annotation>
-	<xs:documentation>
-	The simpleType element and all of its members are defined
-		towards the end of this schema document</xs:documentation>
- </xs:annotation>
-
- <xs:import namespace="http://www.w3.org/XML/1998/namespace" schemaLocation="http://www.w3.org/2001/xml.xsd">
-	<xs:annotation>
-	  <xs:documentation>
-		 Get access to the xml: attribute groups for xml:lang
-		 as declared on 'schema' and 'documentation' below
-	  </xs:documentation>
-	</xs:annotation>
- </xs:import>
-
- <xs:complexType name="openAttrs">
-	<xs:annotation>
-	  <xs:documentation>
-		 This type is extended by almost all schema types
-		 to allow attributes from other namespaces to be
-		 added to user schemas.
-	  </xs:documentation>
-	</xs:annotation>
-	<xs:complexContent>
-	  <xs:restriction base="xs:anyType">
-		 <xs:anyAttribute namespace="##other" processContents="lax"/>
-	  </xs:restriction>
-	</xs:complexContent>
- </xs:complexType>
-
- <xs:complexType name="annotated">
-	<xs:annotation>
-	  <xs:documentation>
-		 This type is extended by all types which allow annotation
-		 other than &lt;schema&gt; itself
-	  </xs:documentation>
-	</xs:annotation>
-	<xs:complexContent>
-	  <xs:extension base="xs:openAttrs">
-		 <xs:sequence>
-			<xs:element ref="xs:annotation" minOccurs="0"/>
-		 </xs:sequence>
-		 <xs:attribute name="id" type="xs:ID"/>
-	  </xs:extension>
-	</xs:complexContent>
- </xs:complexType>
-
- <xs:group name="schemaTop">
-  <xs:annotation>
-	<xs:documentation>
-	This group is for the
-	elements which occur freely at the top level of schemas.
-	All of their types are based on the "annotated" type by extension.</xs:documentation>
-  </xs:annotation>
-  <xs:choice>
-	<xs:group ref="xs:redefinable"/>
-	<xs:element ref="xs:element"/>
-	<xs:element ref="xs:attribute"/>
-	<xs:element ref="xs:notation"/>
-  </xs:choice>
- </xs:group>
- 
- <xs:group name="redefinable">
-  <xs:annotation>
-	<xs:documentation>
-	This group is for the
-	elements which can self-redefine (see &lt;redefine> below).</xs:documentation>
-  </xs:annotation>
-  <xs:choice>
-	<xs:element ref="xs:simpleType"/>
-	<xs:element ref="xs:complexType"/>
-	<xs:element ref="xs:group"/>
-	<xs:element ref="xs:attributeGroup"/>
-  </xs:choice>
- </xs:group>
-
- <xs:simpleType name="formChoice">
-  <xs:annotation>
-	<xs:documentation>
-	A utility type, not for public use</xs:documentation>
-  </xs:annotation>
-  <xs:restriction base="xs:NMTOKEN">
-	<xs:enumeration value="qualified"/>
-	<xs:enumeration value="unqualified"/>
-  </xs:restriction>
- </xs:simpleType>
-
- <xs:simpleType name="reducedDerivationControl">
-  <xs:annotation>
-	<xs:documentation>
-	A utility type, not for public use</xs:documentation>
-  </xs:annotation>
-  <xs:restriction base="xs:derivationControl">
-	<xs:enumeration value="extension"/>
-	<xs:enumeration value="restriction"/>
-  </xs:restriction>
- </xs:simpleType>
-
- <xs:simpleType name="derivationSet">
-  <xs:annotation>
-	<xs:documentation>
-	A utility type, not for public use</xs:documentation>
-	<xs:documentation>
-	#all or (possibly empty) subset of {extension, restriction}</xs:documentation>
-  </xs:annotation>
-  <xs:union>
-	<xs:simpleType>	 
-	 <xs:restriction base="xs:token">
-	  <xs:enumeration value="#all"/>
-	 </xs:restriction>
-	</xs:simpleType>
-	<xs:simpleType>
-	 <xs:list itemType="xs:reducedDerivationControl"/>
-	</xs:simpleType>
-  </xs:union>
- </xs:simpleType>
-
- <xs:element name="schema" id="schema">
-  <xs:annotation>
-	 <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-schema"/>
-  </xs:annotation>
-  <xs:complexType>
-	<xs:complexContent>
-	 <xs:extension base="xs:openAttrs">
-	  <xs:sequence>
-		<xs:choice minOccurs="0" maxOccurs="unbounded">
-		 <xs:element ref="xs:include"/>
-		 <xs:element ref="xs:import"/>
-		 <xs:element ref="xs:redefine"/>
-		 <xs:element ref="xs:annotation"/>
-		</xs:choice>
-		<xs:sequence minOccurs="0" maxOccurs="unbounded">
-		 <xs:group ref="xs:schemaTop"/>
-		 <xs:element ref="xs:annotation" minOccurs="0" maxOccurs="unbounded"/>
-		</xs:sequence>
-	  </xs:sequence>
-	  <xs:attribute name="targetNamespace" type="xs:anyURI"/>
-	  <xs:attribute name="version" type="xs:normalizedString"/>
-	  <xs:attribute name="finalDefault" type="xs:derivationSet" use="optional" default=""/>
-	  <xs:attribute name="blockDefault" type="xs:blockSet" use="optional" default=""/>
-	  <xs:attribute name="attributeFormDefault" type="xs:formChoice" use="optional" default="unqualified"/>
-	  <xs:attribute name="elementFormDefault" type="xs:formChoice" use="optional" default="unqualified"/>
-	  <xs:attribute name="id" type="xs:ID"/>
-	  <xs:attribute ref="xml:lang"/>
-	 </xs:extension>
-	</xs:complexContent>
-  </xs:complexType>
-
-  <xs:key name="element">
-	<xs:selector xpath="xs:element"/>
-	<xs:field xpath="@name"/>
-  </xs:key>
-
-  <xs:key name="attribute">
-	<xs:selector xpath="xs:attribute"/>
-	<xs:field xpath="@name"/>
-  </xs:key>
-
-  <xs:key name="type">
-	<xs:selector xpath="xs:complexType|xs:simpleType"/>
-	<xs:field xpath="@name"/>
-  </xs:key>
- 
-  <xs:key name="group">
-	<xs:selector xpath="xs:group"/>
-	<xs:field xpath="@name"/>
-  </xs:key>
- 
-  <xs:key name="attributeGroup">
-	<xs:selector xpath="xs:attributeGroup"/>
-	<xs:field xpath="@name"/>
-  </xs:key>
- 
-  <xs:key name="notation">
-	<xs:selector xpath="xs:notation"/>
-	<xs:field xpath="@name"/>
-  </xs:key>
-
-  <xs:key name="identityConstraint">
-	<xs:selector xpath=".//xs:key|.//xs:unique|.//xs:keyref"/>
-	<xs:field xpath="@name"/>
-  </xs:key>
-
- </xs:element>
-
- <xs:simpleType name="allNNI">
-  <xs:annotation><xs:documentation>
-	for maxOccurs</xs:documentation></xs:annotation>
-  <xs:union memberTypes="xs:nonNegativeInteger">
-	<xs:simpleType>
-	 <xs:restriction base="xs:NMTOKEN">
-	  <xs:enumeration value="unbounded"/>
-	 </xs:restriction>
-	</xs:simpleType>
-  </xs:union>
- </xs:simpleType>
-
- <xs:attributeGroup name="occurs">
-  <xs:annotation><xs:documentation>
-	for all particles</xs:documentation></xs:annotation>
-  <xs:attribute name="minOccurs" type="xs:nonNegativeInteger" use="optional" default="1"/>
-  <xs:attribute name="maxOccurs" type="xs:allNNI" use="optional" default="1"/>
- </xs:attributeGroup>
-
- <xs:attributeGroup name="defRef">
-  <xs:annotation><xs:documentation>
-	for element, group and attributeGroup,
-	which both define and reference</xs:documentation></xs:annotation>
-  <xs:attribute name="name" type="xs:NCName"/>
-  <xs:attribute name="ref" type="xs:QName"/>
- </xs:attributeGroup>
-
- <xs:group name="typeDefParticle">
-  <xs:annotation>
-	 <xs:documentation>
-	'complexType' uses this</xs:documentation></xs:annotation>
-  <xs:choice>
-	<xs:element name="group" type="xs:groupRef"/>
-	<xs:element ref="xs:all"/>
-	<xs:element ref="xs:choice"/>
-	<xs:element ref="xs:sequence"/>
-  </xs:choice>
- </xs:group>
- 
- 
-
- <xs:group name="nestedParticle">
-  <xs:choice>
-	<xs:element name="element" type="xs:localElement"/>
-	<xs:element name="group" type="xs:groupRef"/>
-	<xs:element ref="xs:choice"/>
-	<xs:element ref="xs:sequence"/>
-	<xs:element ref="xs:any"/>
-  </xs:choice>
- </xs:group>
- 
- <xs:group name="particle">
-  <xs:choice>
-	<xs:element name="element" type="xs:localElement"/>
-	<xs:element name="group" type="xs:groupRef"/>
-	<xs:element ref="xs:all"/>
-	<xs:element ref="xs:choice"/>
-	<xs:element ref="xs:sequence"/>
-	<xs:element ref="xs:any"/>
-  </xs:choice>
- </xs:group>
- 
- <xs:complexType name="attribute">
-  <xs:complexContent>
-	<xs:extension base="xs:annotated">
-	 <xs:sequence>
-	  <xs:element name="simpleType" minOccurs="0" type="xs:localSimpleType"/>
-	 </xs:sequence>
-	 <xs:attributeGroup ref="xs:defRef"/>
-	 <xs:attribute name="type" type="xs:QName"/>
-	 <xs:attribute name="use" use="optional" default="optional">
-	  <xs:simpleType>
-		<xs:restriction base="xs:NMTOKEN">
-		 <xs:enumeration value="prohibited"/>
-		 <xs:enumeration value="optional"/>
-		 <xs:enumeration value="required"/>
-		</xs:restriction>
-	  </xs:simpleType>
-	 </xs:attribute>
-	 <xs:attribute name="default" type="xs:string"/>
-	 <xs:attribute name="fixed" type="xs:string"/>
-	 <xs:attribute name="form" type="xs:formChoice"/>
-	</xs:extension>
-  </xs:complexContent>
- </xs:complexType>
- 
- <xs:complexType name="topLevelAttribute">
-  <xs:complexContent>
-	<xs:restriction base="xs:attribute">
-	 <xs:sequence>
-	  <xs:element ref="xs:annotation" minOccurs="0"/>
-	  <xs:element name="simpleType" minOccurs="0" type="xs:localSimpleType"/>
-	 </xs:sequence>
-	 <xs:attribute name="ref" use="prohibited"/>
-	 <xs:attribute name="form" use="prohibited"/>
-	 <xs:attribute name="use" use="prohibited"/>
-	 <xs:attribute name="name" use="required" type="xs:NCName"/>
-	 <xs:anyAttribute namespace="##other" processContents="lax"/>
-	</xs:restriction>
-  </xs:complexContent>
- </xs:complexType>
-
- <xs:group name="attrDecls">
-  <xs:sequence>
-	<xs:choice minOccurs="0" maxOccurs="unbounded">
-	 <xs:element name="attribute" type="xs:attribute"/>
-	 <xs:element name="attributeGroup" type="xs:attributeGroupRef"/>
-	</xs:choice>
-	<xs:element ref="xs:anyAttribute" minOccurs="0"/>
-  </xs:sequence>
- </xs:group>
-
- <xs:element name="anyAttribute" type="xs:wildcard" id="anyAttribute">
-  <xs:annotation>
-	<xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-anyAttribute"/>
-  </xs:annotation>
- </xs:element>
-
- <xs:group name="complexTypeModel">
-  <xs:choice>
-		<xs:element ref="xs:simpleContent"/>
-		<xs:element ref="xs:complexContent"/>
-		<xs:sequence>
-		 <xs:annotation>
-		  <xs:documentation>
-	This branch is short for
-	&lt;complexContent>
-	&lt;restriction base="xs:anyType">
-	...
-	&lt;/restriction>
-	&lt;/complexContent></xs:documentation>
-		 </xs:annotation>
-		 <xs:group ref="xs:typeDefParticle" minOccurs="0"/>
-		 <xs:group ref="xs:attrDecls"/>
-		</xs:sequence>
-  </xs:choice>
- </xs:group>
-
- <xs:complexType name="complexType" abstract="true">
-  <xs:complexContent>
-	<xs:extension base="xs:annotated">
-	 <xs:group ref="xs:complexTypeModel"/>
-	 <xs:attribute name="name" type="xs:NCName">
-	  <xs:annotation>
-		<xs:documentation>
-		Will be restricted to required or forbidden</xs:documentation>
-	  </xs:annotation>
-	 </xs:attribute>
-	 <xs:attribute name="mixed" type="xs:boolean" use="optional" default="false">
-	  <xs:annotation>
-		<xs:documentation>
-		Not allowed if simpleContent child is chosen.
-		May be overriden by setting on complexContent child.</xs:documentation>
-	 </xs:annotation>
-	 </xs:attribute>
-	 <xs:attribute name="abstract" type="xs:boolean" use="optional" default="false"/>
-	 <xs:attribute name="final" type="xs:derivationSet"/>
-	 <xs:attribute name="block" type="xs:derivationSet"/>
-	</xs:extension>
-  </xs:complexContent>
- </xs:complexType>
- 
- <xs:complexType name="topLevelComplexType">
-  <xs:complexContent>
-	<xs:restriction base="xs:complexType">
-	 <xs:sequence>
-	  <xs:element ref="xs:annotation" minOccurs="0"/>
-	  <xs:group ref="xs:complexTypeModel"/>
-	 </xs:sequence>
-	 <xs:attribute name="name" type="xs:NCName" use="required"/>
-	 <xs:anyAttribute namespace="##other" processContents="lax"/>
-	</xs:restriction>
-  </xs:complexContent>
- </xs:complexType>
- 
- <xs:complexType name="localComplexType">
-  <xs:complexContent>
-	<xs:restriction base="xs:complexType">
-	 <xs:sequence>
-	  <xs:element ref="xs:annotation" minOccurs="0"/>
-	  <xs:group ref="xs:complexTypeModel"/>
-	 </xs:sequence>
-	 <xs:attribute name="name" use="prohibited"/>
-	 <xs:attribute name="abstract" use="prohibited"/>
-	 <xs:attribute name="final" use="prohibited"/>
-	 <xs:attribute name="block" use="prohibited"/>
-	 <xs:anyAttribute namespace="##other" processContents="lax"/>
-	</xs:restriction>
-  </xs:complexContent>
- </xs:complexType>
- 
- <xs:complexType name="restrictionType">
-  <xs:complexContent>
-	<xs:extension base="xs:annotated">
-	 <xs:sequence>
-	  <xs:choice minOccurs="0">
-		<xs:group ref="xs:typeDefParticle"/>
-		<xs:group ref="xs:simpleRestrictionModel"/>
-	  </xs:choice>
-	  <xs:group ref="xs:attrDecls"/>
-	 </xs:sequence>
-	 <xs:attribute name="base" type="xs:QName" use="required"/>
-	</xs:extension>
-  </xs:complexContent>		  
- </xs:complexType>
-
- <xs:complexType name="complexRestrictionType">
-  <xs:complexContent>
-	<xs:restriction base="xs:restrictionType">
-	 <xs:sequence>
-	  <xs:element ref="xs:annotation" minOccurs="0"/>
-	  <xs:choice minOccurs="0">
-		<xs:annotation>
-		 <xs:documentation>This choice is added simply to
-						 make this a valid restriction per the REC</xs:documentation>
-		</xs:annotation>
-		<xs:group ref="xs:typeDefParticle"/>
-	  </xs:choice>
-	  <xs:group ref="xs:attrDecls"/>
-	 </xs:sequence>
-	 <xs:anyAttribute namespace="##other" processContents="lax"/>
-	</xs:restriction>
-  </xs:complexContent>		  
- </xs:complexType>
-
- <xs:complexType name="extensionType">
-  <xs:complexContent>
-	<xs:extension base="xs:annotated">
-	 <xs:sequence>
-	  <xs:group ref="xs:typeDefParticle" minOccurs="0"/>
-	  <xs:group ref="xs:attrDecls"/>
-	 </xs:sequence>
-	 <xs:attribute name="base" type="xs:QName" use="required"/>
-	</xs:extension>
-  </xs:complexContent>		  
- </xs:complexType>
-
- <xs:element name="complexContent" id="complexContent">
-  <xs:annotation>
-	<xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-complexContent"/>
-  </xs:annotation>
-  <xs:complexType>
-	<xs:complexContent>
-	 <xs:extension base="xs:annotated">
-	  <xs:choice>
-		<xs:element name="restriction" type="xs:complexRestrictionType"/>
-		<xs:element name="extension" type="xs:extensionType"/>
-	  </xs:choice> 	 
-	  <xs:attribute name="mixed" type="xs:boolean">
-		<xs:annotation>
-		 <xs:documentation>
-		 Overrides any setting on complexType parent.</xs:documentation>
-		</xs:annotation>
-	 </xs:attribute>
-	 </xs:extension>
-	</xs:complexContent>
-  </xs:complexType>
- </xs:element>
-
- <xs:complexType name="simpleRestrictionType">
-  <xs:complexContent>
-	<xs:restriction base="xs:restrictionType">
-	 <xs:sequence>
-	  <xs:element ref="xs:annotation" minOccurs="0"/>
-	  <xs:choice minOccurs="0">
-		<xs:annotation>
-		 <xs:documentation>This choice is added simply to
-						 make this a valid restriction per the REC</xs:documentation>
-		</xs:annotation>
-		<xs:group ref="xs:simpleRestrictionModel"/>
-	  </xs:choice>
-	  <xs:group ref="xs:attrDecls"/>
-	 </xs:sequence>
-	 <xs:anyAttribute namespace="##other" processContents="lax"/>
-	</xs:restriction>
-  </xs:complexContent>
- </xs:complexType>
-
- <xs:complexType name="simpleExtensionType">
-  <xs:complexContent>
-	<xs:restriction base="xs:extensionType">
-	 <xs:sequence>
-	  <xs:annotation>
-		<xs:documentation>
-		No typeDefParticle group reference</xs:documentation>
-	  </xs:annotation>
-	  <xs:element ref="xs:annotation" minOccurs="0"/>
-	  <xs:group ref="xs:attrDecls"/>
-	 </xs:sequence>
-	 <xs:anyAttribute namespace="##other" processContents="lax"/>
-	</xs:restriction>
-  </xs:complexContent>
- </xs:complexType>
-
- <xs:element name="simpleContent" id="simpleContent">
-  <xs:annotation>
-	<xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-simpleContent"/>
-  </xs:annotation>
-  <xs:complexType>
-	<xs:complexContent>
-	 <xs:extension base="xs:annotated">
-	  <xs:choice>
-		<xs:element name="restriction" type="xs:simpleRestrictionType"/>
-		<xs:element name="extension" type="xs:simpleExtensionType"/>
-	  </xs:choice>
-	 </xs:extension>
-	</xs:complexContent>
-  </xs:complexType>
- </xs:element>
- 
- <xs:element name="complexType" type="xs:topLevelComplexType" id="complexType">
-  <xs:annotation>
-	<xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-complexType"/>
-  </xs:annotation>
- </xs:element>
-
-
-  <xs:simpleType name="blockSet">
-	<xs:annotation>
-	 <xs:documentation>
-	 A utility type, not for public use</xs:documentation>
-	 <xs:documentation>
-	 #all or (possibly empty) subset of {substitution, extension,
-	 restriction}</xs:documentation>
-	</xs:annotation>
-	<xs:union>
-	 <xs:simpleType>	  
-	  <xs:restriction base="xs:token">
-		<xs:enumeration value="#all"/>
-	  </xs:restriction>
-	 </xs:simpleType>
-	 <xs:simpleType>
-	  <xs:list>
-		<xs:simpleType>
-		 <xs:restriction base="xs:derivationControl">
-		  <xs:enumeration value="extension"/>
-		  <xs:enumeration value="restriction"/>
-		  <xs:enumeration value="substitution"/>
-		 </xs:restriction>
-		</xs:simpleType>
-	  </xs:list>
-	 </xs:simpleType>
-	</xs:union>  
-  </xs:simpleType>
-
- <xs:complexType name="element" abstract="true">
-  <xs:annotation>
-	<xs:documentation>
-	The element element can be used either
-	at the top level to define an element-type binding globally,
-	or within a content model to either reference a globally-defined
-	element or type or declare an element-type binding locally.
-	The ref form is not allowed at the top level.</xs:documentation>
-  </xs:annotation>
-
-  <xs:complexContent>
-	<xs:extension base="xs:annotated">
-	 <xs:sequence>
-	  <xs:choice minOccurs="0">
-		<xs:element name="simpleType" type="xs:localSimpleType"/>
-		<xs:element name="complexType" type="xs:localComplexType"/>
-	  </xs:choice>
-	  <xs:group ref="xs:identityConstraint" minOccurs="0" maxOccurs="unbounded"/>
-	 </xs:sequence>
-	 <xs:attributeGroup ref="xs:defRef"/>
-	 <xs:attribute name="type" type="xs:QName"/>
-	 <xs:attribute name="substitutionGroup" type="xs:QName"/>
-	 <xs:attributeGroup ref="xs:occurs"/>
-	 <xs:attribute name="default" type="xs:string"/>
-	 <xs:attribute name="fixed" type="xs:string"/>
-	 <xs:attribute name="nillable" type="xs:boolean" use="optional" default="false"/>
-	 <xs:attribute name="abstract" type="xs:boolean" use="optional" default="false"/>
-	 <xs:attribute name="final" type="xs:derivationSet"/>
-	 <xs:attribute name="block" type="xs:blockSet"/>
-	 <xs:attribute name="form" type="xs:formChoice"/>
-	</xs:extension>
-  </xs:complexContent>
- </xs:complexType>
- 
- <xs:complexType name="topLevelElement">
-  <xs:complexContent>
-	<xs:restriction base="xs:element">
-	 <xs:sequence>
-	  <xs:element ref="xs:annotation" minOccurs="0"/>
-	  <xs:choice minOccurs="0">
-		<xs:element name="simpleType" type="xs:localSimpleType"/>
-		<xs:element name="complexType" type="xs:localComplexType"/>
-	  </xs:choice>
-	  <xs:group ref="xs:identityConstraint" minOccurs="0" maxOccurs="unbounded"/>
-	 </xs:sequence>
-	 <xs:attribute name="ref" use="prohibited"/>
-	 <xs:attribute name="form" use="prohibited"/>
-	 <xs:attribute name="minOccurs" use="prohibited"/>
-	 <xs:attribute name="maxOccurs" use="prohibited"/>
-	 <xs:attribute name="name" use="required" type="xs:NCName"/>
-	 <xs:anyAttribute namespace="##other" processContents="lax"/>
-	</xs:restriction>
-  </xs:complexContent>
- </xs:complexType>
- 
- <xs:complexType name="localElement">
-  <xs:complexContent>
-	<xs:restriction base="xs:element">
-	 <xs:sequence>
-	  <xs:element ref="xs:annotation" minOccurs="0"/>
-	  <xs:choice minOccurs="0">
-		<xs:element name="simpleType" type="xs:localSimpleType"/>
-		<xs:element name="complexType" type="xs:localComplexType"/>
-	  </xs:choice>
-	  <xs:group ref="xs:identityConstraint" minOccurs="0" maxOccurs="unbounded"/>
-	 </xs:sequence>
-	 <xs:attribute name="substitutionGroup" use="prohibited"/>
-	 <xs:attribute name="final" use="prohibited"/>
-	 <xs:attribute name="abstract" use="prohibited"/>
-	 <xs:anyAttribute namespace="##other" processContents="lax"/>
-	</xs:restriction>
-  </xs:complexContent>
- </xs:complexType>
-
- <xs:element name="element" type="xs:topLevelElement" id="element">
-  <xs:annotation>
-	<xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-element"/>
-  </xs:annotation>
- </xs:element>
-
- <xs:complexType name="group" abstract="true">
-  <xs:annotation>
-	<xs:documentation>
-	group type for explicit groups, named top-level groups and
-	group references</xs:documentation>
-  </xs:annotation>
-  <xs:complexContent>
-	<xs:extension base="xs:annotated">
-	 <xs:group ref="xs:particle" minOccurs="0" maxOccurs="unbounded"/>
-	 <xs:attributeGroup ref="xs:defRef"/>
-	 <xs:attributeGroup ref="xs:occurs"/>
-	</xs:extension>
-  </xs:complexContent>
- </xs:complexType>
- 
- <xs:complexType name="realGroup">
-  <xs:complexContent>
-	<xs:restriction base="xs:group">
-	 <xs:sequence>
-	  <xs:element ref="xs:annotation" minOccurs="0"/>
-	  <xs:choice minOccurs="0" maxOccurs="1">
-		<xs:element ref="xs:all"/>
-		<xs:element ref="xs:choice"/>
-		<xs:element ref="xs:sequence"/>
-	  </xs:choice>
-	 </xs:sequence>
-	 <xs:anyAttribute namespace="##other" processContents="lax"/>
-	</xs:restriction>
-  </xs:complexContent>
- </xs:complexType>
-
- <xs:complexType name="namedGroup">
-  <xs:complexContent>
-	<xs:restriction base="xs:realGroup">
-	 <xs:sequence>
-	  <xs:element ref="xs:annotation" minOccurs="0"/>
-	  <xs:choice minOccurs="1" maxOccurs="1">
-		<xs:element name="all">
-		 <xs:complexType>
-		  <xs:complexContent>
-			<xs:restriction base="xs:all">
-			 <xs:group ref="xs:allModel"/>
-			 <xs:attribute name="minOccurs" use="prohibited"/>
-			 <xs:attribute name="maxOccurs" use="prohibited"/>
-			 <xs:anyAttribute namespace="##other" processContents="lax"/>
-			</xs:restriction>
-		  </xs:complexContent>
-		 </xs:complexType>
-		</xs:element>
-		<xs:element name="choice" type="xs:simpleExplicitGroup"/>
-		<xs:element name="sequence" type="xs:simpleExplicitGroup"/>
-	  </xs:choice>
-	 </xs:sequence>
-	 <xs:attribute name="name" use="required" type="xs:NCName"/>
-	 <xs:attribute name="ref" use="prohibited"/>
-	 <xs:attribute name="minOccurs" use="prohibited"/>
-	 <xs:attribute name="maxOccurs" use="prohibited"/>
-	 <xs:anyAttribute namespace="##other" processContents="lax"/>
-	</xs:restriction>
-  </xs:complexContent>
- </xs:complexType>
-
- <xs:complexType name="groupRef">
-  <xs:complexContent>
-	<xs:restriction base="xs:realGroup">
-	 <xs:sequence>
-	  <xs:element ref="xs:annotation" minOccurs="0"/>
-	 </xs:sequence>
-	 <xs:attribute name="ref" use="required" type="xs:QName"/>
-	 <xs:attribute name="name" use="prohibited"/>
-	 <xs:anyAttribute namespace="##other" processContents="lax"/>
-	</xs:restriction>
-  </xs:complexContent>
- </xs:complexType>
-
- <xs:complexType name="explicitGroup">
-  <xs:annotation>
-	<xs:documentation>
-	group type for the three kinds of group</xs:documentation>
-  </xs:annotation>
-  <xs:complexContent>
-	<xs:restriction base="xs:group">
-	 <xs:sequence>
-	  <xs:element ref="xs:annotation" minOccurs="0"/>
-	  <xs:group ref="xs:nestedParticle" minOccurs="0" maxOccurs="unbounded"/>
-	 </xs:sequence>
-	 <xs:attribute name="name" type="xs:NCName" use="prohibited"/>
-	 <xs:attribute name="ref" type="xs:QName" use="prohibited"/>
-	 <xs:anyAttribute namespace="##other" processContents="lax"/>
-	</xs:restriction>
-  </xs:complexContent>
- </xs:complexType>
- 
- <xs:complexType name="simpleExplicitGroup">
-  <xs:complexContent>
-	<xs:restriction base="xs:explicitGroup">
-	 <xs:sequence>
-	  <xs:element ref="xs:annotation" minOccurs="0"/>
-	  <xs:group ref="xs:nestedParticle" minOccurs="0" maxOccurs="unbounded"/>
-	 </xs:sequence>
-	 <xs:attribute name="minOccurs" use="prohibited"/>
-	 <xs:attribute name="maxOccurs" use="prohibited"/>
-	 <xs:anyAttribute namespace="##other" processContents="lax"/>
-	</xs:restriction>
-  </xs:complexContent>
- </xs:complexType>
- 
- <xs:group name="allModel">
-  <xs:sequence>
-		<xs:element ref="xs:annotation" minOccurs="0"/>
-		<xs:choice minOccurs="0" maxOccurs="unbounded">
-		 <xs:annotation>
-		  <xs:documentation>This choice with min/max is here to
-								  avoid a pblm with the Elt:All/Choice/Seq
-								  Particle derivation constraint</xs:documentation>
-		 </xs:annotation>
-		 <xs:element name="element">
-		  <xs:complexType>
-			<xs:annotation>
-			 <xs:documentation>restricted max/min</xs:documentation>
-			</xs:annotation>
-			<xs:complexContent>
-			 <xs:restriction base="xs:localElement">
-			  <xs:sequence>
-				<xs:element ref="xs:annotation" minOccurs="0"/>
-				<xs:choice minOccurs="0">
-				 <xs:element name="simpleType" type="xs:localSimpleType"/>
-				 <xs:element name="complexType" type="xs:localComplexType"/>
-				</xs:choice>
-				<xs:group ref="xs:identityConstraint" minOccurs="0" maxOccurs="unbounded"/>
-			  </xs:sequence>
-			  <xs:attribute name="minOccurs" use="optional" default="1">
-				<xs:simpleType>
-				 <xs:restriction base="xs:nonNegativeInteger">
-				  <xs:enumeration value="0"/>
-				  <xs:enumeration value="1"/>
-				 </xs:restriction>
-				</xs:simpleType>
-			  </xs:attribute>
-			  <xs:attribute name="maxOccurs" use="optional" default="1">
-				<xs:simpleType>
-				 <xs:restriction base="xs:allNNI">
-				  <xs:enumeration value="0"/>
-				  <xs:enumeration value="1"/>
-				 </xs:restriction>
-				</xs:simpleType>
-			  </xs:attribute>
-			  <xs:anyAttribute namespace="##other" processContents="lax"/>
-			 </xs:restriction>
-			</xs:complexContent>
-		  </xs:complexType>	  
-		 </xs:element>
-		</xs:choice>
-	  </xs:sequence>
- </xs:group>
-
-  <xs:complexType name="all">
-	<xs:annotation>
-	 <xs:documentation>
-	Only elements allowed inside</xs:documentation>
-	</xs:annotation>
-	<xs:complexContent>
-	 <xs:restriction base="xs:explicitGroup">
-	  <xs:group ref="xs:allModel"/>
-	  <xs:attribute name="minOccurs" use="optional" default="1">
-		<xs:simpleType>
-		 <xs:restriction base="xs:nonNegativeInteger">
-		  <xs:enumeration value="0"/>
-		  <xs:enumeration value="1"/>
-		 </xs:restriction>
-		</xs:simpleType>
-	  </xs:attribute>
-	  <xs:attribute name="maxOccurs" use="optional" default="1">
-		<xs:simpleType>
-		 <xs:restriction base="xs:allNNI">
-		  <xs:enumeration value="1"/>
-		 </xs:restriction>
-		</xs:simpleType>
-	  </xs:attribute>
-	  <xs:anyAttribute namespace="##other" processContents="lax"/>
-	 </xs:restriction>
-	</xs:complexContent>
-  </xs:complexType>
-
- <xs:element name="all" id="all" type="xs:all">
-  <xs:annotation>
-	<xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-all"/>
-  </xs:annotation>
- </xs:element>
-
- <xs:element name="choice" type="xs:explicitGroup" id="choice">
-  <xs:annotation>
-	<xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-choice"/>
-  </xs:annotation>
- </xs:element>
-
- <xs:element name="sequence" type="xs:explicitGroup" id="sequence">
-  <xs:annotation>
-	<xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-sequence"/>
-  </xs:annotation>
- </xs:element>
-
- <xs:element name="group" type="xs:namedGroup" id="group">
-  <xs:annotation>
-	<xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-group"/>
-  </xs:annotation>
- </xs:element>
-
- <xs:complexType name="wildcard">
-  <xs:complexContent>
-	<xs:extension base="xs:annotated">
-	 <xs:attribute name="namespace" type="xs:namespaceList" use="optional" default="##any"/>
-	 <xs:attribute name="processContents" use="optional" default="strict">
-	  <xs:simpleType>
-		<xs:restriction base="xs:NMTOKEN">
-		 <xs:enumeration value="skip"/>
-		 <xs:enumeration value="lax"/>
-		 <xs:enumeration value="strict"/>
-		</xs:restriction>
-	  </xs:simpleType>
-	 </xs:attribute>
-	</xs:extension>
-  </xs:complexContent>
- </xs:complexType>
-
- <xs:element name="any" id="any">
-  <xs:annotation>
-	<xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-any"/>
-  </xs:annotation>
-  <xs:complexType>
-	<xs:complexContent>
-	 <xs:extension base="xs:wildcard">
-	  <xs:attributeGroup ref="xs:occurs"/>
-	 </xs:extension>
-	</xs:complexContent>
-  </xs:complexType>
- </xs:element>
-
-  <xs:annotation>
-	<xs:documentation>
-	simple type for the value of the 'namespace' attr of
-	'any' and 'anyAttribute'</xs:documentation>
-  </xs:annotation>
-  <xs:annotation>
-	<xs:documentation>
-	Value is
-				  ##any		 - - any non-conflicting WFXML/attribute at all
-
-				  ##other	 - - any non-conflicting WFXML/attribute from
-										namespace other than targetNS
-
-				  ##local	 - - any unqualified non-conflicting WFXML/attribute 
-
-				  one or 	 - - any non-conflicting WFXML/attribute from
-				  more URI			the listed namespaces
-				  references
-				  (space separated)
-
-	 ##targetNamespace or ##local may appear in the above list, to
-		  refer to the targetNamespace of the enclosing
-		  schema or an absent targetNamespace respectively</xs:documentation>
-  </xs:annotation>
-
- <xs:simpleType name="namespaceList">
-  <xs:annotation>
-	<xs:documentation>
-	A utility type, not for public use</xs:documentation>
-  </xs:annotation>
-  <xs:union>
-	<xs:simpleType>
-	 <xs:restriction base="xs:token">
-	  <xs:enumeration value="##any"/>
-	  <xs:enumeration value="##other"/>
-	 </xs:restriction>
-	</xs:simpleType>
-	<xs:simpleType>
-	 <xs:list>
-	  <xs:simpleType>
-		<xs:union memberTypes="xs:anyURI">
-		 <xs:simpleType>
-		  <xs:restriction base="xs:token">
-			<xs:enumeration value="##targetNamespace"/>
-			<xs:enumeration value="##local"/>
-		  </xs:restriction>
-		 </xs:simpleType>
-		</xs:union>
-	  </xs:simpleType>
-	 </xs:list>
-	</xs:simpleType>
-  </xs:union>
- </xs:simpleType>
-
- <xs:element name="attribute" type="xs:topLevelAttribute" id="attribute">
-  <xs:annotation>
-	<xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-attribute"/>
-  </xs:annotation>
- </xs:element>
-
- <xs:complexType name="attributeGroup" abstract="true">
-  <xs:complexContent>
-	<xs:extension base="xs:annotated">
-	 <xs:group ref="xs:attrDecls"/>
-	 <xs:attributeGroup ref="xs:defRef"/>
-	</xs:extension>
-  </xs:complexContent>
- </xs:complexType>
- 
- <xs:complexType name="namedAttributeGroup">
-  <xs:complexContent>
-	<xs:restriction base="xs:attributeGroup">
-	 <xs:sequence>
-	  <xs:element ref="xs:annotation" minOccurs="0"/>
-	  <xs:group ref="xs:attrDecls"/>
-	 </xs:sequence>
-	 <xs:attribute name="name" use="required" type="xs:NCName"/>
-	 <xs:attribute name="ref" use="prohibited"/>
-	 <xs:anyAttribute namespace="##other" processContents="lax"/>
-	</xs:restriction>
-  </xs:complexContent>
- </xs:complexType>
-
- <xs:complexType name="attributeGroupRef">
-  <xs:complexContent>
-	<xs:restriction base="xs:attributeGroup">
-	 <xs:sequence>
-	  <xs:element ref="xs:annotation" minOccurs="0"/>
-	 </xs:sequence>
-	 <xs:attribute name="ref" use="required" type="xs:QName"/>
-	 <xs:attribute name="name" use="prohibited"/>
-	 <xs:anyAttribute namespace="##other" processContents="lax"/>
-	</xs:restriction>
-  </xs:complexContent>
- </xs:complexType>
-
- <xs:element name="attributeGroup" type="xs:namedAttributeGroup" id="attributeGroup">
-  <xs:annotation>
-	<xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-attributeGroup"/>
-  </xs:annotation>
- </xs:element>
-
- <xs:element name="include" id="include">
-  <xs:annotation>
-	<xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-include"/>
-  </xs:annotation>
-  <xs:complexType>
-	<xs:complexContent>
-	 <xs:extension base="xs:annotated">
-	  <xs:attribute name="schemaLocation" type="xs:anyURI" use="required"/>
-	 </xs:extension>
-	</xs:complexContent>
-  </xs:complexType>
- </xs:element>
-
- <xs:element name="redefine" id="redefine">
-  <xs:annotation>
-	<xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-redefine"/>
-  </xs:annotation>
-  <xs:complexType>
-	<xs:complexContent>
-	 <xs:extension base="xs:openAttrs">
-	  <xs:choice minOccurs="0" maxOccurs="unbounded">
-		<xs:element ref="xs:annotation"/>
-		<xs:group ref="xs:redefinable"/>
-	  </xs:choice>
-	  <xs:attribute name="schemaLocation" type="xs:anyURI" use="required"/>
-	  <xs:attribute name="id" type="xs:ID"/>
-	 </xs:extension>
-	</xs:complexContent>
-  </xs:complexType>
- </xs:element>
-
- <xs:element name="import" id="import">
-  <xs:annotation>
-	<xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-import"/>
-  </xs:annotation>
-  <xs:complexType>
-	<xs:complexContent>
-	 <xs:extension base="xs:annotated">
-	  <xs:attribute name="namespace" type="xs:anyURI"/>
-	  <xs:attribute name="schemaLocation" type="xs:anyURI"/>
-	 </xs:extension>
-	</xs:complexContent>
-  </xs:complexType>
- </xs:element>
-
- <xs:element name="selector" id="selector">
-  <xs:annotation>
-	<xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-selector"/>
-  </xs:annotation>
-  <xs:complexType>
-  <xs:complexContent>
-	<xs:extension base="xs:annotated">
-	  <xs:attribute name="xpath" use="required">
-		<xs:simpleType>
-		 <xs:annotation>
-		  <xs:documentation>A subset of XPath expressions for use
-in selectors</xs:documentation>
-		  <xs:documentation>A utility type, not for public
-use</xs:documentation>
-		 </xs:annotation>
-		 <xs:restriction base="xs:token">
-		  <xs:annotation>
-			<xs:documentation>The following pattern is intended to allow XPath
-									expressions per the following EBNF:
-			 Selector	 ::=	  Path ( '|' Path )*  
-			 Path 	::=	 ('.//')? Step ( '/' Step )*	
-			 Step 	::=	 '.' | NameTest  
-			 NameTest	 ::=	  QName | '*' | NCName ':' '*'  
-									child:: is also allowed
-			</xs:documentation>
-		  </xs:annotation>
-		  <xs:pattern value="(\.//)?(((child::)?((\i\c*:)?(\i\c*|\*)))|\.)(/(((child::)?((\i\c*:)?(\i\c*|\*)))|\.))*(\|(\.//)?(((child::)?((\i\c*:)?(\i\c*|\*)))|\.)(/(((child::)?((\i\c*:)?(\i\c*|\*)))|\.))*)*">
-		  </xs:pattern>
-		 </xs:restriction>
-		</xs:simpleType>
-	  </xs:attribute>
-	</xs:extension>
-  </xs:complexContent>
- </xs:complexType>
- </xs:element>
-
- <xs:element name="field" id="field">
-  <xs:annotation>
-	<xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-field"/>
-  </xs:annotation>
-  <xs:complexType>
-  <xs:complexContent>
-	<xs:extension base="xs:annotated">
-	  <xs:attribute name="xpath" use="required">
-		<xs:simpleType>
-		 <xs:annotation>
-		  <xs:documentation>A subset of XPath expressions for use
-in fields</xs:documentation>
-		  <xs:documentation>A utility type, not for public
-use</xs:documentation>
-		 </xs:annotation>
-		 <xs:restriction base="xs:token">
-		  <xs:annotation>
-			<xs:documentation>The following pattern is intended to allow XPath
-									expressions per the same EBNF as for selector,
-									with the following change:
-			 Path 	::=	 ('.//')? ( Step '/' )* ( Step | '@' NameTest ) 
-			</xs:documentation>
-		  </xs:annotation>
-		  <xs:pattern value="(\.//)?((((child::)?((\i\c*:)?(\i\c*|\*)))|\.)/)*((((child::)?((\i\c*:)?(\i\c*|\*)))|\.)|((attribute::|@)((\i\c*:)?(\i\c*|\*))))(\|(\.//)?((((child::)?((\i\c*:)?(\i\c*|\*)))|\.)/)*((((child::)?((\i\c*:)?(\i\c*|\*)))|\.)|((attribute::|@)((\i\c*:)?(\i\c*|\*)))))*">
-		  </xs:pattern>
-		 </xs:restriction>
-		</xs:simpleType>
-	  </xs:attribute>
-	</xs:extension>
-  </xs:complexContent>
- </xs:complexType>
- </xs:element>
-
- <xs:complexType name="keybase">
-  <xs:complexContent>
-	<xs:extension base="xs:annotated">
-	 <xs:sequence>
-	  <xs:element ref="xs:selector"/>
-	  <xs:element ref="xs:field" minOccurs="1" maxOccurs="unbounded"/>
-	 </xs:sequence>
-	 <xs:attribute name="name" type="xs:NCName" use="required"/>
-	</xs:extension>
-  </xs:complexContent>
- </xs:complexType>
-
- <xs:group name="identityConstraint">
-  <xs:annotation>
-	<xs:documentation>The three kinds of identity constraints, all with
-							type of or derived from 'keybase'.
-	</xs:documentation>
-  </xs:annotation>
-  <xs:choice>
-	<xs:element ref="xs:unique"/>
-	<xs:element ref="xs:key"/>
-	<xs:element ref="xs:keyref"/>
-  </xs:choice>
- </xs:group>
-
- <xs:element name="unique" type="xs:keybase" id="unique">
-  <xs:annotation>
-	<xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-unique"/>
-  </xs:annotation>
- </xs:element>
- <xs:element name="key" type="xs:keybase" id="key">
-  <xs:annotation>
-	<xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-key"/>
-  </xs:annotation>
- </xs:element>
- <xs:element name="keyref" id="keyref">
-  <xs:annotation>
-	<xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-keyref"/>
-  </xs:annotation>
-  <xs:complexType>
-	<xs:complexContent>
-	 <xs:extension base="xs:keybase">
-	  <xs:attribute name="refer" type="xs:QName" use="required"/>
-	 </xs:extension>
-	</xs:complexContent>
-  </xs:complexType>
- </xs:element>
-
- <xs:element name="notation" id="notation">
-  <xs:annotation>
-	<xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-notation"/>
-  </xs:annotation>
-  <xs:complexType>
-	<xs:complexContent>
-	 <xs:extension base="xs:annotated">
-	  <xs:attribute name="name" type="xs:NCName" use="required"/>
-	  <xs:attribute name="public" type="xs:public" use="required"/>
-	  <xs:attribute name="system" type="xs:anyURI"/>
-	 </xs:extension>
-	</xs:complexContent>
-  </xs:complexType>
- </xs:element>
-
- <xs:simpleType name="public">
-  <xs:annotation>
-	<xs:documentation>
-	A utility type, not for public use</xs:documentation>
-	<xs:documentation>
-	A public identifier, per ISO 8879</xs:documentation>
-  </xs:annotation>
-  <xs:restriction base="xs:token"/>
- </xs:simpleType>
-
- <xs:element name="appinfo" id="appinfo">
-	<xs:annotation>
-	  <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-appinfo"/>
-	</xs:annotation>
-	<xs:complexType mixed="true">
-	  <xs:sequence minOccurs="0" maxOccurs="unbounded">
-		 <xs:any processContents="lax"/>
-	  </xs:sequence>
-	  <xs:attribute name="source" type="xs:anyURI"/>
-	</xs:complexType>
- </xs:element>
-
- <xs:element name="documentation" id="documentation">
-	<xs:annotation>
-	  <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-documentation"/>
-	</xs:annotation>
-	<xs:complexType mixed="true">
-	  <xs:sequence minOccurs="0" maxOccurs="unbounded">
-		 <xs:any processContents="lax"/>
-	  </xs:sequence>
-	  <xs:attribute name="source" type="xs:anyURI"/>
-	<xs:attribute ref="xml:lang"/>
-	</xs:complexType>
- </xs:element>
-
- <xs:element name="annotation" id="annotation">
-	<xs:annotation>
-	  <xs:documentation source="http://www.w3.org/TR/xmlschema-1/#element-annotation"/>
-	</xs:annotation>
-	<xs:complexType>
-	 <xs:complexContent>
-	  <xs:extension base="xs:openAttrs">
-		<xs:choice minOccurs="0" maxOccurs="unbounded">
-		 <xs:element ref="xs:appinfo"/>
-		 <xs:element ref="xs:documentation"/>
-		</xs:choice>
-		<xs:attribute name="id" type="xs:ID"/>
-	  </xs:extension>
-	 </xs:complexContent>
-	</xs:complexType>
- </xs:element>
-
- <xs:annotation>
-  <xs:documentation>
-	notations for use within XML Schema schemas</xs:documentation>
- </xs:annotation>
-
- <xs:notation name="XMLSchemaStructures" public="structures" system="http://www.w3.org/2000/08/XMLSchema.xsd"/>
- <xs:notation name="XML" public="REC-xml-19980210" system="http://www.w3.org/TR/1998/REC-xml-19980210"/>
- 
- <xs:complexType name="anyType" mixed="true">
-  <xs:annotation>
-	<xs:documentation>
-	Not the real urType, but as close an approximation as we can
-	get in the XML representation</xs:documentation>
-  </xs:annotation>
-  <xs:sequence>
-	<xs:any minOccurs="0" maxOccurs="unbounded"/>
-  </xs:sequence>
-  <xs:anyAttribute/>
- </xs:complexType>
-
-  <xs:annotation>
-	 <xs:documentation>
-		First the built-in primitive datatypes.  These definitions are for
-		information only, the real built-in definitions are magic.	Note in
-		particular that there is no type named 'anySimpleType'.	The
-		primitives should really be derived from no type at all, and
-		anySimpleType should be derived as a union of all the primitives.
-	 </xs:documentation>
-
-	 <xs:documentation>
-		For each built-in datatype in this schema (both primitive and
-		derived) can be uniquely addressed via a URI constructed
-		as follows:
-		  1) the base URI is the URI of the XML Schema namespace
-		  2) the fragment identifier is the name of the datatype
-		  
-		For example, to address the int datatype, the URI is:
-		
-		  http://www.w3.org/2001/XMLSchema#int
-		
-		Additionally, each facet definition element can be uniquely
-		addressed via a URI constructed as follows:
-		  1) the base URI is the URI of the XML Schema namespace
-		  2) the fragment identifier is the name of the facet
-		  
-		For example, to address the maxInclusive facet, the URI is:
-		
-		  http://www.w3.org/2001/XMLSchema#maxInclusive
-
-		Additionally, each facet usage in a built-in datatype definition
-		can be uniquely addressed via a URI constructed as follows:
-		  1) the base URI is the URI of the XML Schema namespace
-		  2) the fragment identifier is the name of the datatype, followed
-			  by a period (".") followed by the name of the facet
-		  
-		For example, to address the usage of the maxInclusive facet in
-		the definition of int, the URI is:
-		
-		  http://www.w3.org/2001/XMLSchema#int.maxInclusive
-		  
-	 </xs:documentation>
-  </xs:annotation>
- 
-  <xs:simpleType name="string" id="string">
-	 <xs:annotation>
-		<xs:appinfo>
-		  <hfp:hasFacet name="length"/>
-		  <hfp:hasFacet name="minLength"/>
-		  <hfp:hasFacet name="maxLength"/>
-		  <hfp:hasFacet name="pattern"/>
-		  <hfp:hasFacet name="enumeration"/>
-		  <hfp:hasFacet name="whiteSpace"/>
-		  <hfp:hasProperty name="ordered" value="false"/>
-		  <hfp:hasProperty name="bounded" value="false"/>
-		  <hfp:hasProperty name="cardinality" value="countably infinite"/>
-		  <hfp:hasProperty name="numeric" value="false"/>
-		</xs:appinfo>
-		<xs:documentation
-					 source="http://www.w3.org/TR/xmlschema-2/#string"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:anySimpleType">
-		<xs:whiteSpace value="preserve" id="string.preserve"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="boolean" id="boolean">
-	 <xs:annotation>
-		<xs:appinfo>
-		  <hfp:hasFacet name="pattern"/>
-		  <hfp:hasFacet name="whiteSpace"/>
-		  <hfp:hasProperty name="ordered" value="false"/>
-		  <hfp:hasProperty name="bounded" value="false"/>
-		  <hfp:hasProperty name="cardinality" value="finite"/>
-		  <hfp:hasProperty name="numeric" value="false"/>
-		</xs:appinfo>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#boolean"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:anySimpleType">
-		<xs:whiteSpace value="collapse" fixed="true"
-		  id="boolean.whiteSpace"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="float" id="float">
-	 <xs:annotation>
-		<xs:appinfo>
-		  <hfp:hasFacet name="pattern"/>
-		  <hfp:hasFacet name="enumeration"/>
-		  <hfp:hasFacet name="whiteSpace"/>
-		  <hfp:hasFacet name="maxInclusive"/>
-		  <hfp:hasFacet name="maxExclusive"/>
-		  <hfp:hasFacet name="minInclusive"/>
-		  <hfp:hasFacet name="minExclusive"/>
-		  <hfp:hasProperty name="ordered" value="total"/>
-		  <hfp:hasProperty name="bounded" value="true"/>
-		  <hfp:hasProperty name="cardinality" value="finite"/>
-		  <hfp:hasProperty name="numeric" value="true"/>
-		</xs:appinfo>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#float"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:anySimpleType">
-		<xs:whiteSpace value="collapse" fixed="true"
-		  id="float.whiteSpace"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="double" id="double">
-	 <xs:annotation>
-		<xs:appinfo>
-		  <hfp:hasFacet name="pattern"/>
-		  <hfp:hasFacet name="enumeration"/>
-		  <hfp:hasFacet name="whiteSpace"/>
-		  <hfp:hasFacet name="maxInclusive"/>
-		  <hfp:hasFacet name="maxExclusive"/>
-		  <hfp:hasFacet name="minInclusive"/>
-		  <hfp:hasFacet name="minExclusive"/>
-		  <hfp:hasProperty name="ordered" value="total"/>
-		  <hfp:hasProperty name="bounded" value="true"/>
-		  <hfp:hasProperty name="cardinality" value="finite"/>
-		  <hfp:hasProperty name="numeric" value="true"/>
-		</xs:appinfo>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#double"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:anySimpleType">
-		<xs:whiteSpace value="collapse"	fixed="true"
-		  id="double.whiteSpace"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="decimal" id="decimal">
-	 <xs:annotation>
-		<xs:appinfo>
-		  <hfp:hasFacet name="totalDigits"/>
-		  <hfp:hasFacet name="fractionDigits"/>
-		  <hfp:hasFacet name="pattern"/>
-		  <hfp:hasFacet name="whiteSpace"/>
-		  <hfp:hasFacet name="enumeration"/>
-		  <hfp:hasFacet name="maxInclusive"/>
-		  <hfp:hasFacet name="maxExclusive"/>
-		  <hfp:hasFacet name="minInclusive"/>
-		  <hfp:hasFacet name="minExclusive"/>
-		  <hfp:hasProperty name="ordered" value="total"/>
-		  <hfp:hasProperty name="bounded" value="false"/>
-		  <hfp:hasProperty name="cardinality"
-					 value="countably infinite"/>
-		  <hfp:hasProperty name="numeric" value="true"/>
-		</xs:appinfo>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#decimal"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:anySimpleType">
-		<xs:whiteSpace value="collapse"	fixed="true"
-		  id="decimal.whiteSpace"/>
-	 </xs:restriction>
-	</xs:simpleType>
-
-	<xs:simpleType name="duration" id="duration">
-	 <xs:annotation>
-		<xs:appinfo>
-		  <hfp:hasFacet name="pattern"/>
-		  <hfp:hasFacet name="enumeration"/>
-		  <hfp:hasFacet name="whiteSpace"/>
-		  <hfp:hasFacet name="maxInclusive"/>
-		  <hfp:hasFacet name="maxExclusive"/>
-		  <hfp:hasFacet name="minInclusive"/>
-		  <hfp:hasFacet name="minExclusive"/>
-		  <hfp:hasProperty name="ordered" value="partial"/>
-		  <hfp:hasProperty name="bounded" value="false"/>
-		  <hfp:hasProperty name="cardinality"
-					 value="countably infinite"/>
-		  <hfp:hasProperty name="numeric" value="false"/>
-		</xs:appinfo>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#duration"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:anySimpleType">
-		<xs:whiteSpace value="collapse"	fixed="true"
-		  id="duration.whiteSpace"/>
-	 </xs:restriction>
-	</xs:simpleType>
-
- <xs:simpleType name="dateTime" id="dateTime">
-	 <xs:annotation>
-	 <xs:appinfo>
-		  <hfp:hasFacet name="pattern"/>
-		  <hfp:hasFacet name="enumeration"/>
-		  <hfp:hasFacet name="whiteSpace"/>
-		  <hfp:hasFacet name="maxInclusive"/>
-		  <hfp:hasFacet name="maxExclusive"/>
-		  <hfp:hasFacet name="minInclusive"/>
-		  <hfp:hasFacet name="minExclusive"/>
-		  <hfp:hasProperty name="ordered" value="partial"/>
-		  <hfp:hasProperty name="bounded" value="false"/>
-		  <hfp:hasProperty name="cardinality"
-					 value="countably infinite"/>
-		  <hfp:hasProperty name="numeric" value="false"/>
-		</xs:appinfo>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#dateTime"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:anySimpleType">
-		<xs:whiteSpace value="collapse"	fixed="true"
-		  id="dateTime.whiteSpace"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="time" id="time">
-	 <xs:annotation>
-	 <xs:appinfo>
-		  <hfp:hasFacet name="pattern"/>
-		  <hfp:hasFacet name="enumeration"/>
-		  <hfp:hasFacet name="whiteSpace"/>
-		  <hfp:hasFacet name="maxInclusive"/>
-		  <hfp:hasFacet name="maxExclusive"/>
-		  <hfp:hasFacet name="minInclusive"/>
-		  <hfp:hasFacet name="minExclusive"/>
-		  <hfp:hasProperty name="ordered" value="partial"/>
-		  <hfp:hasProperty name="bounded" value="false"/>
-		  <hfp:hasProperty name="cardinality"
-					 value="countably infinite"/>
-		  <hfp:hasProperty name="numeric" value="false"/>
-		</xs:appinfo>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#time"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:anySimpleType">
-		<xs:whiteSpace value="collapse"	fixed="true"
-		  id="time.whiteSpace"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="date" id="date">
-	<xs:annotation>
-	 <xs:appinfo>
-		  <hfp:hasFacet name="pattern"/>
-		  <hfp:hasFacet name="enumeration"/>
-		  <hfp:hasFacet name="whiteSpace"/>
-		  <hfp:hasFacet name="maxInclusive"/>
-		  <hfp:hasFacet name="maxExclusive"/>
-		  <hfp:hasFacet name="minInclusive"/>
-		  <hfp:hasFacet name="minExclusive"/>
-		  <hfp:hasProperty name="ordered" value="partial"/>
-		  <hfp:hasProperty name="bounded" value="false"/>
-		  <hfp:hasProperty name="cardinality"
-					 value="countably infinite"/>
-		  <hfp:hasProperty name="numeric" value="false"/>
-		</xs:appinfo>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#date"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:anySimpleType">
-		<xs:whiteSpace value="collapse"	fixed="true"
-		  id="date.whiteSpace"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="gYearMonth" id="gYearMonth">
-	<xs:annotation>
-	 <xs:appinfo>
-		  <hfp:hasFacet name="pattern"/>
-		  <hfp:hasFacet name="enumeration"/>
-		  <hfp:hasFacet name="whiteSpace"/>
-		  <hfp:hasFacet name="maxInclusive"/>
-		  <hfp:hasFacet name="maxExclusive"/>
-		  <hfp:hasFacet name="minInclusive"/>
-		  <hfp:hasFacet name="minExclusive"/>
-		  <hfp:hasProperty name="ordered" value="partial"/>
-		  <hfp:hasProperty name="bounded" value="false"/>
-		  <hfp:hasProperty name="cardinality"
-					 value="countably infinite"/>
-		  <hfp:hasProperty name="numeric" value="false"/>
-		</xs:appinfo>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#gYearMonth"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:anySimpleType">
-		<xs:whiteSpace value="collapse"	fixed="true"
-		  id="gYearMonth.whiteSpace"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="gYear" id="gYear">
-	 <xs:annotation>
-	 <xs:appinfo>
-		  <hfp:hasFacet name="pattern"/>
-		  <hfp:hasFacet name="enumeration"/>
-		  <hfp:hasFacet name="whiteSpace"/>
-		  <hfp:hasFacet name="maxInclusive"/>
-		  <hfp:hasFacet name="maxExclusive"/>
-		  <hfp:hasFacet name="minInclusive"/>
-		  <hfp:hasFacet name="minExclusive"/>
-		  <hfp:hasProperty name="ordered" value="partial"/>
-		  <hfp:hasProperty name="bounded" value="false"/>
-		  <hfp:hasProperty name="cardinality"
-					 value="countably infinite"/>
-		  <hfp:hasProperty name="numeric" value="false"/>
-		</xs:appinfo>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#gYear"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:anySimpleType">
-		<xs:whiteSpace value="collapse"	fixed="true"
-		  id="gYear.whiteSpace"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
- <xs:simpleType name="gMonthDay" id="gMonthDay">
-	 <xs:annotation>
-		<xs:appinfo>
-		  <hfp:hasFacet name="pattern"/>
-		  <hfp:hasFacet name="enumeration"/>
-		  <hfp:hasFacet name="whiteSpace"/>
-		  <hfp:hasFacet name="maxInclusive"/>
-		  <hfp:hasFacet name="maxExclusive"/>
-		  <hfp:hasFacet name="minInclusive"/>
-		  <hfp:hasFacet name="minExclusive"/>
-		  <hfp:hasProperty name="ordered" value="partial"/>
-		  <hfp:hasProperty name="bounded" value="false"/>
-		  <hfp:hasProperty name="cardinality"
-					 value="countably infinite"/>
-		  <hfp:hasProperty name="numeric" value="false"/>
-		</xs:appinfo>
-		 <xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#gMonthDay"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:anySimpleType">
-			<xs:whiteSpace value="collapse" fixed="true"
-					 id="gMonthDay.whiteSpace"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="gDay" id="gDay">
-	 <xs:annotation>
-  <xs:appinfo>
-		  <hfp:hasFacet name="pattern"/>
-		  <hfp:hasFacet name="enumeration"/>
-		  <hfp:hasFacet name="whiteSpace"/>
-		  <hfp:hasFacet name="maxInclusive"/>
-		  <hfp:hasFacet name="maxExclusive"/>
-		  <hfp:hasFacet name="minInclusive"/>
-		  <hfp:hasFacet name="minExclusive"/>
-		  <hfp:hasProperty name="ordered" value="partial"/>
-		  <hfp:hasProperty name="bounded" value="false"/>
-		  <hfp:hasProperty name="cardinality"
-					 value="countably infinite"/>
-		  <hfp:hasProperty name="numeric" value="false"/>
-		</xs:appinfo>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#gDay"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:anySimpleType">
-			<xs:whiteSpace value="collapse"	fixed="true"
-					 id="gDay.whiteSpace"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
- <xs:simpleType name="gMonth" id="gMonth">
-	 <xs:annotation>
-  <xs:appinfo>
-		  <hfp:hasFacet name="pattern"/>
-		  <hfp:hasFacet name="enumeration"/>
-		  <hfp:hasFacet name="whiteSpace"/>
-		  <hfp:hasFacet name="maxInclusive"/>
-		  <hfp:hasFacet name="maxExclusive"/>
-		  <hfp:hasFacet name="minInclusive"/>
-		  <hfp:hasFacet name="minExclusive"/>
-		  <hfp:hasProperty name="ordered" value="partial"/>
-		  <hfp:hasProperty name="bounded" value="false"/>
-		  <hfp:hasProperty name="cardinality"
-					 value="countably infinite"/>
-		  <hfp:hasProperty name="numeric" value="false"/>
-		</xs:appinfo>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#gMonth"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:anySimpleType">
-			<xs:whiteSpace value="collapse"	fixed="true"
-					 id="gMonth.whiteSpace"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-	<xs:simpleType name="hexBinary" id="hexBinary">
-	 <xs:annotation>
-		<xs:appinfo>
-		  <hfp:hasFacet name="length"/>
-		  <hfp:hasFacet name="minLength"/>
-		  <hfp:hasFacet name="maxLength"/>
-		  <hfp:hasFacet name="pattern"/>
-		  <hfp:hasFacet name="enumeration"/>
-		  <hfp:hasFacet name="whiteSpace"/>
-		  <hfp:hasProperty name="ordered" value="false"/>
-		  <hfp:hasProperty name="bounded" value="false"/>
-		  <hfp:hasProperty name="cardinality"
-					 value="countably infinite"/>
-		  <hfp:hasProperty name="numeric" value="false"/>
-		</xs:appinfo>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#binary"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:anySimpleType">
-		<xs:whiteSpace value="collapse" fixed="true"
-		  id="hexBinary.whiteSpace"/>
-	 </xs:restriction>
-	</xs:simpleType>
- 
- <xs:simpleType name="base64Binary" id="base64Binary">
-	 <xs:annotation>
-		<xs:appinfo>
-		  <hfp:hasFacet name="length"/>
-		  <hfp:hasFacet name="minLength"/>
-		  <hfp:hasFacet name="maxLength"/>
-		  <hfp:hasFacet name="pattern"/>
-		  <hfp:hasFacet name="enumeration"/>
-		  <hfp:hasFacet name="whiteSpace"/>
-		  <hfp:hasProperty name="ordered" value="false"/>
-		  <hfp:hasProperty name="bounded" value="false"/>
-		  <hfp:hasProperty name="cardinality"
-					 value="countably infinite"/>
-		  <hfp:hasProperty name="numeric" value="false"/>
-		</xs:appinfo>
-		<xs:documentation
-					 source="http://www.w3.org/TR/xmlschema-2/#base64Binary"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:anySimpleType">
-		<xs:whiteSpace value="collapse" fixed="true"
-		  id="base64Binary.whiteSpace"/>
-	 </xs:restriction>
-	</xs:simpleType>
-
-	<xs:simpleType name="anyURI" id="anyURI">
-	 <xs:annotation>
-		<xs:appinfo>
-		  <hfp:hasFacet name="length"/>
-		  <hfp:hasFacet name="minLength"/>
-		  <hfp:hasFacet name="maxLength"/>
-		  <hfp:hasFacet name="pattern"/>
-		  <hfp:hasFacet name="enumeration"/>
-		  <hfp:hasFacet name="whiteSpace"/>
-		  <hfp:hasProperty name="ordered" value="false"/>
-		  <hfp:hasProperty name="bounded" value="false"/>
-		  <hfp:hasProperty name="cardinality"
-					 value="countably infinite"/>
-		  <hfp:hasProperty name="numeric" value="false"/>
-		</xs:appinfo>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#anyURI"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:anySimpleType">
-		<xs:whiteSpace value="collapse"	fixed="true"
-		  id="anyURI.whiteSpace"/>
-	 </xs:restriction>
-	</xs:simpleType>
-
-  <xs:simpleType name="QName" id="QName">
-	 <xs:annotation>
-		  <xs:appinfo>
-		  <hfp:hasFacet name="length"/>
-		  <hfp:hasFacet name="minLength"/>
-		  <hfp:hasFacet name="maxLength"/>
-		  <hfp:hasFacet name="pattern"/>
-		  <hfp:hasFacet name="enumeration"/>
-		  <hfp:hasFacet name="whiteSpace"/>
-		  <hfp:hasProperty name="ordered" value="false"/>
-		  <hfp:hasProperty name="bounded" value="false"/>
-		  <hfp:hasProperty name="cardinality"
-					 value="countably infinite"/>
-		  <hfp:hasProperty name="numeric" value="false"/>
-		</xs:appinfo>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#QName"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:anySimpleType">
-		<xs:whiteSpace value="collapse"	fixed="true"
-		  id="QName.whiteSpace"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-	<xs:simpleType name="NOTATION" id="NOTATION">
-	 <xs:annotation>
-		  <xs:appinfo>
-		  <hfp:hasFacet name="length"/>
-		  <hfp:hasFacet name="minLength"/>
-		  <hfp:hasFacet name="maxLength"/>
-		  <hfp:hasFacet name="pattern"/>
-		  <hfp:hasFacet name="enumeration"/>
-		  <hfp:hasFacet name="whiteSpace"/>
-		  <hfp:hasProperty name="ordered" value="false"/>
-		  <hfp:hasProperty name="bounded" value="false"/>
-		  <hfp:hasProperty name="cardinality"
-					 value="countably infinite"/>
-		  <hfp:hasProperty name="numeric" value="false"/>
-		</xs:appinfo>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#NOTATION"/>
-		<xs:documentation>
-		  NOTATION cannot be used directly in a schema; rather a type
-		  must be derived from it by specifying at least one enumeration
-		  facet whose value is the name of a NOTATION declared in the
-		  schema.
-		</xs:documentation>
-	 </xs:annotation>
-	 <xs:restriction base="xs:anySimpleType">
-		<xs:whiteSpace value="collapse"	fixed="true"
-		  id="NOTATION.whiteSpace"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:annotation>
-	 <xs:documentation>
-		Now the derived primitive types
-	 </xs:documentation>
-  </xs:annotation>
-
-  <xs:simpleType name="normalizedString" id="normalizedString">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#normalizedString"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:string">
-		<xs:whiteSpace value="replace"
-		  id="normalizedString.whiteSpace"/>
-	 </xs:restriction>
-  </xs:simpleType>
-  
-  <xs:simpleType name="token" id="token">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#token"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:normalizedString">
-		<xs:whiteSpace value="collapse" id="token.whiteSpace"/>
-	 </xs:restriction>
-  </xs:simpleType>
-  
-  <xs:simpleType name="language" id="language">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#language"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:token">
-		<xs:pattern
-		  value="([a-zA-Z]{2}|[iI]-[a-zA-Z]+|[xX]-[a-zA-Z]{1,8})(-[a-zA-Z]{1,8})*"
-					 id="language.pattern">
-		  <xs:annotation>
-			 <xs:documentation
-					 source="http://www.w3.org/TR/REC-xml#NT-LanguageID">
-				pattern specifies the content of section 2.12 of XML 1.0e2
-				and RFC 1766
-			 </xs:documentation>
-		  </xs:annotation>
-		</xs:pattern>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="IDREFS" id="IDREFS">
-	 <xs:annotation>
-		<xs:appinfo>
-		  <hfp:hasFacet name="length"/>
-		  <hfp:hasFacet name="minLength"/>
-		  <hfp:hasFacet name="maxLength"/>
-		  <hfp:hasFacet name="enumeration"/>
-		  <hfp:hasFacet name="whiteSpace"/>
-		  <hfp:hasProperty name="ordered" value="false"/>
-		  <hfp:hasProperty name="bounded" value="false"/>
-		  <hfp:hasProperty name="cardinality"
-					 value="countably infinite"/>
-		  <hfp:hasProperty name="numeric" value="false"/>
-		</xs:appinfo>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#IDREFS"/>
-	 </xs:annotation>
-	 <xs:restriction>
-		<xs:simpleType>
-		  <xs:list itemType="xs:IDREF"/> 	
-		</xs:simpleType>
-		  <xs:minLength value="1" id="IDREFS.minLength"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="ENTITIES" id="ENTITIES">
-	 <xs:annotation>
-		<xs:appinfo>
-		  <hfp:hasFacet name="length"/>
-		  <hfp:hasFacet name="minLength"/>
-		  <hfp:hasFacet name="maxLength"/>
-		  <hfp:hasFacet name="enumeration"/>
-		  <hfp:hasFacet name="whiteSpace"/>
-		  <hfp:hasProperty name="ordered" value="false"/>
-		  <hfp:hasProperty name="bounded" value="false"/>
-		  <hfp:hasProperty name="cardinality"
-					 value="countably infinite"/>
-		  <hfp:hasProperty name="numeric" value="false"/>
-		</xs:appinfo>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#ENTITIES"/>
-	 </xs:annotation>
-	 <xs:restriction>
-		<xs:simpleType>
-		  <xs:list itemType="xs:ENTITY"/>
-		</xs:simpleType>
-		  <xs:minLength value="1" id="ENTITIES.minLength"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="NMTOKEN" id="NMTOKEN">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#NMTOKEN"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:token">
-		<xs:pattern value="\c+" id="NMTOKEN.pattern">
-		  <xs:annotation>
-			 <xs:documentation
-					 source="http://www.w3.org/TR/REC-xml#NT-Nmtoken">
-				pattern matches production 7 from the XML spec
-			 </xs:documentation>
-		  </xs:annotation>
-		</xs:pattern>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="NMTOKENS" id="NMTOKENS">
-	 <xs:annotation>
-		<xs:appinfo>
-		  <hfp:hasFacet name="length"/>
-		  <hfp:hasFacet name="minLength"/>
-		  <hfp:hasFacet name="maxLength"/>
-		  <hfp:hasFacet name="enumeration"/>
-		  <hfp:hasFacet name="whiteSpace"/>
-		  <hfp:hasProperty name="ordered" value="false"/>
-		  <hfp:hasProperty name="bounded" value="false"/>
-		  <hfp:hasProperty name="cardinality"
-					 value="countably infinite"/>
-		  <hfp:hasProperty name="numeric" value="false"/>
-		</xs:appinfo>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#NMTOKENS"/>
-	 </xs:annotation>
-	 <xs:restriction>
-		<xs:simpleType>
-		  <xs:list itemType="xs:NMTOKEN"/>
-		</xs:simpleType>
-		  <xs:minLength value="1" id="NMTOKENS.minLength"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="Name" id="Name">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#Name"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:token">
-		<xs:pattern value="\i\c*" id="Name.pattern">
-		  <xs:annotation>
-			 <xs:documentation
-								source="http://www.w3.org/TR/REC-xml#NT-Name">
-				pattern matches production 5 from the XML spec
-			 </xs:documentation>
-		  </xs:annotation>
-		</xs:pattern>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="NCName" id="NCName">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#NCName"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:Name">
-		<xs:pattern value="[\i-[:]][\c-[:]]*" id="NCName.pattern">
-		  <xs:annotation>
-			 <xs:documentation
-					 source="http://www.w3.org/TR/REC-xml-names/#NT-NCName">
-				pattern matches production 4 from the Namespaces in XML spec
-			 </xs:documentation>
-		  </xs:annotation>
-		</xs:pattern>
-	 </xs:restriction>
-  </xs:simpleType>
-
-	<xs:simpleType name="ID" id="ID">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#ID"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:NCName"/>
-	</xs:simpleType>
-
-	<xs:simpleType name="IDREF" id="IDREF">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#IDREF"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:NCName"/>
-	</xs:simpleType>
-
-	<xs:simpleType name="ENTITY" id="ENTITY">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#ENTITY"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:NCName"/>
-	</xs:simpleType>
-
-  <xs:simpleType name="integer" id="integer">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#integer"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:decimal">
-		<xs:fractionDigits value="0" fixed="true" id="integer.fractionDigits"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="nonPositiveInteger" id="nonPositiveInteger">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#nonPositiveInteger"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:integer">
-		<xs:maxInclusive value="0" id="nonPositiveInteger.maxInclusive"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="negativeInteger" id="negativeInteger">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#negativeInteger"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:nonPositiveInteger">
-		<xs:maxInclusive value="-1" id="negativeInteger.maxInclusive"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="long" id="long">
-	 <xs:annotation>
-		<xs:appinfo>
-		  <hfp:hasProperty name="bounded" value="true"/>
-		  <hfp:hasProperty name="cardinality" value="finite"/>
-		</xs:appinfo>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#long"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:integer">
-		<xs:minInclusive value="-9223372036854775808" id="long.minInclusive"/>
-		<xs:maxInclusive value="9223372036854775807" id="long.maxInclusive"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="int" id="int">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#int"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:long">
-		<xs:minInclusive value="-2147483648" id="int.minInclusive"/>
-		<xs:maxInclusive value="2147483647" id="int.maxInclusive"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="short" id="short">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#short"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:int">
-		<xs:minInclusive value="-32768" id="short.minInclusive"/>
-		<xs:maxInclusive value="32767" id="short.maxInclusive"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="byte" id="byte">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#byte"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:short">
-		<xs:minInclusive value="-128" id="byte.minInclusive"/>
-		<xs:maxInclusive value="127" id="byte.maxInclusive"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="nonNegativeInteger" id="nonNegativeInteger">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#nonNegativeInteger"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:integer">
-		<xs:minInclusive value="0" id="nonNegativeInteger.minInclusive"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="unsignedLong" id="unsignedLong">
-	 <xs:annotation>
-		<xs:appinfo>
-		  <hfp:hasProperty name="bounded" value="true"/>
-		  <hfp:hasProperty name="cardinality" value="finite"/>
-		</xs:appinfo>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#unsignedLong"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:nonNegativeInteger">
-		<xs:maxInclusive value="18446744073709551615"
-		  id="unsignedLong.maxInclusive"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="unsignedInt" id="unsignedInt">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#unsignedInt"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:unsignedLong">
-		<xs:maxInclusive value="4294967295"
-		  id="unsignedInt.maxInclusive"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="unsignedShort" id="unsignedShort">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#unsignedShort"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:unsignedInt">
-		<xs:maxInclusive value="65535"
-		  id="unsignedShort.maxInclusive"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="unsignedByte" id="unsignedByte">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#unsignedByte"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:unsignedShort">
-		<xs:maxInclusive value="255" id="unsignedByte.maxInclusive"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
-  <xs:simpleType name="positiveInteger" id="positiveInteger">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#positiveInteger"/>
-	 </xs:annotation>
-	 <xs:restriction base="xs:nonNegativeInteger">
-		<xs:minInclusive value="1" id="positiveInteger.minInclusive"/>
-	 </xs:restriction>
-  </xs:simpleType>
-
- <xs:simpleType name="derivationControl">
-  <xs:annotation>
-	<xs:documentation>
-	A utility type, not for public use</xs:documentation>
-  </xs:annotation>
-  <xs:restriction base="xs:NMTOKEN">
-	<xs:enumeration value="substitution"/>
-	<xs:enumeration value="extension"/>
-	<xs:enumeration value="restriction"/>
-	<xs:enumeration value="list"/>
-	<xs:enumeration value="union"/>
-  </xs:restriction>
- </xs:simpleType>
-
- <xs:group name="simpleDerivation">
-  <xs:choice>
-	 <xs:element ref="xs:restriction"/>
-	 <xs:element ref="xs:list"/>
-	 <xs:element ref="xs:union"/>
-  </xs:choice>
- </xs:group>
-
- <xs:simpleType name="simpleDerivationSet">
-  <xs:annotation>
-	<xs:documentation>
-	#all or (possibly empty) subset of {restriction, union, list}
-	</xs:documentation>
-	<xs:documentation>
-	A utility type, not for public use</xs:documentation>
-  </xs:annotation>
-  <xs:union>
-	<xs:simpleType>	 
-	 <xs:restriction base="xs:token">
-	  <xs:enumeration value="#all"/>
-	 </xs:restriction>
-	</xs:simpleType>
-	<xs:simpleType>
-	 <xs:restriction base="xs:derivationControl">
-	  <xs:enumeration value="list"/>
-	  <xs:enumeration value="union"/>
-	  <xs:enumeration value="restriction"/>
-	 </xs:restriction>
-	</xs:simpleType>
-  </xs:union>
- </xs:simpleType>
-
-  <xs:complexType name="simpleType" abstract="true">
-	 <xs:complexContent>
-		<xs:extension base="xs:annotated">
-		  <xs:group ref="xs:simpleDerivation"/>
-		  <xs:attribute name="final" type="xs:simpleDerivationSet"/>
-		  <xs:attribute name="name" type="xs:NCName">
-			 <xs:annotation>
-				<xs:documentation>
-				  Can be restricted to required or forbidden
-				</xs:documentation>
-			 </xs:annotation>
-		  </xs:attribute>
-		</xs:extension>
-	 </xs:complexContent>
-  </xs:complexType>
-
-  <xs:complexType name="topLevelSimpleType">
-	 <xs:complexContent>
-		<xs:restriction base="xs:simpleType">
-		  <xs:sequence>
-			 <xs:element ref="xs:annotation" minOccurs="0"/>
-			 <xs:group ref="xs:simpleDerivation"/>
-		  </xs:sequence>
-		  <xs:attribute name="name" use="required"
-				 type="xs:NCName">
-			 <xs:annotation>
-				<xs:documentation>
-				  Required at the top level
-				</xs:documentation>
-			 </xs:annotation>
-		  </xs:attribute>
-		 <xs:anyAttribute namespace="##other" processContents="lax"/>
-		</xs:restriction>
-	 </xs:complexContent>
-  </xs:complexType>
-
-  <xs:complexType name="localSimpleType">
-	 <xs:complexContent>
-		<xs:restriction base="xs:simpleType">
-		  <xs:sequence>
-			 <xs:element ref="xs:annotation" minOccurs="0"/>
-			 <xs:group ref="xs:simpleDerivation"/>
-		  </xs:sequence>
-		  <xs:attribute name="name" use="prohibited">
-			 <xs:annotation>
-				<xs:documentation>
-				  Forbidden when nested
-				</xs:documentation>
-			 </xs:annotation>
-		  </xs:attribute>   
-		  <xs:attribute name="final" use="prohibited"/>
-		 <xs:anyAttribute namespace="##other" processContents="lax"/>
-		</xs:restriction>
-	 </xs:complexContent>
-  </xs:complexType>
-
-  <xs:element name="simpleType" type="xs:topLevelSimpleType" id="simpleType">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#element-simpleType"/>
-	 </xs:annotation>
-  </xs:element>
-
-  <xs:group name="facets">
-	<xs:annotation>
-	 <xs:documentation>
-		 We should use a substitution group for facets, but
-		 that's ruled out because it would allow users to
-		 add their own, which we're not ready for yet.
-	 </xs:documentation>
-	</xs:annotation>
-	<xs:choice>
-	 <xs:element ref="xs:minExclusive"/>
-	 <xs:element ref="xs:minInclusive"/>
-	 <xs:element ref="xs:maxExclusive"/>
-	 <xs:element ref="xs:maxInclusive"/>
-	 <xs:element ref="xs:totalDigits"/>
-	 <xs:element ref="xs:fractionDigits"/>
-	 <xs:element ref="xs:length"/>
-	 <xs:element ref="xs:minLength"/>
-	 <xs:element ref="xs:maxLength"/>
-	 <xs:element ref="xs:enumeration"/>
-	 <xs:element ref="xs:whiteSpace"/>
-	 <xs:element ref="xs:pattern"/>
-	</xs:choice>
-  </xs:group>
-
-  <xs:group name="simpleRestrictionModel">
-	<xs:sequence>
-	 <xs:element name="simpleType" type="xs:localSimpleType" minOccurs="0"/>
-	 <xs:group ref="xs:facets" minOccurs="0" maxOccurs="unbounded"/>
-	</xs:sequence>
-  </xs:group>
-
-  <xs:element name="restriction" id="restriction">
-	<xs:complexType>
-	 <xs:annotation>
-		<xs:documentation
-					 source="http://www.w3.org/TR/xmlschema-2/#element-restriction">
-			 base attribute and simpleType child are mutually
-			 exclusive, but one or other is required
-		  </xs:documentation>
-		</xs:annotation>
-		<xs:complexContent>
-		  <xs:extension base="xs:annotated">
-			<xs:group ref="xs:simpleRestrictionModel"/>
-			<xs:attribute name="base" type="xs:QName" use="optional"/>
-		  </xs:extension>
-		</xs:complexContent>
-	 </xs:complexType>
-  </xs:element>
-
-  <xs:element name="list" id="list">
-	<xs:complexType>
-	 <xs:annotation>
-		<xs:documentation
-					 source="http://www.w3.org/TR/xmlschema-2/#element-list">
-			 itemType attribute and simpleType child are mutually
-			 exclusive, but one or other is required
-		  </xs:documentation>
-		</xs:annotation>
-		<xs:complexContent>
-		  <xs:extension base="xs:annotated">
-			 <xs:sequence>
-				<xs:element name="simpleType" type="xs:localSimpleType"
-					 minOccurs="0"/>
-			 </xs:sequence>
-			 <xs:attribute name="itemType" type="xs:QName" use="optional"/>
-		  </xs:extension>
-		</xs:complexContent>
-	 </xs:complexType>
-  </xs:element>
-
-  <xs:element name="union" id="union">
-	<xs:complexType>
-	 <xs:annotation>
-		<xs:documentation
-					 source="http://www.w3.org/TR/xmlschema-2/#element-union">
-			 memberTypes attribute must be non-empty or there must be
-			 at least one simpleType child
-		  </xs:documentation>
-		</xs:annotation>
-		<xs:complexContent>
-		  <xs:extension base="xs:annotated">
-			 <xs:sequence>
-				<xs:element name="simpleType" type="xs:localSimpleType"
-					 minOccurs="0" maxOccurs="unbounded"/>
-			 </xs:sequence>
-			 <xs:attribute name="memberTypes" use="optional">
-				<xs:simpleType>
-				  <xs:list itemType="xs:QName"/>
-				</xs:simpleType>
-			 </xs:attribute>
-		  </xs:extension>
-		</xs:complexContent>
-	 </xs:complexType>
-  </xs:element>
-  
-  <xs:complexType name="facet">
-	 <xs:complexContent>
-		<xs:extension base="xs:annotated">
-		  <xs:attribute name="value" use="required"/>
-		  <xs:attribute name="fixed" type="xs:boolean" use="optional"
-							 default="false"/>
-		</xs:extension>
-	 </xs:complexContent>
-  </xs:complexType>
- 
- <xs:complexType name="noFixedFacet">
-  <xs:complexContent>
-	<xs:restriction base="xs:facet">
-	 <xs:sequence>
-	  <xs:element ref="xs:annotation" minOccurs="0"/>
-	 </xs:sequence>
-	 <xs:attribute name="fixed" use="prohibited"/>
-	 <xs:anyAttribute namespace="##other" processContents="lax"/>
-	</xs:restriction>
-  </xs:complexContent>
- </xs:complexType>
-
-  <xs:element name="minExclusive" id="minExclusive" type="xs:facet">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#element-minExclusive"/>
-	 </xs:annotation>
-  </xs:element>
-  <xs:element name="minInclusive" id="minInclusive" type="xs:facet">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#element-minInclusive"/>
-	 </xs:annotation>
-  </xs:element>
-
-  <xs:element name="maxExclusive" id="maxExclusive" type="xs:facet">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#element-maxExclusive"/>
-	 </xs:annotation>
-  </xs:element>
-  <xs:element name="maxInclusive" id="maxInclusive" type="xs:facet">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#element-maxInclusive"/>
-	 </xs:annotation>
-  </xs:element>
-
-  <xs:complexType name="numFacet">
-	 <xs:complexContent>
-		<xs:restriction base="xs:facet">
-		 <xs:sequence>
-			<xs:element ref="xs:annotation" minOccurs="0"/>
-		 </xs:sequence>
-		 <xs:attribute name="value" type="xs:nonNegativeInteger" use="required"/>
-		 <xs:anyAttribute namespace="##other" processContents="lax"/>
-		</xs:restriction>
-	 </xs:complexContent>
-  </xs:complexType>
-
-  <xs:element name="totalDigits" id="totalDigits">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#element-totalDigits"/>
-	 </xs:annotation>
-	 <xs:complexType>
-		<xs:complexContent>
-		  <xs:restriction base="xs:numFacet">
-			 <xs:sequence>
-				<xs:element ref="xs:annotation" minOccurs="0"/>
-			 </xs:sequence>
-			 <xs:attribute name="value" type="xs:positiveInteger" use="required"/>
-			<xs:anyAttribute namespace="##other" processContents="lax"/>
-		  </xs:restriction>
-		</xs:complexContent>
-	 </xs:complexType>
-  </xs:element>
-  <xs:element name="fractionDigits" id="fractionDigits" type="xs:numFacet">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#element-fractionDigits"/>
-	 </xs:annotation>
-  </xs:element>
-
-  <xs:element name="length" id="length" type="xs:numFacet">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#element-length"/>
-	 </xs:annotation>
-  </xs:element>
-  <xs:element name="minLength" id="minLength" type="xs:numFacet">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#element-minLength"/>
-	 </xs:annotation>
-  </xs:element>
-  <xs:element name="maxLength" id="maxLength" type="xs:numFacet">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#element-maxLength"/>
-	 </xs:annotation>
-  </xs:element>
-  
-  <xs:element name="enumeration" id="enumeration" type="xs:noFixedFacet">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#element-enumeration"/>
-	 </xs:annotation>
-  </xs:element>
-
-  <xs:element name="whiteSpace" id="whiteSpace">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#element-whiteSpace"/>
-	 </xs:annotation>
-	 <xs:complexType>
-		<xs:complexContent>
-		  <xs:restriction base="xs:facet">
-			 <xs:sequence>
-				<xs:element ref="xs:annotation" minOccurs="0"/>
-			 </xs:sequence>
-			 <xs:attribute name="value" use="required">
-				<xs:simpleType>
-				  <xs:restriction base="xs:NMTOKEN">
-					 <xs:enumeration value="preserve"/>
-					 <xs:enumeration value="replace"/>
-					 <xs:enumeration value="collapse"/>
-				  </xs:restriction>
-				</xs:simpleType>
-			 </xs:attribute>
-			<xs:anyAttribute namespace="##other" processContents="lax"/>
-		  </xs:restriction>
-		</xs:complexContent>
-	 </xs:complexType>
-  </xs:element>
-
-  <xs:element name="pattern" id="pattern" type="xs:noFixedFacet">
-	 <xs:annotation>
-		<xs:documentation
-		  source="http://www.w3.org/TR/xmlschema-2/#element-pattern"/>
-	 </xs:annotation>
-  </xs:element>
-
-</xs:schema>
diff --git a/python/libmumbl/xmml/external/xs3p-1/examples/address.xsd b/python/libmumbl/xmml/external/xs3p-1/examples/address.xsd
deleted file mode 100644
index 61456139d9f65c6e6cb778c62126b276a7189785..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/external/xs3p-1/examples/address.xsd
+++ /dev/null
@@ -1,55 +0,0 @@
-<schema targetNamespace="http://www.example.com/IPO"
-        xmlns="http://www.w3.org/2001/XMLSchema"
-        xmlns:ipo="http://www.example.com/IPO">
-
- <annotation>
-  <documentation xml:lang="en">
-   Addresses for International Purchase order schema
-   Copyright 2000 Example.com. All rights reserved.
-  </documentation>
- </annotation>
-
- <complexType name="Address">
-  <sequence>
-   <element name="name"   type="string"/>
-   <element name="street" type="string"/>
-   <element name="city"   type="string"/>
-  </sequence>
- </complexType>
-
- <complexType name="USAddress">
-  <complexContent>
-   <extension base="ipo:Address">
-    <sequence>
-     <element name="state" type="ipo:USState"/>
-     <element name="zip"   type="positiveInteger"/>
-    </sequence>
-   </extension>
-  </complexContent>
- </complexType>
-
- <complexType name="UKAddress">
-  <complexContent>
-   <extension base="ipo:Address">
-    <sequence>
-     <element name="postcode" type="ipo:UKPostcode"/>
-    </sequence>
-    <attribute name="exportCode" type="positiveInteger" fixed="1"/>
-   </extension>
-  </complexContent>
- </complexType>
-
- <!-- other Address derivations for more countries -->
-
- <simpleType name="USState">
-  <restriction base="string">
-   <enumeration value="AK"/>
-   <enumeration value="AL"/>
-   <enumeration value="AR"/>
-   <!-- and so on ... -->
-  </restriction>
- </simpleType>
-
- <!-- simple type definition for UKPostcode -->
-
-</schema>
\ No newline at end of file
diff --git a/python/libmumbl/xmml/external/xs3p-1/examples/build.xml b/python/libmumbl/xmml/external/xs3p-1/examples/build.xml
deleted file mode 100644
index 6e25f4a7fee201b7f2b8e1f7a61ca12e6bafbf6f..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/external/xs3p-1/examples/build.xml
+++ /dev/null
@@ -1,40 +0,0 @@
-<project name="TestAnt" default="all" basedir=".">
-	<description>Script to generate documentation for example schema files using Ant.</description>
-
-	<property name="original-loc" value="../.."/>
-	<property name="xslt-file" value="xs3p.xsl"/>
-	<property name="target-dir" value="ant-results"/>
-
-	<target name="all" description="Generates documentation for all *.xsd files.">
-      <xslt basedir="." destdir="${target-dir}"
-       extension=".html" style="${original-loc}/${xslt-file}">
-         <include name="*.xsd"/>
-      </xslt>
-	</target>
-
-	<target name="test-external-links" description="Test linking between schema files.">
-      <!-- Copy xslt file to local dir. -->
-      <copy file="${original-loc}/${xslt-file}" todir="${basedir}"/>
-      <!-- address.xsd -->
-      <xslt in="address.xsd" out="${target-dir}/address.xsd.html" style="${xslt-file}">
-         <param name="searchImportedSchemas" expression="true"/>
-         <param name="searchIncludedSchemas" expression="true"/>
-         <param name="linksFile" expression="links.xml"/>
-      </xslt>
-      <!-- ipo.xsd -->
-      <xslt in="ipo.xsd" out="${target-dir}/ipo.xsd.html" style="${xslt-file}">
-         <param name="searchImportedSchemas" expression="true"/>
-         <param name="searchIncludedSchemas" expression="true"/>
-         <param name="linksFile" expression="links.xml"/>
-      </xslt>
-      <!-- report.xsd -->
-      <xslt in="report.xsd" out="${target-dir}/report.xsd.html" style="${xslt-file}">
-         <param name="searchImportedSchemas" expression="true"/>
-         <param name="searchIncludedSchemas" expression="true"/>
-         <param name="linksFile" expression="links.xml"/>
-      </xslt>
-      <!-- Delete local copy of xslt file. -->
-      <delete file="${basedir}/${xslt-file}"/>
-	</target>
-
-</project>
diff --git a/python/libmumbl/xmml/external/xs3p-1/examples/ipo.xsd b/python/libmumbl/xmml/external/xs3p-1/examples/ipo.xsd
deleted file mode 100644
index 419416eaf550e1a6bc68fcd9860ee2199de4dc87..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/external/xs3p-1/examples/ipo.xsd
+++ /dev/null
@@ -1,59 +0,0 @@
-<schema targetNamespace="http://www.example.com/IPO"
-        xmlns="http://www.w3.org/2001/XMLSchema"
-        xmlns:ipo="http://www.example.com/IPO">
-
- <annotation>
-  <documentation xml:lang="en">
-   International Purchase order schema for Example.com
-   Copyright 2000 Example.com. All rights reserved.
-  </documentation>
- </annotation>
-
- <!-- include address constructs -->
- <include
-  schemaLocation="address.xsd"/>
-
- <element name="purchaseOrder" type="ipo:PurchaseOrderType"/>
-
- <element name="comment" type="string"/>
-
- <complexType name="PurchaseOrderType">
-  <sequence>
-   <element name="shipTo"     type="ipo:Address"/>
-   <element name="billTo"     type="ipo:Address"/>
-   <element ref="ipo:comment" minOccurs="0"/>
-   <element name="items"      type="ipo:Items"/>
-  </sequence>
-  <attribute name="orderDate" type="date"/>
- </complexType>
-
- <complexType name="Items">
-  <sequence>
-   <element name="item" minOccurs="0" maxOccurs="unbounded">
-    <complexType>
-     <sequence>
-      <element name="productName" type="string"/>
-      <element name="quantity">
-       <simpleType>
-        <restriction base="positiveInteger">
-         <maxExclusive value="100"/>
-        </restriction>
-       </simpleType>
-      </element>
-      <element name="USPrice"    type="decimal"/>
-      <element ref="ipo:comment" minOccurs="0"/>
-      <element name="shipDate"   type="date" minOccurs="0"/>
-     </sequence>
-     <attribute name="partNum" type="ipo:SKU" use="required"/>
-    </complexType>
-   </element>
-  </sequence>
- </complexType>
-
- <simpleType name="SKU">
-  <restriction base="string">
-   <pattern value="\d{3}-[A-Z]{2}"/>
-  </restriction>
- </simpleType>
-
-</schema>
\ No newline at end of file
diff --git a/python/libmumbl/xmml/external/xs3p-1/examples/links.xml b/python/libmumbl/xmml/external/xs3p-1/examples/links.xml
deleted file mode 100644
index 5bea6b8cab904cebce336e92303330f58cc43a3a..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/external/xs3p-1/examples/links.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0"?>
-<links xmlns="http://titanium.dstc.edu.au/xml/xs3p">
-	<schema file-location="address.xsd" docfile-location="address.xsd.html"/>
-	<schema file-location="ipo.xsd" docfile-location="ipo.xsd.html"/>
-	<schema file-location="report.xsd" docfile-location="report.xsd.html"/>
-</links>
\ No newline at end of file
diff --git a/python/libmumbl/xmml/external/xs3p-1/examples/po.xsd b/python/libmumbl/xmml/external/xs3p-1/examples/po.xsd
deleted file mode 100644
index 65ed861694a4e530eb3eadf5c7e826d86cd671e7..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/external/xs3p-1/examples/po.xsd
+++ /dev/null
@@ -1,66 +0,0 @@
-<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
-
- <xsd:annotation>
-  <xsd:documentation xml:lang="en">
-   Purchase order schema for Example.com.
-   Copyright 2000 Example.com. All rights reserved.
-  </xsd:documentation>
- </xsd:annotation>
-
- <xsd:element name="purchaseOrder" type="PurchaseOrderType"/>
-
- <xsd:element name="comment" type="xsd:string"/>
-
- <xsd:complexType name="PurchaseOrderType">
-  <xsd:sequence>
-   <xsd:element name="shipTo" type="USAddress"/>
-   <xsd:element name="billTo" type="USAddress"/>
-   <xsd:element ref="comment" minOccurs="0"/>
-   <xsd:element name="items"  type="Items"/>
-  </xsd:sequence>
-  <xsd:attribute name="orderDate" type="xsd:date"/>
- </xsd:complexType>
-
- <xsd:complexType name="USAddress">
-  <xsd:sequence>
-   <xsd:element name="name"   type="xsd:string"/>
-   <xsd:element name="street" type="xsd:string"/>
-   <xsd:element name="city"   type="xsd:string"/>
-   <xsd:element name="state"  type="xsd:string"/>
-   <xsd:element name="zip"    type="xsd:decimal"/>
-  </xsd:sequence>
-  <xsd:attribute name="country" type="xsd:NMTOKEN"
-     fixed="US"/>
- </xsd:complexType>
-
- <xsd:complexType name="Items">
-  <xsd:sequence>
-   <xsd:element name="item" minOccurs="0" maxOccurs="unbounded">
-    <xsd:complexType>
-     <xsd:sequence>
-      <xsd:element name="productName" type="xsd:string"/>
-      <xsd:element name="quantity">
-       <xsd:simpleType>
-        <xsd:restriction base="xsd:positiveInteger">
-         <xsd:maxExclusive value="100"/>
-        </xsd:restriction>
-       </xsd:simpleType>
-      </xsd:element>
-      <xsd:element name="USPrice"  type="xsd:decimal"/>
-      <xsd:element ref="comment"   minOccurs="0"/>
-      <xsd:element name="shipDate" type="xsd:date" minOccurs="0"/>
-     </xsd:sequence>
-     <xsd:attribute name="partNum" type="SKU" use="required"/>
-    </xsd:complexType>
-   </xsd:element>
-  </xsd:sequence>
- </xsd:complexType>
-
- <!-- Stock Keeping Unit, a code for identifying products -->
- <xsd:simpleType name="SKU">
-  <xsd:restriction base="xsd:string">
-   <xsd:pattern value="\d{3}-[A-Z]{2}"/>
-  </xsd:restriction>
- </xsd:simpleType>
-
-</xsd:schema>
\ No newline at end of file
diff --git a/python/libmumbl/xmml/external/xs3p-1/examples/recursion.xsd b/python/libmumbl/xmml/external/xs3p-1/examples/recursion.xsd
deleted file mode 100644
index cbe14b365599d584f35204f7f6a59bcbe3929084..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/external/xs3p-1/examples/recursion.xsd
+++ /dev/null
@@ -1,85 +0,0 @@
-<?xml version="1.0"?>
-<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com" targetNamespace="http://example.com">
-   <xsd:element name="x">
-      <xsd:simpleType>
-         <xsd:restriction base="X">
-            <xsd:enumeration value="abc"/>
-         </xsd:restriction>
-      </xsd:simpleType>
-   </xsd:element>
-   <xsd:simpleType name="X">
-      <xsd:restriction base="Z">
-         <xsd:enumeration value="abc"/>
-      </xsd:restriction>
-   </xsd:simpleType>
-   <xsd:simpleType name="Y">
-      <xsd:restriction base="X">
-         <xsd:enumeration value="abc"/>
-      </xsd:restriction>
-   </xsd:simpleType>
-   <xsd:simpleType name="Z">
-      <xsd:restriction base="Y">
-         <xsd:enumeration value="abc"/>
-      </xsd:restriction>
-   </xsd:simpleType>
-
-   <xsd:complexType name="A">
-      <xsd:complexContent>
-         <xsd:extension base="C">
-            <xsd:sequence>
-               <xsd:element name="a" type="xsd:string" minOccurs="1" maxOccurs="unbounded"/>
-            </xsd:sequence>
-         </xsd:extension>
-      </xsd:complexContent>
-   </xsd:complexType>
-   <xsd:complexType name="B">
-      <xsd:complexContent>
-         <xsd:extension base="A">
-            <xsd:sequence>
-               <xsd:element name="b" type="xsd:string" minOccurs="1" maxOccurs="unbounded"/>
-            </xsd:sequence>
-         </xsd:extension>
-      </xsd:complexContent>
-   </xsd:complexType>
-   <xsd:complexType name="C">
-      <xsd:complexContent>
-         <xsd:extension base="B">
-            <xsd:sequence>
-               <xsd:element name="c" type="xsd:string" minOccurs="1" maxOccurs="unbounded"/>
-            </xsd:sequence>
-         </xsd:extension>
-      </xsd:complexContent>
-   </xsd:complexType>
-
-   <xsd:group name="A">
-      <xsd:sequence>
-         <xsd:group ref="C"/>
-         <xsd:element name="a" type="xsd:string" minOccurs="1" maxOccurs="unbounded"/>
-      </xsd:sequence>
-   </xsd:group>
-   <xsd:group name="B">
-      <xsd:sequence>
-         <xsd:group ref="A"/>
-         <xsd:element name="b" type="xsd:string" minOccurs="1" maxOccurs="unbounded"/>
-      </xsd:sequence>
-   </xsd:group>
-   <xsd:group name="C">
-      <xsd:sequence>
-         <xsd:group ref="B"/>
-         <xsd:element name="c" type="xsd:string" minOccurs="1" maxOccurs="unbounded"/>
-      </xsd:sequence>
-   </xsd:group>
-
-   <xsd:attributeGroup name="A">
-      <xsd:attributeGroup ref="C"/>
-      <xsd:attribute name="a" type="xsd:string"/>
-   </xsd:attributeGroup>
-   <xsd:attributeGroup name="B">
-      <xsd:attributeGroup ref="A"/>
-      <xsd:attribute name="b" type="xsd:string"/>
-   </xsd:attributeGroup>
-   <xsd:attributeGroup name="C">
-      <xsd:attributeGroup ref="B"/>
-      <xsd:attribute name="c" type="xsd:string"/>
-   </xsd:attributeGroup>
-</xsd:schema>
\ No newline at end of file
diff --git a/python/libmumbl/xmml/external/xs3p-1/examples/report.xsd b/python/libmumbl/xmml/external/xs3p-1/examples/report.xsd
deleted file mode 100644
index 9cc6cca256e0881b66e78f8beea2e0ca45df2c1a..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/external/xs3p-1/examples/report.xsd
+++ /dev/null
@@ -1,84 +0,0 @@
-<?xml version="1.0"?>
-<schema targetNamespace="http://www.example.com/Report" xmlns="http://www.w3.org/2001/XMLSchema" xmlns:r="http://www.example.com/Report" xmlns:xipo="http://www.example.com/IPO" elementFormDefault="qualified">
-   <!-- for SKU -->
-   <import namespace="http://www.example.com/IPO" schemaLocation="ipo.xsd"/>
-
-   <annotation>
-      <documentation xml:lang="en">Report schema for Example.com
-	Copyright 2000 Example.com. All rights reserved.</documentation>
-   </annotation>
-
-   <element name="purchaseReport">
-      <complexType>
-         <sequence>
-            <element name="regions" type="r:RegionsType">
-               <keyref name="dummy2" refer="r:pNumKey">
-                  <selector xpath="r:zip/r:part"/>
-                  <field xpath="@number"/>
-               </keyref>
-            </element>
-            <element name="parts" type="r:PartsType"/>
-            <element ref="xipo:comment"/>
-         </sequence>
-         <attribute name="period" type="duration"/>
-         <attribute name="periodEnding" type="date"/>
-      </complexType>
-
-      <unique name="dummy1">
-         <selector xpath="r:regions/r:zip"/>
-         <field xpath="@code"/>
-      </unique>
-
-      <key name="pNumKey">
-         <selector xpath="r:parts/r:part"/>
-         <field xpath="@number"/>
-      </key>
-   </element>
-
-   <complexType name="RegionsType">
-      <sequence>
-         <element name="zip" maxOccurs="unbounded">
-            <complexType>
-               <sequence>
-                  <element name="part" maxOccurs="unbounded">
-                     <complexType>
-                        <complexContent>
-                           <restriction base="anyType">
-                              <attribute name="number" type="xipo:SKU"/>
-                              <attribute name="quantity" type="positiveInteger"/>
-                           </restriction>
-                        </complexContent>
-                     </complexType>
-                  </element>
-               </sequence>
-               <attribute name="code" type="positiveInteger"/>
-            </complexType>
-         </element>
-      </sequence>
-   </complexType>
-
-   <complexType name="PartsType">
-      <sequence>
-         <element name="part" maxOccurs="unbounded">
-            <complexType>
-               <simpleContent>
-                  <extension base="string">
-                     <attribute name="number" type="xipo:SKU"/>
-                  </extension>
-               </simpleContent>
-            </complexType>
-         </element>
-      </sequence>
-   </complexType>
-
-   <complexType name="ExtendedPurchaseOrderType">
-      <complexContent>
-         <extension base="xipo:PurchaseOrderType">
-            <sequence>
-               <element name="shipper" type="xipo:Address"/>
-            </sequence>
-            <attribute name="shipToDate" type="date"/>
-         </extension>
-      </complexContent>
-   </complexType>
-</schema>
\ No newline at end of file
diff --git a/python/libmumbl/xmml/external/xs3p-1/examples/test_msxsl.bat b/python/libmumbl/xmml/external/xs3p-1/examples/test_msxsl.bat
deleted file mode 100644
index 70f847ccc7bf8f17550019283e6214880c8a7676..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/external/xs3p-1/examples/test_msxsl.bat
+++ /dev/null
@@ -1,19 +0,0 @@
-set RESULTS_DIR=msxsl-results
-set LINKS_FILE=links.xml
-set XSLT_FILE=xs3p.xsl
-set ORIGINAL_XSLT_FILE=..\%XSLT_FILE%
-rem      Copy XSLT file to local directory
-copy %ORIGINAL_XSLT_FILE% .
-rem      Create results directory
-if not exist %RESULTS_DIR% mkdir %RESULTS_DIR%
-rem      Loop through schema files
-for %%f in (*.xsd) do msxsl %%f %XSLT_FILE% -t -o %RESULTS_DIR%\%%f.html
-rem      Test external links
-rem set XSD_FILE=address.xsd
-rem msxsl %XSD_FILE% %XSLT_FILE% -t -o %RESULTS_DIR%\%XSD_FILE%.html searchImportedSchemas=true searchIncludedSchemas=true linksFile=%LINKS_FILE%
-rem set XSD_FILE=ipo.xsd
-rem msxsl %XSD_FILE% %XSLT_FILE% -t -o %RESULTS_DIR%\%XSD_FILE%.html searchImportedSchemas=true searchIncludedSchemas=true linksFile=%LINKS_FILE%
-rem set XSD_FILE=report.xsd
-rem msxsl %XSD_FILE% %XSLT_FILE% -t -o %RESULTS_DIR%\%XSD_FILE%.html searchImportedSchemas=true searchIncludedSchemas=true linksFile=%LINKS_FILE%
-rem      Delete local copy of stylesheet
-del %XSLT_FILE%
diff --git a/python/libmumbl/xmml/external/xs3p-1/examples/test_xalanj.bat b/python/libmumbl/xmml/external/xs3p-1/examples/test_xalanj.bat
deleted file mode 100644
index 3a3f07694ef91e0db3b66cdb7944efb0d939649b..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/external/xs3p-1/examples/test_xalanj.bat
+++ /dev/null
@@ -1,19 +0,0 @@
-set RESULTS_DIR=xalanj-results
-set LINKS_FILE=links.xml
-set XSLT_FILE=xs3p.xsl
-set ORIGINAL_XSLT_FILE=..\%XSLT_FILE%
-rem      Copy XSLT file to local directory
-copy %ORIGINAL_XSLT_FILE% .
-rem      Create results directory
-if not exist %RESULTS_DIR% mkdir %RESULTS_DIR%
-rem      Loop through schema files
-for %%f in (*.xsd) do java org.apache.xalan.xslt.Process -IN %%f -XSL %XSLT_FILE% -OUT %RESULTS_DIR%\%%f.html
-rem      Test external links
-rem set XSD_FILE=address.xsd
-rem java org.apache.xalan.xslt.Process -IN %XSD_FILE% -XSL %XSLT_FILE% -OUT %RESULTS_DIR%\%XSD_FILE%.html -PARAM searchImportedSchemas true -PARAM searchIncludedSchemas true -PARAM linksFile %LINKS_FILE%
-rem set XSD_FILE=ipo.xsd
-rem java org.apache.xalan.xslt.Process -IN %XSD_FILE% -XSL %XSLT_FILE% -OUT %RESULTS_DIR%\%XSD_FILE%.html -PARAM searchImportedSchemas true -PARAM searchIncludedSchemas true -PARAM linksFile %LINKS_FILE%
-rem set XSD_FILE=report.xsd
-rem java org.apache.xalan.xslt.Process -IN %XSD_FILE% -XSL %XSLT_FILE% -OUT %RESULTS_DIR%\%XSD_FILE%.html -PARAM searchImportedSchemas true -PARAM searchIncludedSchemas true -PARAM linksFile %LINKS_FILE%
-rem      Delete local copy of stylesheet
-del %XSLT_FILE%
diff --git a/python/libmumbl/xmml/external/xs3p-1/examples/test_xsltproc.sh b/python/libmumbl/xmml/external/xs3p-1/examples/test_xsltproc.sh
deleted file mode 100644
index f2e3120a4080bbec8bf1ed4a1d01c2262c474d40..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/external/xs3p-1/examples/test_xsltproc.sh
+++ /dev/null
@@ -1,30 +0,0 @@
-#!bin/bash
-RESULTS_DIR=xsltproc-results
-LINKS_FILE=links.xml
-XSLT_FILE=xs3p.xsl
-ORIGINAL_XSLT_FILE=../$XSLT_FILE
-#    Copy XSLT file to local directory
-cp $ORIGINAL_XSLT_FILE .
-#    Create results directory
-if [ ! -d $RESULTS_DIR ] ;
-then
-  mkdir $RESULTS_DIR
-fi
-#    Loop through schema files
-for f in *.xsd
-do
-  echo "Generating documentation for: $f"
-  xsltproc --nonet --output $RESULTS_DIR/$f.html $XSLT_FILE $f
-done
-#    Test external links
-# XSD_FILE=address.xsd
-# echo "Generating documentation for: $XSD_FILE"
-# xsltproc --nonet --output $RESULTS_DIR/$XSD_FILE.html $XSLT_FILE $XSD_FILE
-# XSD_FILE=ipo.xsd
-# echo "Generating documentation for: $XSD_FILE"
-# xsltproc --param searchIncludedSchemas "'true'" --param linksFile "'links.xml'" --nonet --output $RESULTS_DIR/$XSD_FILE.html $XSLT_FILE $XSD_FILE
-# XSD_FILE=report.xsd
-# echo "Generating documentation for: $XSD_FILE"
-# xsltproc --param searchIncludedSchemas "'true'" --param linksFile "'links.xml'" --nonet --output $RESULTS_DIR/$XSD_FILE.html $XSLT_FILE $XSD_FILE
-#    Delete local copy of stylesheet
-rm $XSLT_FILE
diff --git a/python/libmumbl/xmml/external/xs3p-1/examples/xml.xsd b/python/libmumbl/xmml/external/xs3p-1/examples/xml.xsd
deleted file mode 100644
index 8e4d66656e79fea7e8b19bd8c14c17b48a021032..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/external/xs3p-1/examples/xml.xsd
+++ /dev/null
@@ -1,80 +0,0 @@
-<?xml version='1.0'?>
-<xs:schema targetNamespace="http://www.w3.org/XML/1998/namespace" xmlns:xs="http://www.w3.org/2001/XMLSchema" xml:lang="en">
-
- <xs:annotation>
-  <xs:documentation>
-   See http://www.w3.org/XML/1998/namespace.html and
-   http://www.w3.org/TR/REC-xml for information about this namespace.
-  </xs:documentation>
- </xs:annotation>
-
- <xs:annotation>
-  <xs:documentation>This schema defines attributes and an attribute group
-        suitable for use by
-        schemas wishing to allow xml:base, xml:lang or xml:space attributes
-        on elements they define.
-
-        To enable this, such a schema must import this schema
-        for the XML namespace, e.g. as follows:
-        &lt;schema . . .>
-         . . .
-         &lt;import namespace="http://www.w3.org/XML/1998/namespace"
-                    schemaLocation="http://www.w3.org/2001/03/xml.xsd"/>
-
-        Subsequently, qualified reference to any of the attributes
-        or the group defined below will have the desired effect, e.g.
-
-        &lt;type . . .>
-         . . .
-         &lt;attributeGroup ref="xml:specialAttrs"/>
- 
-         will define a type which will schema-validate an instance
-         element with any of those attributes</xs:documentation>
- </xs:annotation>
-
- <xs:annotation>
-  <xs:documentation>In keeping with the XML Schema WG's standard versioning
-   policy, this schema document will persist at
-   http://www.w3.org/2001/03/xml.xsd.
-   At the date of issue it can also be found at
-   http://www.w3.org/2001/xml.xsd.
-   The schema document at that URI may however change in the future,
-   in order to remain compatible with the latest version of XML Schema
-   itself.  In other words, if the XML Schema namespace changes, the version
-   of this document at
-   http://www.w3.org/2001/xml.xsd will change
-   accordingly; the version at
-   http://www.w3.org/2001/03/xml.xsd will not change.
-  </xs:documentation>
- </xs:annotation>
-
- <xs:attribute name="lang" type="xs:language">
-  <xs:annotation>
-   <xs:documentation>In due course, we should install the relevant ISO 2- and 3-letter
-         codes as the enumerated possible values . . .</xs:documentation>
-  </xs:annotation>
- </xs:attribute>
-
- <xs:attribute name="space" default="preserve">
-  <xs:simpleType>
-   <xs:restriction base="xs:NCName">
-    <xs:enumeration value="default"/>
-    <xs:enumeration value="preserve"/>
-   </xs:restriction>
-  </xs:simpleType>
- </xs:attribute>
-
- <xs:attribute name="base" type="xs:anyURI">
-  <xs:annotation>
-   <xs:documentation>See http://www.w3.org/TR/xmlbase/ for
-                     information about this attribute.</xs:documentation>
-  </xs:annotation>
- </xs:attribute>
-
- <xs:attributeGroup name="specialAttrs">
-  <xs:attribute ref="xml:base"/>
-  <xs:attribute ref="xml:lang"/>
-  <xs:attribute ref="xml:space"/>
- </xs:attributeGroup>
-
-</xs:schema>
diff --git a/python/libmumbl/xmml/external/xs3p-1/links.dtd b/python/libmumbl/xmml/external/xs3p-1/links.dtd
deleted file mode 100644
index c9f348ac45f37c7108f2fe70bfbc2f28a2113c3e..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/external/xs3p-1/links.dtd
+++ /dev/null
@@ -1,7 +0,0 @@
-<!ELEMENT links (schema)+>
-<!ATTLIST links 
-	xmlns CDATA #FIXED "http://titanium.dstc.edu.au/xml/xs3p">
-<!ELEMENT schema EMPTY>
-<!ATTLIST schema 
-	file-location CDATA #REQUIRED
-	docfile-location CDATA #REQUIRED>
\ No newline at end of file
diff --git a/python/libmumbl/xmml/external/xs3p-1/links.xsd b/python/libmumbl/xmml/external/xs3p-1/links.xsd
deleted file mode 100644
index 7928bc3ea4069138ddebef1b7e55650b11b481f4..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/external/xs3p-1/links.xsd
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0"?>
-<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:html="http://www.w3.org/1999/xhtml" xmlns="http://titanium.dstc.edu.au/xml/xs3p" targetNamespace="http://titanium.dstc.edu.au/xml/xs3p">
-   <xsd:element name="links">
-      <xsd:annotation>
-         <xsd:documentation>
-            <html:p>List of mappings from schema file locations (<html:code style="color:blue;">@file-location</html:code>) to their documentation file locations (<html:code style="color:blue;">@docfile-location</html:code>)</html:p>
-         </xsd:documentation>
-      </xsd:annotation>
-      <xsd:complexType>
-         <xsd:sequence>
-            <xsd:element name="schema" minOccurs="1" maxOccurs="unbounded">
-               <xsd:complexType>
-                  <xsd:attribute name="file-location" type="xsd:string" use="required"/>
-                  <xsd:attribute name="docfile-location" type="xsd:string" use="required"/>
-               </xsd:complexType>
-            </xsd:element>
-         </xsd:sequence>
-      </xsd:complexType>
-   </xsd:element>
-</xsd:schema>
\ No newline at end of file
diff --git a/python/libmumbl/xmml/external/xs3p-1/tests/recursive_groups.xsd b/python/libmumbl/xmml/external/xs3p-1/tests/recursive_groups.xsd
deleted file mode 100644
index ae245b49971f59162f654947720924ae88b92cc2..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/external/xs3p-1/tests/recursive_groups.xsd
+++ /dev/null
@@ -1,25 +0,0 @@
-<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
-<!-- XML Schema to test xs3p's handling of recursive groups
-     Submitted by Martin Beran -->
-
-<xsd:element name="ping">
-    <xsd:complexType>
-        <xsd:sequence>
-            <xsd:group ref="g"/>
-        </xsd:sequence>
-    </xsd:complexType>
-</xsd:element>
-
-<xsd:group name="g">
-    <xsd:sequence>
-        <xsd:element name="G">
-            <xsd:complexType>
-                <xsd:sequence>
-                    <xsd:group ref="g"/>
-                </xsd:sequence>
-            </xsd:complexType>
-        </xsd:element>
-    </xsd:sequence>
-</xsd:group>
-
-</xsd:schema>
diff --git a/python/libmumbl/xmml/external/xs3p-1/xs3p.xsl b/python/libmumbl/xmml/external/xs3p-1/xs3p.xsl
deleted file mode 100644
index 047b1f70f132d8b97199646979414f9dac71c8ec..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/external/xs3p-1/xs3p.xsl
+++ /dev/null
@@ -1,8520 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<!--
-  Copyright (C) DSTC Pty Ltd (ACN 052 372 577) 2002
- 
-  The software contained on this media is the property of the
-  DSTC Pty Ltd.  Use of this software is strictly in accordance
-  with the license agreement in the accompanying LICENSE file.
-  If your distribution of this software does not contain a
-  LICENSE file then you have no rights to use this software
-  in any manner and should contact DSTC at the address below
-  to determine an appropriate licensing arrangement.
- 
-      DSTC Pty Ltd
-      Level 7, General Purpose South 
-      The University of Queensland
-      QLD 4072 Australia 
-      Tel: +61 7 3365 4310
-      Fax: +61 7 3365 4311
-      Email: titanium_enquiries@dstc.edu.au
- 
-  This software is being provided "AS IS" without warranty of
-  any kind.  In no event shall DSTC Pty Ltd be liable for
-  damage of any kind arising out of or in connection with
-  the use or performance of this software.
--->
-<!-- 
-  File:
-     xs3p.xsl
-  Description:
-     Stylesheet that generates XHTML documentation, given an XML 
-     Schema document
-  Assumptions:
-     -Resulting documentation will only be displayed properly with 
-      the latest browsers that support XHTML and CSS. Older 
-      browsers are not supported.
-     -Assumed that XSD document conforms to the XSD recommendation.
-      No validity checking is done.
-  Constraints:
-     -Local schema components cannot contain two dashes in 
-      'documentation' elements within their 'annotation' element.
-      This is because the contents of those 'documentation' 
-      elements are displayed in a separate window using Javascript. 
-      This Javascript code is enclosed in comments, which do not
-      allow two dashes inside themselves.
-  Notes:
-     -Javascript code is placed within comments, even though in 
-      strict XHTML, JavaScript code should be placed within CDATA 
-      sections. This is because current browsers generate a syntax 
-      error if the page contains CDATA sections. Placing Javascript 
-      code within comments means that the code cannot contain two 
-      dashes.
-      (See 'PrintJSCode' named template.)
-  Stylesheet Sections:
-     -Global Parameters
-          Specify parameters that can be set externally to customise 
-          stylesheet
-     -Constants
-          Constants used by the stylesheet
-     -Main Document
-          Templates to generate the overall document and the top-level 
-          sections within it
-     -Hierarchy table
-          Templates for displaying type hierarchy for simple and 
-          complex types, and substitution group hierarchy for elements
-     -Properties table
-          Templates for displaying the properties of top-level schema 
-          components
-     -XML Instance Representation table
-          Templates for displaying how an XML instance conforming to 
-          the schema component would look like
-     -Schema Component Representation table
-          Templates for displaying the XML representation of the schema
-          component
-     -XML Pretty Printer
-          Templates for displaying arbitrary XML instances
-     -Handling Schema Component References
-          Templates for generating internal and external links
-     -General Utility Templates
-          General templates used by other templates in this stylesheet
-  To Do List:
-     -It is not clever when printing out element and attribute 
-      wildcards in the XML Instance Representation tables. It prints 
-      out all wildcards, rather than working out the actual wildcard 
-      is from multiple wildcard instances.
-     -Same as above for simple type constraints, e.g. it doesn't 
-      summarise multiple pattern constraints.
--->
-<xsl:stylesheet 
- xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
- xmlns="http://www.w3.org/1999/xhtml" 
- xmlns:html="http://www.w3.org/1999/xhtml" 
- xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
- xmlns:ppp="http://titanium.dstc.edu.au/xml/xs3p" 
- version="1.0" 
- exclude-result-prefixes="xsd ppp html">
-
-   <xsl:output 
-    method="xml" 
-    encoding="ISO-8859-1"
-    standalone="yes"
-    version="1.0"
-    doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN" 
-    doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" 
-    indent="yes"/>
-
-   <xsl:key name="type" match="/xsd:schema/xsd:complexType | /xsd:schema/xsd:simpleType | /xsd:schema/xsd:redefine/xsd:complexType | /xsd:schema/xsd:redefine/xsd:simpleType" use="@name" />
-   <xsl:key name="complexType" match="/xsd:schema/xsd:complexType | /xsd:schema/xsd:redefine/xsd:complexType" use="@name" />
-   <xsl:key name="simpleType" match="/xsd:schema/xsd:simpleType | /xsd:schema/xsd:redefine/xsd:simpleType" use="@name" />
-   <xsl:key name="attributeGroup" match="/xsd:schema/xsd:attributeGroup | /xsd:schema/xsd:redefine/xsd:attributeGroup" use="@name" />
-   <xsl:key name="group" match="/xsd:schema/xsd:group | /xsd:schema/xsd:redefine/xsd:group" use="@name" />
-   <xsl:key name="attribute" match="/xsd:schema/xsd:attribute" use="@name" />
-   <xsl:key name="element" match="/xsd:schema/xsd:element" use="@name" />
-
-   <!-- ******** Global Parameters ******** -->
-
-   <!-- Title of XHTML document. -->
-   <xsl:param name="title"></xsl:param>
-
-   <!-- If 'true', sorts the top-level schema components by type, 
-        then name. Otherwise, displays the components by the order that 
-        they appear in the schema. -->
-   <xsl:param name="sortByComponent">true</xsl:param>
-
-   <!-- If 'true', XHTML document uses JavaScript for added
-        functionality, such as pop-up windows and information-
-        hiding.
-        Otherwise, XHTML document does not use JavaScript. -->
-   <xsl:param name="useJavaScript">true</xsl:param>
-
-   <!-- If 'true', prints all super-types in the
-        type hierarchy box.
-        Otherwise, prints the parent type only in the
-        type hierarchy box. -->
-   <xsl:param name="printAllSuperTypes">true</xsl:param>
-
-   <!-- If 'true', prints all sub-types in the
-        type hierarchy box.
-        Otherwise, prints the direct sub-types only in the
-        type hierarchy box. -->
-   <xsl:param name="printAllSubTypes">true</xsl:param>
-
-   <!-- If 'true', prints out the Glossary section. -->
-   <xsl:param name="printGlossary">true</xsl:param>
-
-   <!-- If 'true', prints out the Legend section. -->
-   <xsl:param name="printLegend">true</xsl:param>
-
-   <!-- If 'true', prints prefix matching namespace of schema
-        components in XML Instance Representation tables. -->
-   <xsl:param name="printNSPrefixes">true</xsl:param>
-
-   <!-- If 'true', searches 'included' schemas for schema components 
-        when generating links and XML Instance Representation tables. -->
-   <xsl:param name="searchIncludedSchemas">false</xsl:param>
-
-   <!-- If 'true', searches 'imported' schemas for schema components 
-        when generating links and XML Instance Representation tables. -->
-   <xsl:param name="searchImportedSchemas">false</xsl:param>
-
-   <!-- File containing the mapping from file locations of external 
-        (e.g. included, imported, refined) schemas to file locations 
-        of their XHTML documentation. -->
-   <xsl:param name="linksFile"></xsl:param>
-  
-   <!-- Set the base URL for resolving links. -->
-   <xsl:param name="baseURL"></xsl:param>
-  
-   <!-- Uses an external CSS stylesheet rather than using 
-        internally-declared CSS properties. -->
-   <xsl:param name="externalCSSURL"></xsl:param>
-
-
-   <!-- ******** Constants ******** -->
-
-   <!-- XML Schema Namespace -->
-   <xsl:variable name="XSD_NS">http://www.w3.org/2001/XMLSchema</xsl:variable>
-
-   <!-- XML Namespace -->
-   <xsl:variable name="XML_NS">http://www.w3.org/XML/1998/namespace</xsl:variable>
-
-   <!-- Number of 'em' to indent from parent element's start tag to
-        child element's start tag -->
-   <xsl:variable name="ELEM_INDENT">1.5</xsl:variable>
-
-   <!-- Number of 'em' to indent from parent element's start tag to
-        attribute's tag -->
-   <xsl:variable name="ATTR_INDENT">0.5</xsl:variable>
-
-   <!-- Title to use if none provided -->
-   <xsl:variable name="DEFAULT_TITLE">XML Schema Documentation</xsl:variable>
-
-   <!-- Prefixes used for anchor names -->
-      <!-- Type definitions -->
-   <xsl:variable name="TYPE_PREFIX">type_</xsl:variable>
-      <!-- Attribute declarations -->
-   <xsl:variable name="ATTR_PREFIX">attribute_</xsl:variable>
-      <!-- Attribute group definitions -->
-   <xsl:variable name="ATTR_GRP_PREFIX">attributeGroup_</xsl:variable>
-      <!-- Complex type definitions -->
-   <xsl:variable name="CTYPE_PREFIX" select="$TYPE_PREFIX"/>
-      <!-- Element declarations -->
-   <xsl:variable name="ELEM_PREFIX">element_</xsl:variable>
-      <!-- Key definitions -->
-   <xsl:variable name="KEY_PREFIX">key_</xsl:variable>
-      <!-- Group definitions -->
-   <xsl:variable name="GRP_PREFIX">group_</xsl:variable>
-      <!-- Notations -->
-   <xsl:variable name="NOTA_PREFIX">notation_</xsl:variable>
-      <!-- Namespace declarations -->
-   <xsl:variable name="NS_PREFIX">ns_</xsl:variable>
-      <!-- Simple type definitions -->
-   <xsl:variable name="STYPE_PREFIX" select="$TYPE_PREFIX"/>
-      <!-- Glossary terms -->
-   <xsl:variable name="TERM_PREFIX">term_</xsl:variable>
-
-   <!-- The original schema needs to be stored because when
-        calculating links for references, the links have to be
-        relative to the original schema. See 'PrintCompRef'
-        template. -->
-   <xsl:variable name="ORIGINAL_SCHEMA" select="/xsd:schema"/>
-
-   <!-- ******** Main Document ******** -->
-
-   <!--
-     Main template that starts the process
-     -->
-   <xsl:template match="/xsd:schema">
-      <!-- Check that links file is provided if searching external
-           schemas for components. -->
-      <xsl:if test="$linksFile='' and (normalize-space(translate($searchIncludedSchemas, 'TRUE', 'true'))='true' or normalize-space(translate($searchImportedSchemas, 'TRUE', 'true'))='true')">
-         <xsl:call-template name="HandleError">
-            <xsl:with-param name="isTerminating">true</xsl:with-param>
-            <xsl:with-param name="errorMsg">
-'linksFile' variable must be provided if either 
-'searchIncludedSchemas' or 'searchImportedSchemas' is true.
-            </xsl:with-param>
-         </xsl:call-template>
-      </xsl:if>
-
-      <!-- Get title of document -->
-      <xsl:variable name="actualTitle">
-         <xsl:choose>
-            <xsl:when test="$title != ''">
-               <xsl:value-of select="$title"/>
-            </xsl:when>
-            <xsl:otherwise>
-               <xsl:value-of select="$DEFAULT_TITLE"/>
-            </xsl:otherwise>
-         </xsl:choose>
-      </xsl:variable>
-
-      <html>
-         <head>
-            <!-- Set title bar -->
-            <title><xsl:value-of select="$actualTitle"/></title>
-
-            <!-- Set content type -->
-            <meta http-equiv="Content-Type" content="text/xml; charset=iso-8859-1"/>
-
-            <!-- Set base URL to use in working out relative paths -->
-            <xsl:if test="$baseURL != ''">
-               <xsl:element name="base">
-                  <xsl:attribute name="href"><xsl:value-of select="$baseURL"/></xsl:attribute> 
-               </xsl:element>
-            </xsl:if>
-
-            <!-- Set CSS styles -->
-            <style type="text/css">
-               <xsl:choose>
-                  <!-- Use external CSS stylesheet -->
-                  <xsl:when test="$externalCSSURL != ''">
-                     <xsl:text>
-@import url(</xsl:text><xsl:value-of select="$externalCSSURL"/><xsl:text>);
-</xsl:text>
-                  </xsl:when>
-                  <!-- Use internal CSS styles -->
-                  <xsl:otherwise>
-                     <xsl:call-template name="DocumentCSSStyles"/>
-                  </xsl:otherwise>
-               </xsl:choose>
-            </style>
-
-            <!-- Add Javascript code to make the collapseable boxes work -->
-            <xsl:if test="normalize-space(translate($useJavaScript,'TRUE','true'))='true'">
-               <xsl:call-template name="PrintJSCode">
-                  <xsl:with-param name="code">
-                     <xsl:call-template name="DocumentJSCode"/>
-                  </xsl:with-param>
-               </xsl:call-template>
-            </xsl:if>
-         </head>
-         <body>
-            <!-- Title -->
-            <h1><a name="top"><xsl:value-of select="$actualTitle"/></a></h1>
-
-            <!-- Buttons for displaying printer-friendly version, and
-                 expanding and collapsing all boxes -->
-            <xsl:call-template name="GlobalControlButtons"/>
-
-            <!-- Section: Table of Contents -->
-            <h2>Table of Contents</h2>
-            <xsl:apply-templates select="." mode="toc"/>
-            <xsl:call-template name="SectionFooter"/>
-
-            <!-- Section: Schema Document Properties -->
-            <h2><a name="SchemaProperties">Schema Document Properties</a></h2>
-            <!-- Sub-section: Properties table -->
-            <xsl:apply-templates select="." mode="properties"/>
-            <!-- Sub-section: Namespace Legend -->
-            <h3>Declared Namespaces</h3>
-            <xsl:apply-templates select="." mode="namespaces"/>
-            <!-- Sub-section: Schema Component Representation table -->
-            <xsl:call-template name="SchemaComponentTable">
-               <xsl:with-param name="component" select="."/>
-            </xsl:call-template>
-            <xsl:call-template name="SectionFooter"/>
-
-            <!-- Section: Redefined Schema Components -->
-            <xsl:if test="xsd:redefine">
-               <h2><a name="Redefinitions">Redefined Schema Components</a></h2>
-               <xsl:apply-templates select="xsd:redefine/xsd:simpleType | xsd:redefine/xsd:complexType | xsd:redefine/xsd:attributeGroup | xsd:redefine/xsd:group" mode="topSection"/>
-            </xsl:if>
-
-            <!-- Sections: Top-level Schema Components -->
-            <xsl:choose>
-               <!-- Sort schema components -->
-               <xsl:when test="normalize-space(translate($sortByComponent,'TRUE','true'))='true'">
-                  <!-- Declarations -->
-                  <xsl:if test="xsd:attribute or xsd:element">
-                     <h2><a name="SchemaDeclarations">Global Declarations</a></h2>
-                     <xsl:apply-templates select="xsd:attribute | xsd:element" mode="topSection">
-                        <xsl:sort select="local-name(.)" order="ascending"/>
-                        <xsl:sort select="@name" order="ascending"/>
-                     </xsl:apply-templates>
-                  </xsl:if>
-                  <!-- Definitions -->
-                  <xsl:if test="xsd:attributeGroup or xsd:complexType or xsd:group or xsd:notation or xsd:simpleType">
-                     <h2><a name="SchemaDefinitions">Global Definitions</a></h2>
-                     <xsl:apply-templates select="xsd:attributeGroup | xsd:complexType | xsd:group | xsd:notation | xsd:simpleType" mode="topSection">
-                        <xsl:sort select="local-name(.)" order="ascending"/>
-                        <xsl:sort select="@name" order="ascending"/>
-                     </xsl:apply-templates>
-                  </xsl:if>
-               </xsl:when>
-               <!-- Display schema components as they occur -->
-               <xsl:otherwise>
-                  <h2><a name="SchemaComponents">Global Schema Components</a></h2>
-                  <xsl:apply-templates select="xsd:attribute | xsd:attributeGroup | xsd:complexType | xsd:element | xsd:group | xsd:notation | xsd:simpleType" mode="topSection"/>
-               </xsl:otherwise>
-            </xsl:choose>
-
-            <!-- Section: Legend -->
-            <xsl:if test="normalize-space(translate($printLegend,'TRUE','true'))='true'">
-               <div id="legend">
-                  <h2><a name="Legend">Legend</a></h2>
-                  <xsl:call-template name="Legend"/>
-                  <xsl:call-template name="SectionFooter"/>
-               </div>
-            </xsl:if>
-
-            <!-- Section: Glossary -->
-            <xsl:if test="normalize-space(translate($printGlossary,'TRUE','true'))='true'">
-               <div id="glossary">
-                  <h2><a name="Glossary">Glossary</a></h2>
-                  <xsl:call-template name="Glossary"/>
-                  <xsl:call-template name="SectionFooter"/>
-               </div>
-            </xsl:if>
-
-            <!-- Document Footer -->
-            <p class="footer">
-               <xsl:text>Generated by </xsl:text>
-               <a href="http://xml.fiforms.org/xs3p/">xs3p</a> (<a href="http://titanium.dstc.edu.au/xml/xs3p">old link</a>)
-               <xsl:text>.</xsl:text>
-               <xsl:if test="normalize-space(translate($useJavaScript,'TRUE','true'))='true'">
-                  <xsl:text> Last modified: </xsl:text>
-                  <xsl:call-template name="PrintJSCode">
-                     <xsl:with-param name="code">document.write(document.lastModified);</xsl:with-param>
-                  </xsl:call-template>
-               </xsl:if>
-            </p>
-         </body>
-      </html>
-   </xsl:template>
-
-   <!--
-     Prints out the table of Declared Namespaces for the
-     current schema.
-     -->
-   <xsl:template match="xsd:schema" mode="namespaces">
-      <table class="namespaces">
-         <tr>
-            <th>Prefix</th>
-            <th>Namespace</th>
-         </tr>
-         <!-- Default namespace (no prefix) -->
-         <xsl:if test="namespace::*[local-name(.)='']">
-            <xsl:variable name="ns" select="namespace::*[local-name(.)='']"/>
-            <tr>
-               <td>
-                  <a name="{$NS_PREFIX}">Default namespace</a>
-               </td>
-               <td>
-                  <xsl:choose>
-                     <xsl:when test="/xsd:schema/@targetNamespace and $ns=normalize-space(/xsd:schema/@targetNamespace)">
-                        <span class="targetNS">
-                           <xsl:value-of select="$ns"/>
-                        </span>
-                     </xsl:when>
-                     <xsl:otherwise>
-                        <xsl:value-of select="$ns"/>
-                     </xsl:otherwise>
-                  </xsl:choose>
-               </td>
-            </tr>
-         </xsl:if>
-         <!-- Namespaces with prefixes -->
-         <xsl:for-each select="namespace::*[local-name(.)!='']">
-            <xsl:variable name="prefix" select="local-name(.)"/>
-            <xsl:variable name="ns" select="."/>
-            <tr>
-               <td>
-                  <a name="{concat($NS_PREFIX, $prefix)}">
-                     <xsl:value-of select="$prefix"/>
-                  </a>
-               </td>
-               <td>
-                  <xsl:choose>
-                     <xsl:when test="/xsd:schema/@targetNamespace and $ns=normalize-space(/xsd:schema/@targetNamespace)">
-                        <span class="targetNS">
-                           <xsl:value-of select="$ns"/>
-                        </span>
-                     </xsl:when>
-                     <xsl:otherwise>
-                        <xsl:value-of select="$ns"/>
-                     </xsl:otherwise>
-                  </xsl:choose>
-               </td>
-            </tr>
-         </xsl:for-each>
-      </table>
-   </xsl:template>
-
-   <!--
-     Prints out the Table of Contents.
-     -->
-   <xsl:template match="xsd:schema" mode="toc">
-      <ul>
-         <!-- Section: Schema Document Properties -->
-         <li>
-            <a href="#SchemaProperties">Schema Document Properties</a>
-         </li>
-
-         <!-- Section: Redefined Schema Components -->
-         <xsl:if test="xsd:redefine">
-            <li>
-               <a href="#Redefinitions">Redefined Schema Components</a>
-            </li>
-         </xsl:if>
-
-         <!-- Sections: Top-level Schema Components -->
-         <xsl:choose>
-            <!-- Sort schema components -->
-            <xsl:when test="normalize-space(translate($sortByComponent,'TRUE','true'))='true'">
-               <!-- Declarations -->
-               <xsl:if test="xsd:attribute or xsd:element">
-                  <li><a href="#SchemaDeclarations">Global Declarations</a>
-                     <ul>
-                        <xsl:apply-templates select="xsd:attribute | xsd:element" mode="toc">
-                           <xsl:sort select="local-name(.)" order="ascending"/>
-                           <xsl:sort select="@name" order="ascending"/>
-                        </xsl:apply-templates>
-                     </ul>
-                  </li>
-               </xsl:if>
-               <!-- Definitions -->
-               <xsl:if test="xsd:attributeGroup or xsd:complexType or xsd:group or xsd:notation or xsd:simpleType">
-                  <li><a href="#SchemaDefinitions">Global Definitions</a>
-                     <ul>
-                        <xsl:apply-templates select="xsd:attributeGroup | xsd:complexType | xsd:group | xsd:notation | xsd:simpleType" mode="toc">
-                           <xsl:sort select="local-name(.)" order="ascending"/>
-                           <xsl:sort select="@name" order="ascending"/>
-                        </xsl:apply-templates>
-                     </ul>
-                  </li>
-               </xsl:if>
-            </xsl:when>
-            <!-- Display schema components in order as they appear in schema -->
-            <xsl:otherwise>
-               <li><a href="#SchemaComponents">Global Schema Components</a>
-                  <ul>
-                     <xsl:apply-templates select="xsd:attribute | xsd:attributeGroup | xsd:complexType | xsd:element | xsd:group | xsd:notation | xsd:simpleType" mode="toc"/>
-                  </ul>
-               </li>
-            </xsl:otherwise>
-         </xsl:choose>
-      </ul>
-
-      <!-- Section: Legend -->
-      <xsl:if test="normalize-space(translate($printLegend,'TRUE','true'))='true'">
-         <ul id="legendTOC" style="margin-top: 0em">
-            <li><a href="#Legend">Legend</a></li>
-         </ul>
-      </xsl:if>
-
-      <!-- Section: Glossary -->
-      <xsl:if test="normalize-space(translate($printGlossary,'TRUE','true'))='true'">
-         <ul id="glossaryTOC" style="margin-top: 0em">
-            <li><a href="#Glossary">Glossary</a></li>
-         </ul>
-      </xsl:if>
-   </xsl:template>
-
-   <!--
-     Prints out a link to a top-level schema component section in the
-     Table of Contents.
-     -->
-   <xsl:template match="xsd:*[@name]" mode="toc">
-      <xsl:variable name="componentID">
-         <xsl:call-template name="GetComponentID">
-            <xsl:with-param name="component" select="."/>
-         </xsl:call-template>
-      </xsl:variable>
-
-      <li>
-         <a href="#{$componentID}">
-            <xsl:call-template name="GetComponentDescription">
-               <xsl:with-param name="component" select="."/>
-            </xsl:call-template>
-            <xsl:text>: </xsl:text>
-            <strong><xsl:value-of select="@name"/></strong>
-         </a>
-      </li>
-   </xsl:template>
-
-   <!--
-     Prints out the section for a top-level schema component.
-     -->
-   <xsl:template match="xsd:*[@name]" mode="topSection">
-      <!-- Header -->
-      <xsl:call-template name="ComponentSectionHeader">
-         <xsl:with-param name="component" select="."/>
-      </xsl:call-template>
-
-      <!-- Hierarchy table (for types and elements) -->
-      <xsl:apply-templates select="." mode="hierarchy"/>
-
-      <!-- Properties table -->
-      <xsl:apply-templates select="." mode="properties"/>
-
-      <!-- XML Instance Representation table -->
-      <xsl:call-template name="SampleInstanceTable">
-         <xsl:with-param name="component" select="."/>
-      </xsl:call-template>
-
-      <!-- Schema Component Representation table -->
-      <xsl:call-template name="SchemaComponentTable">
-         <xsl:with-param name="component" select="."/>
-      </xsl:call-template>
-
-      <!-- Footer -->
-      <xsl:call-template name="SectionFooter"/>
-   </xsl:template>
-
-   <!--
-     Prints out the buttons that can expand and collapse all boxes in
-     this page.
-     -->
-   <xsl:template name="GlobalControlButtons">
-      <xsl:if test="normalize-space(translate($useJavaScript,'TRUE','true'))='true'">
-         <div style="float: right;">
-            <!-- Printer-friendly Version -->
-            <div id="printerControls" style="display:none;">
-               <input type="checkbox" onclick="displayMode(this.checked)"/>
-               <xsl:text>Printer-friendly Version</xsl:text>
-            </div>
-            <xsl:call-template name="PrintJSCode">
-               <xsl:with-param name="code">
-var pc = getElementObject("printerControls");
-if (pc != null) {
-   pc.style.display="block";
-}
-               </xsl:with-param>
-            </xsl:call-template>
-
-            <!-- Expand/Collapse All buttons -->
-            <div id="globalControls" style="display:none">
-               <strong>XML Instance Representation:</strong><br/>
-               <span style="margin-left: 1em; white-space: nowrap">
-                  <xsl:text>[ </xsl:text>
-                  <a href="javascript:void(0)" onclick="expandAll(xiBoxes)">Expand All</a>
-                  <xsl:text> | </xsl:text>
-                  <a href="javascript:void(0)" onclick="collapseAll(xiBoxes)">Collapse All</a>
-                  <xsl:text> ]</xsl:text>
-               </span><br/><br/>
-               <strong>Schema Component Representation:</strong><br/>
-               <span style="margin-left: 1em; white-space: nowrap">
-                  <xsl:text>[ </xsl:text>
-                  <a href="javascript:void(0)" onclick="expandAll(scBoxes)">Expand All</a>
-                  <xsl:text> | </xsl:text>
-                  <a href="javascript:void(0)" onclick="collapseAll(scBoxes)">Collapse All</a>
-                  <xsl:text> ]</xsl:text>
-               </span>
-            </div>
-            <xsl:call-template name="PrintJSCode">
-               <xsl:with-param name="code">
-var gc = getElementObject("globalControls");
-if (gc != null) {
-   gc.style.display="block";
-}
-               </xsl:with-param>
-            </xsl:call-template>
-         </div>
-      </xsl:if>
-   </xsl:template>
-
-   <!--
-     Prints out the section header of a top-level schema component.
-     Param(s):
-            component (Node) required
-              Top-level schema component
-     -->
-   <xsl:template name="ComponentSectionHeader">
-      <xsl:param name="component"/>
-
-      <xsl:variable name="componentID">
-         <xsl:call-template name="GetComponentID">
-            <xsl:with-param name="component" select="$component"/>
-         </xsl:call-template>
-      </xsl:variable>
-      <xsl:variable name="componentDescription">
-         <xsl:call-template name="GetComponentDescription">
-            <xsl:with-param name="component" select="$component"/>
-         </xsl:call-template>
-      </xsl:variable>
-      <xsl:variable name="componentTermRef">
-         <xsl:call-template name="GetComponentTermRef">
-            <xsl:with-param name="component" select="$component"/>
-         </xsl:call-template>
-      </xsl:variable>
-
-      <h3>
-         <!-- Description -->
-         <xsl:choose>
-            <xsl:when test="$componentTermRef != ''">
-               <xsl:call-template name="PrintGlossaryTermRef">
-                  <xsl:with-param name="code" select="$componentTermRef"/>
-                  <xsl:with-param name="term" select="$componentDescription"/>
-               </xsl:call-template>
-            </xsl:when>
-            <xsl:otherwise>
-               <xsl:value-of select="$componentDescription"/>
-            </xsl:otherwise>
-         </xsl:choose>
-         <xsl:text>: </xsl:text>
-         <!-- Name -->
-         <a name="{$componentID}" class="name">
-            <xsl:value-of select="$component/@name"/>
-         </a>
-      </h3>
-   </xsl:template>
-
-   <!-- 
-     Prints out footer for top-level sections. 
-     -->
-   <xsl:template name="SectionFooter">
-      <!-- Link to top of page-->
-      <div style="text-align: right; clear: both;"><a href="#top">top</a></div>
-      <hr/>
-   </xsl:template>
-
-   <!-- 
-     Java Script code required by the entire HTML document.
-     -->
-   <xsl:template name="DocumentJSCode">
-      <!-- Get all IDs of XML Instance Representation boxes
-            and place them in an array. -->
-      <xsl:text>/* IDs of XML Instance Representation boxes */
-</xsl:text>
-      <xsl:text>var xiBoxes = new Array(</xsl:text>
-      <xsl:for-each select="/xsd:schema/xsd:*[@name]">
-         <xsl:if test="position()!=1">
-            <xsl:text>, </xsl:text>
-         </xsl:if>
-         <xsl:text>'</xsl:text>
-         <xsl:call-template name="GetComponentID">
-            <xsl:with-param name="component" select="."/>
-         </xsl:call-template>
-         <xsl:text>_xibox'</xsl:text>
-      </xsl:for-each>
-      <xsl:text>);
-</xsl:text>
-      <!-- Get all IDs of Schema Component Representation boxes
-            and place them in an array. -->
-      <xsl:text>/* IDs of Schema Component Representation boxes */
-</xsl:text>
-      <xsl:text>var scBoxes = new Array('schema_scbox'</xsl:text>
-      <xsl:for-each select="/xsd:schema/xsd:*[@name]">
-         <xsl:text>, '</xsl:text>
-         <xsl:call-template name="GetComponentID">
-            <xsl:with-param name="component" select="."/>
-         </xsl:call-template>
-         <xsl:text>_scbox'</xsl:text>
-      </xsl:for-each>
-      <xsl:text>);
-</xsl:text>
-      <!-- Functions -->
-      <xsl:text>
-/**
- * Can get the ID of the button controlling
- * a collapseable box by concatenating
- * this string onto the ID of the box itself.
- */
-var B_SFIX = "_button";
-
-/**
- * Counter of documentation windows
- * Used to give each window a unique name
- */
-var windowCount = 0;
-
-/**
- * Returns an element in the current HTML document.
- * 
- * @param elementID Identifier of HTML element
- * @return               HTML element object
- */
-function getElementObject(elementID) {
-    var elemObj = null;
-    if (document.getElementById) {
-        elemObj = document.getElementById(elementID);
-    }
-    return elemObj;
-}             
-
-/**
- * Closes a collapseable box.
- * 
- * @param boxObj       Collapseable box
- * @param buttonObj Button controlling box
- */
-function closeBox(boxObj, buttonObj) {
-  if (boxObj == null || buttonObj == null) {
-     // Box or button not found
-  } else {
-     // Change 'display' CSS property of box
-     boxObj.style.display="none";
-
-     // Change text of button 
-     if (boxObj.style.display=="none") {
-        buttonObj.value=" + ";
-     }
-  }
-}
-
-/**
- * Opens a collapseable box.
- * 
- * @param boxObj       Collapseable box
- * @param buttonObj Button controlling box
- */
-function openBox(boxObj, buttonObj) {
-  if (boxObj == null || buttonObj == null) {
-     // Box or button not found
-  } else {
-     // Change 'display' CSS property of box
-     boxObj.style.display="block";
-
-     // Change text of button
-     if (boxObj.style.display=="block") {
-        buttonObj.value=" - ";
-     }
-  }
-}
-
-/**
- * Sets the state of a collapseable box.
- * 
- * @param boxID Identifier of box
- * @param open If true, box is "opened",
- *             Otherwise, box is "closed".
- */
-function setState(boxID, open) {
-  var boxObj = getElementObject(boxID);
-  var buttonObj = getElementObject(boxID+B_SFIX);
-  if (boxObj == null || buttonObj == null) {
-     // Box or button not found
-  } else if (open) {
-     openBox(boxObj, buttonObj);
-     // Make button visible
-     buttonObj.style.display="inline";
-  } else {
-     closeBox(boxObj, buttonObj);
-     // Make button visible
-     buttonObj.style.display="inline";
-  }
-}
-
-/**
- * Switches the state of a collapseable box, e.g.
- * if it's opened, it'll be closed, and vice versa.
- * 
- * @param boxID Identifier of box
- */
-function switchState(boxID) {
-  var boxObj = getElementObject(boxID);
-  var buttonObj = getElementObject(boxID+B_SFIX);
-  if (boxObj == null || buttonObj == null) {
-     // Box or button not found
-  } else if (boxObj.style.display=="none") {
-     // Box is closed, so open it
-     openBox(boxObj, buttonObj);
-  } else if (boxObj.style.display=="block") {
-     // Box is opened, so close it
-     closeBox(boxObj, buttonObj);
-  }
-}
-
-/**
- * Closes all boxes in a given list.
- * 
- * @param boxList Array of box IDs
- */
-function collapseAll(boxList) {
-  var idx;
-  for (idx = 0; idx &lt; boxList.length; idx++) {
-     var boxObj = getElementObject(boxList[idx]);
-     var buttonObj = getElementObject(boxList[idx]+B_SFIX);
-     closeBox(boxObj, buttonObj);
-  }
-}
-
-/**
- * Open all boxes in a given list.
- * 
- * @param boxList Array of box IDs
- */
-function expandAll(boxList) {
-  var idx;
-  for (idx = 0; idx &lt; boxList.length; idx++) {
-     var boxObj = getElementObject(boxList[idx]);
-     var buttonObj = getElementObject(boxList[idx]+B_SFIX);
-     openBox(boxObj, buttonObj);
-  }
-}
-
-/**
- * Makes all the control buttons of boxes appear.
- * 
- * @param boxList Array of box IDs
- */
-function viewControlButtons(boxList) {
-    var idx;
-    for (idx = 0; idx &lt; boxList.length; idx++) {
-        buttonObj = getElementObject(boxList[idx]+B_SFIX);
-        if (buttonObj != null) {
-            buttonObj.style.display = "inline";
-        }
-    }
-}
-
-/**
- * Makes all the control buttons of boxes disappear.
- * 
- * @param boxList Array of box IDs
- */
-function hideControlButtons(boxList) {
-    var idx;
-    for (idx = 0; idx &lt; boxList.length; idx++) {
-        buttonObj = getElementObject(boxList[idx]+B_SFIX);
-        if (buttonObj != null) {
-            buttonObj.style.display = "none";
-        }
-    }
-}
-
-/**
- * Sets the page for either printing mode
- * or viewing mode. In printing mode, the page
- * is made to be more readable when printing it out.
- * In viewing mode, the page is more browsable.
- *
- * @param isPrinterVersion If true, display in
- *                                 printing mode; otherwise, 
- *                                 in viewing mode
- */
-function displayMode(isPrinterVersion) {
-    var obj;
-    if (isPrinterVersion) {
-        // Hide global control buttons
-        obj = getElementObject("globalControls");
-        if (obj != null) {
-            obj.style.visibility = "hidden";
-        }
-        // Hide Legend
-        obj = getElementObject("legend");
-        if (obj != null) {
-            obj.style.display = "none";
-        }
-        obj = getElementObject("legendTOC");
-        if (obj != null) {
-            obj.style.display = "none";
-        }
-        // Hide Glossary
-        obj = getElementObject("glossary");
-        if (obj != null) {
-            obj.style.display = "none";
-        }
-        obj = getElementObject("glossaryTOC");
-        if (obj != null) {
-            obj.style.display = "none";
-        }
-
-        // Expand all XML Instance Representation tables
-        expandAll(xiBoxes);
-        // Expand all Schema Component Representation tables
-        expandAll(scBoxes);
-
-        // Hide Control buttons
-        hideControlButtons(xiBoxes);
-        hideControlButtons(scBoxes);
-    } else {
-        // View global control buttons
-        obj = getElementObject("globalControls");
-        if (obj != null) {
-            obj.style.visibility = "visible";
-        }
-        // View Legend
-        obj = getElementObject("legend");
-        if (obj != null) {
-            obj.style.display = "block";
-        }
-        obj = getElementObject("legendTOC");
-        if (obj != null) {
-            obj.style.display = "block";
-        }
-        // View Glossary
-        obj = getElementObject("glossary");
-        if (obj != null) {
-            obj.style.display = "block";
-        }
-        obj = getElementObject("glossaryTOC");
-        if (obj != null) {
-            obj.style.display = "block";
-        }
-
-        // Expand all XML Instance Representation tables
-        expandAll(xiBoxes);
-        // Collapse all Schema Component Representation tables
-        collapseAll(scBoxes);
-
-        // View Control buttons
-        viewControlButtons(xiBoxes);
-        viewControlButtons(scBoxes);
-    }
-}
-
-/**
- * Opens up a window displaying the documentation
- * of a schema component in the XML Instance
- * Representation table.
- * 
- * @param compDesc      Description of schema component 
- * @param compName      Name of schema component 
- * @param docTextArray Array containing the paragraphs 
- *                           of the new document
- */
-function viewDocumentation(compDesc, compName, docTextArray) {
-  var width = 400;
-  var height = 200;
-  var locX = 100;
-  var locY = 200;
-
-  /* Generate content */
-  var actualText = "&lt;html>";
-  actualText += "&lt;head>&lt;title>";
-  actualText += compDesc;
-  if (compName != '') {
-     actualText += ": " + compName;
-  }
-  actualText += "&lt;/title>&lt;/head>";
-  actualText += "&lt;body bgcolor=\"#FFFFEE\">";
-  // Title
-  actualText += "&lt;p style=\"font-family: Arial, sans-serif; font-size: 12pt; font-weight: bold; letter-spacing:1px;\">";
-  actualText += compDesc;
-  if (compName != '') {
-     actualText += ": &lt;span style=\"color:#006699\">" + compName + "&lt;/span>";
-  }
-  actualText += "&lt;/p>";
-  // Documentation
-  var idx;
-  for (idx = 0; idx &lt; docTextArray.length; idx++) {
-     actualText += "&lt;p style=\"font-family: Arial, sans-serif; font-size: 10pt;\">" + docTextArray[idx] + "&lt;/p>";
-  }
-  // Link to close window
-  actualText += "&lt;a href=\"javascript:void(0)\" onclick=\"window.close();\" style=\"font-family: Arial, sans-serif; font-size: 8pt;\">Close&lt;/a>";
-  actualText += "&lt;/body>&lt;/html>";
-
-  /* Display window */
-  windowCount++;
-  var docWindow = window.open("", "documentation"+windowCount, "toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable,alwaysRaised,dependent,titlebar=no,width="+width+",height="+height+",screenX="+locX+",left="+locX+",screenY="+locY+",top="+locY);
-  docWindow.document.write(actualText);
-}
-</xsl:text>
-   </xsl:template>
-
-   <!--
-     CSS properties for the entire HTML document.
-     -->
-   <xsl:template name="DocumentCSSStyles">
-      <xsl:text>
-/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
-/* More-configurable styles */
-
-/******** General ********/
-
-/* Document body */
-body {
-   color: Black;
-   background-color: White;
-   font-family: Arial, sans-serif;
-   font-size: 10pt;
-}
-/* Horizontal rules */
-hr {
-   color: black;
-}
-/* Document title */
-h1 {
-   font-size: 18pt;
-   letter-spacing: 2px;
-   border-bottom: 1px #ccc solid;
-   padding-top: 5px;
-   padding-bottom: 5px;
-}
-/* Main section headers */
-h2 {
-   font-size: 14pt;
-   letter-spacing: 1px;
-}
-/* Sub-section headers */
-h3, h3 a, h3 span {
-   font-size: 12pt;
-   font-weight: bold;
-   color: black;
-}
-/* Table displaying the properties of the schema components or the
-   schema document itself */
-table.properties th, table.properties th a {
-   color: black;
-   background-color: #F99; /* Pink */
-}
-table.properties td {
-   background-color: #eee; /* Gray */
-}
-
-
-/******** Table of Contents Section ********/
-
-/* Controls for switching between printing and viewing modes */
-div#printerControls {
-   color: #963; /* Orange-brown */
-}
-/* Controls that can collapse or expand all XML Instance
-   Representation and Schema Component Representation boxes */
-div#globalControls {
-   border: 2px solid #999;
-}
-
-
-/******** Schema Document Properties Section ********/
-
-/* Table displaying the namespaces declared in the schema */
-table.namespaces th {
-   background-color: #ccc;
-}
-table.namespaces td {
-   background-color: #eee;
-}
-/* Target namespace of the schema */
-span.targetNS {
-   color: #06C;
-   font-weight: bold;
-}
-
-
-/******** Schema Components' Sections ********/
-
-/* Name of schema component */
-.name {
-   color: #F93; /* Orange */
-}
-
-/* Hierarchy table */
-table.hierarchy {
-   border: 2px solid #999; /* Gray */
-}
-
-/* XML Instance Representation table */
-div.sample div.contents {
-   border: 2px dashed black;
-}
-
-/* Schema Component Representation table */
-div.schemaComponent div.contents {
-   border: 2px black solid;
-}
-
-
-/******** Glossary Section ********/
-
-/* Glossary Terms */
-.glossaryTerm {
-   color: #036; /* Blue */
-}
-
-
-/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
-/* Printer-version styles */
-
-@media print {
-
-/* Ensures that controls are hidden when printing */
-div#printerControls {
-   visibility: hidden;
-}
-div#globalControls {
-   visibility: hidden;
-}
-#legend {
-   display: none;
-}
-#legendTOC {
-   display: none;
-}
-#glossary {
-   display: none;
-}
-#glossaryTOC {
-   display: none;
-}
-
-}
-
-/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
-/* Base styles */
-
-/******** General ********/
-
-/* Unordered lists */
-ul {
-   margin-left: 1.5em;
-   margin-bottom: 0em;
-}
-/* Tables */
-table {
-   margin-top: 10px;
-   margin-bottom: 10px;
-   margin-left: 2px;
-   margin-right: 2px;
-}
-table th, table td {
-   font-size: 10pt;
-   vertical-align: top;
-   padding-top: 3px;
-   padding-bottom: 3px;
-   padding-left: 10px;
-   padding-right: 10px;
-}
-table th {
-   font-weight: bold;
-   text-align: left;
-}
-/* Table displaying the properties of the schema components or the
-   schema document itself */
-table.properties {
-   width: 90%;
-}
-table.properties th {
-   width: 30%;
-}
-/* Boxes that can make its content appear and disappear*/
-div.box {
-   margin: 1em;
-}
-   /* Box caption */
-div.box span.caption {
-   font-weight: bold;
-}
-   /* Button to open and close the box */
-div.box input.control {
-   width: 1.4em;
-   height: 1.4em;
-   text-align: center;
-   vertical-align: middle;
-   font-size: 11pt;
-}
-   /* Box contents */
-div.box div.contents {
-   margin-top: 3px;
-}
-
-
-/******** Table of Contents Section ********/
-
-/* Controls for switching between printing and viewing modes */
-div#printerControls {
-   white-space: nowrap;
-   font-weight: bold;
-   padding: 5px;
-   margin: 5px;
-}
-/* Controls that can collapse or expand all XML Instance
-   Representation and Schema Component Representation boxes */
-div#globalControls {
-   padding: 10px;
-   margin: 5px;
-}
-
-
-/******** Schema Document Properties Section ********/
-
-/* Table displaying the namespaces declared in the schema */
-table.namespaces th {
-}
-table.namespaces td {
-}
-/* Target namespace of the schema */
-span.targetNS {
-}
-
-
-/******** Schema Components' Sections ********/
-
-/* Name of schema component */
-.name {
-}
-
-/* Hierarchy table */
-table.hierarchy {
-   width: 90%;
-}
-table.hierarchy th {
-   font-weight: normal;
-   font-style: italic;
-   width: 20%;
-}
-table.hierarchy th, table.hierarchy td {
-   padding: 5px;
-}
-
-/* XML Instance Representation table */
-div.sample {
-   width: 90%;
-}
-div.sample div.contents {
-   padding: 5px;
-   font-family: Courier New, sans-serif;
-   font-size: 10pt;
-}
-   /* Normal elements and attributes */
-div.sample div.contents, div.sample div.contents a {
-   color: black;
-}
-   /* Group Headers */
-div.sample div.contents .group, div.sample div.contents .group a {
-   color: #999; /* Light gray */
-}
-   /* Type Information */
-div.sample div.contents .type, div.sample div.contents .type a {
-   color: #999; /* Light gray */
-}
-   /* Occurrence Information */
-div.sample div.contents .occurs, div.sample div.contents .occurs a {
-   color: #999; /* Light gray */
-}
-   /* Fixed values */
-div.sample div.contents .fixed {
-   color: #063; /* Green */
-   font-weight: bold;
-}
-   /* Simple type constraints */
-div.sample div.contents .constraint, div.sample div.contents .constraint a {
-   color: #999; /* Light gray */
-}
-   /* Elements and attributes inherited from base type */
-div.sample div.contents .inherited, div.sample div.contents .inherited a {
-   color: #666; /* Dark gray */
-}
-   /* Elements and attributes added to or changed from base type */
-div.sample div.contents .newFields {
-   font-weight: bold;
-}
-   /* Other type of information */
-div.sample div.contents .other, div.sample div.contents .other a {
-   color: #369; /* Blue */
-   font-style: italic;
-}
-   /* Link to open up window displaying documentation */
-div.sample div.contents a.documentation {
-   text-decoration: none;
-   padding-left: 3px;
-   padding-right: 3px;
-   padding-top: 0px;
-   padding-bottom: 0px;
-   font-weight: bold;
-   font-size: 11pt;
-   background-color: #FFD;
-   color: #069;
-}
-   /* Invert colors when hovering over link to open up window 
-      displaying documentation */
-div.sample div.contents a.documentation:hover {
-   color: #FFD;
-   background-color: #069;
-}
-
-/* Schema Component Representation table */
-div.schemaComponent {
-   width: 90%;
-}
-div.schemaComponent div.contents {
-   font-family: Courier New, sans-serif;
-   font-size: 10pt;
-   padding: 5px;
-}
-   /* Syntax characters */
-div.schemaComponent div.contents {
-   color: #00f; /* blue */
-}
-   /* Element and attribute tags */
-div.schemaComponent div.contents .scTag {
-   color: #933; /* maroon */
-}
-   /* Element and attribute content */
-div.schemaComponent div.contents .scContent, div.schemaComponent div.contents .scContent a {
-   color: black;
-   font-weight: bold;
-}
-   /* Comments */
-div.schemaComponent div.contents .comment {
-   color: #999; /* Light gray */
-}
-
-/******** Legend Section ********/
-
-div#legend table, div#legend div {
-   margin-bottom: 3px;
-}
-div#legend div.hint {
-   color: #999; /* Light gray */
-   width: 90%;
-   margin-left: 1em;
-   margin-bottom: 2em;
-}
-
-
-/******** Glossary Section ********/
-
-/* Glossary Terms */
-.glossaryTerm {
-   font-weight: bold;
-}
-
-
-/******** Footer ********/
-
-.footer {
-   font-size: 8pt;
-}
-</xsl:text>
-   </xsl:template>
-
-   <!--
-     Print outs a legend describing the meaning of colors, bold items,
-     etc. in the top-level sections.
-     -->
-   <xsl:template name="Legend">
-      <!-- Header -->
-      <div style="float: left; width: 15em;">
-         <h3 style="margin-bottom: 0px;">Complex Type:</h3>
-         <div class="hint" style="margin-left: 0em;">Schema Component Type</div>
-      </div>
-      <div style="float: left; width: 15em;">
-         <h3 style="margin-bottom: 0px;"><span class="name">AusAddress</span></h3>
-         <div class="hint" style="margin-left: 0em;">Schema Component Name</div>
-      </div>
-
-      <!-- Hierarchy Table -->
-      <table class="hierarchy" style="clear : both">
-         <tr>
-            <xsl:choose>
-               <xsl:when test="normalize-space(translate($printAllSuperTypes, 'TRUE', 'true'))='true'">
-                  <th>Super-types:</th>
-                  <td>
-                     <span class="type" style="color: #0000FF; text-decoration:underline;">Address</span>
-                     <xsl:text> &lt; </xsl:text>
-                     <span class="current">AusAddress</span>
-                     <xsl:text> (by extension)</xsl:text>
-                  </td>
-               </xsl:when>
-               <xsl:otherwise>
-                  <th>Parent type:</th>
-                  <td>
-                     <span class="type" style="color: #0000FF; text-decoration:underline;">Address</span>
-                     <xsl:text> (derivation method: extension)</xsl:text>
-                  </td>
-               </xsl:otherwise>
-            </xsl:choose>
-         </tr>
-         <tr>
-            <xsl:choose>
-               <xsl:when test="normalize-space(translate($printAllSubTypes, 'TRUE', 'true'))='true'">
-                  <th>Sub-types:</th>
-                  <td>
-                     <ul>
-                        <li>
-                           <span class="type" style="color: #0000FF; text-decoration:underline;">QLDAddress</span>
-                           <xsl:text> (by restriction)</xsl:text>
-                        </li>
-                     </ul>
-                  </td>
-               </xsl:when>
-               <xsl:otherwise>
-                  <th>Direct sub-types:</th>
-                  <td>
-                     <ul>
-                        <li>
-                           <span class="type" style="color: #0000FF; text-decoration:underline;">QLDAddress</span>
-                           <xsl:text> (by restriction)</xsl:text>
-                        </li>
-                     </ul>
-                  </td>
-               </xsl:otherwise>
-            </xsl:choose>
-         </tr>
-      </table>
-      <div class="hint">If this schema component is a type definition, its type hierarchy is shown in a gray-bordered box.</div>
-
-      <!-- Properties Table -->
-      <table class="properties">
-         <tr>
-            <th>Name</th>
-            <td>AusAddress</td>
-         </tr>
-         <tr>
-            <th>
-               <a title="Look up 'Abstract' in glossary" href="#term_Abstract">Abstract</a>
-            </th>
-            <td>no</td>
-         </tr>
-      </table>
-      <div class="hint">The table above displays the properties of this schema component.</div>
-
-      <!-- XML Instance Representation Table -->
-      <div class="sample box">
-         <div>
-            <span class="caption">XML Instance Representation</span>
-         </div>
-         <div class="contents">
-            <span style="margin-left: 0em">&lt;...</span>
-            <span class="newFields">
-               <span> country="<span class="fixed">Australia</span>"</span>
-            </span>
-            <xsl:text>&gt; </xsl:text><br/>
-            <span style="margin-left: 1.5em" class="inherited">&lt;unitNo&gt; <span class="type">string</span> &lt;/unitNo&gt; <span class="occurs">[0..1]</span></span><br/>
-            <span style="margin-left: 1.5em" class="inherited">&lt;houseNo&gt; <span class="type">string</span> &lt;/houseNo&gt; <span class="occurs">[1]</span></span><br/>
-            <span style="margin-left: 1.5em" class="inherited">&lt;street&gt; <span class="type">string</span> &lt;/street&gt; <span class="occurs">[1]</span></span><br/>
-            <span class="group" style="margin-left: 1.5em">Start <a title="Look up 'Choice' in glossary" href="#term_Choice">Choice</a> <span class="occurs">[1]</span></span><br/>
-            <span style="margin-left: 3em" class="inherited">&lt;city&gt; <span class="type">string</span> &lt;/city&gt; <span class="occurs">[1]</span></span><br/>
-            <span style="margin-left: 3em" class="inherited">&lt;town&gt; <span class="type">string</span> &lt;/town&gt; <span class="occurs">[1]</span></span><br/>
-            <span class="group" style="margin-left: 1.5em">End Choice</span><br/>
-            <span class="newFields">
-            <span style="margin-left: 1.5em">&lt;state&gt; <span class="type" style="text-decoration:underline;">AusStates</span> &lt;/state&gt; <span class="occurs">[1]</span></span><br/>
-            <span style="margin-left: 1.5em">&lt;postcode&gt; <span class="constraint">string &lt;&lt;<em>pattern</em> = [1-9][0-9]{3}>></span> &lt;/postcode&gt; <span class="occurs">[1]</span>
-               <xsl:if test="normalize-space(translate($useJavaScript,'TRUE','true'))='true'">
-                  <a href="javascript:void(0)" title="View Documentation" class="documentation" onclick="docArray = new Array('Post code must be a four-digit number.'); viewDocumentation('Element', 'postcode', docArray);">?</a>
-               </xsl:if>
-               </span><br/>
-            </span>
-            <span style="margin-left: 0em">&lt;/...&gt;</span><br/>
-         </div>
-      </div>
-      <div class="hint">
-         <p>The XML Instance Representation table above shows the schema component's content as an XML instance.</p>
-         <ul>
-            <li>The minimum and maximum occurrence of elements and attributes are provided in square brackets, e.g. [0..1].</li>
-            <li>Model group information are shown in gray, e.g. Start Choice ... End Choice.</li>
-            <li>For type derivations, the elements and attributes that have been added to or changed from the base type's content are shown in <span style="font-weight: bold">bold</span>.</li>
-            <li>If an element/attribute has a fixed value, the fixed value is shown in green, e.g. country="Australia".</li>
-            <li>Otherwise, the type of the element/attribute is displayed.
-               <ul>
-                  <li>If the element/attribute's type is in the schema, a link is provided to it.</li>
-                  <!--<li>An <em>E</em> symbol is shown if the element/attribute's type is located in an external schema.</li>-->
-                  <li>For local simple type definitions, the constraints are displayed in angle brackets, e.g. &lt;&lt;<em>pattern</em> = [1-9][0-9]{3}>>.</li>
-               </ul>
-            </li>
-            <xsl:if test="normalize-space(translate($useJavaScript,'TRUE','true'))='true'">
-               <li>If a local element/attribute has documentation, it will be displayed in a window that pops up when the question mark inside the attribute or next to the element is clicked, e.g. &lt;postcode>.</li>
-            </xsl:if>
-         </ul>
-      </div>
-
-      <!-- Schema Component Representation Table -->
-      <div class="schemaComponent box">
-         <div>
-            <span class="caption">Schema Component Representation</span>
-         </div>
-         <div class="contents">
-            <span style="margin-left: 0em">&lt;<span class="scTag">complexType</span> <span class="scTag">name</span>="<span class="scContent">AusAddress</span>"&gt;</span><br/>
-            <span style="margin-left: 1.5em">&lt;<span class="scTag">complexContent</span>&gt;</span><br/>
-            <span style="margin-left: 3em">&lt;<span class="scTag">extension</span> <span class="scTag">base</span>="<span class="scContent"><span class="type" style="text-decoration:underline;">Address</span></span>"&gt;</span><br/>
-            <span style="margin-left: 4.5em">&lt;<span class="scTag">sequence</span>&gt;</span><br/>
-            <span style="margin-left: 6em">&lt;<span class="scTag">element</span> <span class="scTag">name</span>="<span class="scContent">state</span>" <span class="scTag">type</span>="<span class="scContent"><span class="type" style="text-decoration:underline;">AusStates</span></span>"/&gt;</span><br/>
-            <span style="margin-left: 6em">&lt;<span class="scTag">element</span> <span class="scTag">name</span>="<span class="scContent">postcode</span>"&gt;</span><br/>
-            <span style="margin-left: 7.5em">&lt;<span class="scTag">simpleType</span>&gt;</span><br/>
-            <span style="margin-left: 9em">&lt;<span class="scTag">restriction</span> <span class="scTag">base</span>="<span class="scContent"><span class="type">string</span></span>"&gt;</span><br/>
-            <span style="margin-left: 10.5em">&lt;<span class="scTag">pattern</span> <span class="scTag">value</span>="<span class="scContent">[1-9][0-9]{3}</span>"/&gt;</span><br/>
-            <span style="margin-left: 9em">&lt;/<span class="scTag">restriction</span>&gt;</span><br/>
-            <span style="margin-left: 7.5em">&lt;/<span class="scTag">simpleType</span>&gt;</span><br/>
-            <span style="margin-left: 6em">&lt;/<span class="scTag">element</span>&gt;</span><br/>
-            <span style="margin-left: 4.5em">&lt;/<span class="scTag">sequence</span>&gt;</span><br/>
-            <span style="margin-left: 4.5em">&lt;<span class="scTag">attribute</span> <span class="scTag">name</span>="<span class="scContent">country</span>" <span class="scTag">type</span>="<span class="scContent"><span class="type">string</span></span>" <span class="scTag">fixed</span>="<span class="scContent">Australia</span>"/&gt;</span><br/>
-            <span style="margin-left: 3em">&lt;/<span class="scTag">extension</span>&gt;</span><br/>
-            <span style="margin-left: 1.5em">&lt;/<span class="scTag">complexContent</span>&gt;</span><br/>
-            <span style="margin-left: 0em">&lt;/<span class="scTag">complexType</span>&gt;</span><br/>
-         </div>
-      </div>
-      <div class="hint">The Schema Component Representation table above displays the underlying XML representation of the schema component. (Annotations are not shown.)</div>
-   </xsl:template>
-
-   <!--
-     Print outs all terms for the glossary section.
-     -->
-   <xsl:template name="Glossary">
-      <xsl:call-template name="PrintGlossaryTerm">
-         <xsl:with-param name="code">Abstract</xsl:with-param>
-         <xsl:with-param name="term">Abstract</xsl:with-param>
-         <xsl:with-param name="description">
-            <xsl:text>(Applies to complex type definitions and element declarations).</xsl:text>
-            <xsl:text> An abstract element or complex type cannot used to validate an element instance.</xsl:text>
-            <xsl:text> If there is a reference to an abstract element, only element declarations that can substitute the abstract element can be used to validate the instance.</xsl:text>
-            <xsl:text> For references to abstract type definitions, only derived types can be used.</xsl:text>
-         </xsl:with-param>
-      </xsl:call-template>
-
-      <xsl:call-template name="PrintGlossaryTerm">
-         <xsl:with-param name="code">All</xsl:with-param>
-         <xsl:with-param name="term">All Model Group</xsl:with-param>
-         <xsl:with-param name="description">
-            <xsl:text>Child elements can be provided </xsl:text>
-            <em>
-               <xsl:text>in any order</xsl:text>
-            </em>
-            <xsl:text> in instances.</xsl:text>
-         </xsl:with-param>
-         <xsl:with-param name="link">http://www.w3.org/TR/xmlschema-1/#element-all</xsl:with-param>
-      </xsl:call-template>
-
-      <xsl:call-template name="PrintGlossaryTerm">
-         <xsl:with-param name="code">Choice</xsl:with-param>
-         <xsl:with-param name="term">Choice Model Group</xsl:with-param>
-         <xsl:with-param name="description">
-            <em>
-               <xsl:text>Only one</xsl:text>
-            </em>
-            <xsl:text> from the list of child elements and model groups can be provided in instances.</xsl:text>
-         </xsl:with-param>
-         <xsl:with-param name="link">http://www.w3.org/TR/xmlschema-1/#element-choice</xsl:with-param>
-      </xsl:call-template>
-
-      <xsl:call-template name="PrintGlossaryTerm">
-         <xsl:with-param name="code">CollapseWS</xsl:with-param>
-         <xsl:with-param name="term">Collapse Whitespace Policy</xsl:with-param>
-         <xsl:with-param name="description">Replace tab, line feed, and carriage return characters with space character (Unicode character 32). Then, collapse contiguous sequences of space characters into single space character, and remove leading and trailing space characters.</xsl:with-param>
-      </xsl:call-template>
-
-      <xsl:call-template name="PrintGlossaryTerm">
-         <xsl:with-param name="code">ElemBlock</xsl:with-param>
-         <xsl:with-param name="term">Disallowed Substitutions</xsl:with-param>
-         <xsl:with-param name="description">
-            <xsl:text>(Applies to element declarations).</xsl:text>
-            <xsl:text> If </xsl:text>
-            <em>substitution</em>
-            <xsl:text> is specified, then </xsl:text>
-            <xsl:call-template name="PrintGlossaryTermRef">
-               <xsl:with-param name="code">SubGroup</xsl:with-param>
-               <xsl:with-param name="term">substitution group</xsl:with-param>
-            </xsl:call-template>
-            <xsl:text> members cannot be used in place of the given element declaration to validate element instances.</xsl:text>
-
-            <xsl:text> If </xsl:text>
-            <em>derivation methods</em>
-            <xsl:text>, e.g. extension, restriction, are specified, then the given element declaration will not validate element instances that have types derived from the element declaration's type using the specified derivation methods.</xsl:text>
-            <xsl:text> Normally, element instances can override their declaration's type by specifying an </xsl:text>
-            <code>xsi:type</code>
-            <xsl:text> attribute.</xsl:text>
-         </xsl:with-param>
-      </xsl:call-template>
-
-      <xsl:call-template name="PrintGlossaryTerm">
-         <xsl:with-param name="code">Key</xsl:with-param>
-         <xsl:with-param name="term">Key Constraint</xsl:with-param>
-         <xsl:with-param name="description">
-            <xsl:text>Like </xsl:text>
-            <xsl:call-template name="PrintGlossaryTermRef">
-               <xsl:with-param name="code">Unique</xsl:with-param>
-               <xsl:with-param name="term">Uniqueness Constraint</xsl:with-param>
-            </xsl:call-template>
-            <xsl:text>, but additionally requires that the specified value(s) must be provided.</xsl:text>
-         </xsl:with-param>
-         <xsl:with-param name="link">http://www.w3.org/TR/xmlschema-1/#cIdentity-constraint_Definitions</xsl:with-param>
-      </xsl:call-template>
-
-      <xsl:call-template name="PrintGlossaryTerm">
-         <xsl:with-param name="code">KeyRef</xsl:with-param>
-         <xsl:with-param name="term">Key Reference Constraint</xsl:with-param>
-         <xsl:with-param name="description">
-            <xsl:text>Ensures that the specified value(s) must match value(s) from a </xsl:text>
-            <xsl:call-template name="PrintGlossaryTermRef">
-               <xsl:with-param name="code">Key</xsl:with-param>
-               <xsl:with-param name="term">Key Constraint</xsl:with-param>
-            </xsl:call-template>
-            <xsl:text> or </xsl:text>
-            <xsl:call-template name="PrintGlossaryTermRef">
-               <xsl:with-param name="code">Unique</xsl:with-param>
-               <xsl:with-param name="term">Uniqueness Constraint</xsl:with-param>
-            </xsl:call-template>
-            <xsl:text>.</xsl:text>
-         </xsl:with-param>
-         <xsl:with-param name="link">http://www.w3.org/TR/xmlschema-1/#cIdentity-constraint_Definitions</xsl:with-param>
-      </xsl:call-template>
-
-      <xsl:call-template name="PrintGlossaryTerm">
-         <xsl:with-param name="code">ModelGroup</xsl:with-param>
-         <xsl:with-param name="term">Model Group</xsl:with-param>
-         <xsl:with-param name="description">
-            <xsl:text>Groups together element content, specifying the order in which the element content can occur and the number of times the group of element content may be repeated.</xsl:text>
-         </xsl:with-param>
-         <xsl:with-param name="link">http://www.w3.org/TR/xmlschema-1/#Model_Groups</xsl:with-param>
-      </xsl:call-template>
-
-      <xsl:call-template name="PrintGlossaryTerm">
-         <xsl:with-param name="code">Nillable</xsl:with-param>
-         <xsl:with-param name="term">Nillable</xsl:with-param>
-         <xsl:with-param name="description">
-            <xsl:text>(Applies to element declarations). </xsl:text>
-            <xsl:text>If an element declaration is nillable, instances can use the </xsl:text>
-            <code>xsi:nil</code>
-            <xsl:text> attribute.</xsl:text>
-            <xsl:text> The </xsl:text>
-            <code>xsi:nil</code>
-            <xsl:text> attribute is the boolean attribute, </xsl:text>
-            <em>nil</em>
-            <xsl:text>, from the </xsl:text>
-            <em>http://www.w3.org/2001/XMLSchema-instance</em>
-            <xsl:text> namespace.</xsl:text>
-            <xsl:text> If an element instance has an </xsl:text>
-            <code>xsi:nil</code>
-            <xsl:text> attribute set to true, it can be left empty, even though its element declaration may have required content.</xsl:text>
-         </xsl:with-param>
-      </xsl:call-template>
-
-      <xsl:call-template name="PrintGlossaryTerm">
-         <xsl:with-param name="code">Notation</xsl:with-param>
-         <xsl:with-param name="term">Notation</xsl:with-param>
-         <xsl:with-param name="description">A notation is used to identify the format of a piece of data. Values of elements and attributes that are of type, NOTATION, must come from the names of declared notations.</xsl:with-param>
-         <xsl:with-param name="link">http://www.w3.org/TR/xmlschema-1/#cNotation_Declarations</xsl:with-param>
-      </xsl:call-template>
-
-      <xsl:call-template name="PrintGlossaryTerm">
-         <xsl:with-param name="code">PreserveWS</xsl:with-param>
-         <xsl:with-param name="term">Preserve Whitespace Policy</xsl:with-param>
-         <xsl:with-param name="description">Preserve whitespaces exactly as they appear in instances.</xsl:with-param>
-      </xsl:call-template>
-
-      <xsl:call-template name="PrintGlossaryTerm">
-         <xsl:with-param name="code">TypeFinal</xsl:with-param>
-         <xsl:with-param name="term">Prohibited Derivations</xsl:with-param>
-         <xsl:with-param name="description">
-            <xsl:text>(Applies to type definitions). </xsl:text>
-            <xsl:text>Derivation methods that cannot be used to create sub-types from a given type definition.</xsl:text>
-         </xsl:with-param>
-      </xsl:call-template>
-
-      <xsl:call-template name="PrintGlossaryTerm">
-         <xsl:with-param name="code">TypeBlock</xsl:with-param>
-         <xsl:with-param name="term">Prohibited Substitutions</xsl:with-param>
-         <xsl:with-param name="description">
-            <xsl:text>(Applies to complex type definitions). </xsl:text>
-            <xsl:text>Prevents sub-types that have been derived using the specified derivation methods from validating element instances in place of the given type definition.</xsl:text>
-         </xsl:with-param>
-      </xsl:call-template>
-
-      <xsl:call-template name="PrintGlossaryTerm">
-         <xsl:with-param name="code">ReplaceWS</xsl:with-param>
-         <xsl:with-param name="term">Replace Whitespace Policy</xsl:with-param>
-         <xsl:with-param name="description">Replace tab, line feed, and carriage return characters with space character (Unicode character 32).</xsl:with-param>
-      </xsl:call-template>
-
-      <xsl:call-template name="PrintGlossaryTerm">
-         <xsl:with-param name="code">Sequence</xsl:with-param>
-         <xsl:with-param name="term">Sequence Model Group</xsl:with-param>
-         <xsl:with-param name="description">
-            <xsl:text>Child elements and model groups must be provided </xsl:text>
-            <em>
-               <xsl:text>in the specified order</xsl:text>
-            </em>
-            <xsl:text> in instances.</xsl:text>
-         </xsl:with-param>
-         <xsl:with-param name="link">http://www.w3.org/TR/xmlschema-1/#element-sequence</xsl:with-param>
-      </xsl:call-template>
-
-      <xsl:call-template name="PrintGlossaryTerm">
-         <xsl:with-param name="code">SubGroup</xsl:with-param>
-         <xsl:with-param name="term">Substitution Group</xsl:with-param>
-         <xsl:with-param name="description">
-            <xsl:text>Elements that are </xsl:text>
-            <em>
-               <xsl:text>members</xsl:text>
-            </em>
-            <xsl:text> of a substitution group can be used wherever the </xsl:text>
-            <em>
-               <xsl:text>head</xsl:text>
-            </em>
-            <xsl:text> element of the substitution group is referenced.</xsl:text>
-         </xsl:with-param>
-      </xsl:call-template>
-
-      <xsl:call-template name="PrintGlossaryTerm">
-         <xsl:with-param name="code">ElemFinal</xsl:with-param>
-         <xsl:with-param name="term">Substitution Group Exclusions</xsl:with-param>
-         <xsl:with-param name="description">
-            <xsl:text>(Applies to element declarations). </xsl:text>
-            <xsl:text>Prohibits element declarations from nominating themselves as being able to substitute a given element declaration, if they have types that are derived from the original element's type using the specified derivation methods.</xsl:text>
-         </xsl:with-param>
-      </xsl:call-template>
-
-      <xsl:call-template name="PrintGlossaryTerm">
-         <xsl:with-param name="code">TargetNS</xsl:with-param>
-         <xsl:with-param name="term">Target Namespace</xsl:with-param>
-         <xsl:with-param name="description">The target namespace identifies the namespace that components in this schema belongs to. If no target namespace is provided, then the schema components do not belong to any namespace.</xsl:with-param>
-      </xsl:call-template>
-
-      <xsl:call-template name="PrintGlossaryTerm">
-         <xsl:with-param name="code">Unique</xsl:with-param>
-         <xsl:with-param name="term">Uniqueness Constraint</xsl:with-param>
-         <xsl:with-param name="description">Ensures uniqueness of an element/attribute value, or a combination of values, within a specified scope.</xsl:with-param>
-         <xsl:with-param name="link">http://www.w3.org/TR/xmlschema-1/#cIdentity-constraint_Definitions</xsl:with-param>
-      </xsl:call-template>
-   </xsl:template>
-
-   <!--
-     Prints out a term in the glossary section.
-     Param(s):
-            code (String) required
-              Unique ID of glossary term
-            term (String) required
-              Glossary term
-            description (Result Tree Fragment) required
-              Meaning of term; may contain HTML tags and links
-            link (String) optional
-              URI containing more info about term
-     -->
-   <xsl:template name="PrintGlossaryTerm">
-      <xsl:param name="code"/>
-      <xsl:param name="term"/>
-      <xsl:param name="description"/>
-      <xsl:param name="link"/>
-
-      <p>
-         <span class="glossaryTerm">
-            <a name="{concat($TERM_PREFIX, $code)}"><xsl:value-of select="$term"/></a>
-            <xsl:text> </xsl:text>
-         </span>
-         <xsl:copy-of select="$description"/>
-         <xsl:if test="$link != ''">
-            <xsl:text> See: </xsl:text>
-            <xsl:call-template name="PrintURI">
-               <xsl:with-param name="uri" select="$link"/>
-            </xsl:call-template>
-            <xsl:text>.</xsl:text>
-         </xsl:if>
-      </p>
-   </xsl:template>
-
-
-   <!-- ******** Hierarchy table ******** -->
-
-   <!-- 
-     Prints out substitution group hierarchy for
-     element declarations.
-     -->
-   <xsl:template match="xsd:element" mode="hierarchy">
-      <!--
-        Find out members of substitution group that this element 
-        heads.
-        -->
-      <xsl:variable name="members">
-         <ul>
-            <xsl:call-template name="PrintSGroupMembers">
-               <xsl:with-param name="element" select="."/>
-            </xsl:call-template>
-         </ul>
-      </xsl:variable>
-      <xsl:variable name="hasMembers">
-         <xsl:if test="normalize-space($members)!=''">
-            <xsl:text>true</xsl:text>
-         </xsl:if>
-      </xsl:variable>
-      <!-- Print hierarchy table -->
-      <xsl:if test="@substitutionGroup or normalize-space($hasMembers)='true'">
-         <table class="hierarchy">
-            <tr>
-               <td>
-                  <ul>
-                     <!-- Print substitution group that this element belongs to -->
-                     <xsl:if test="@substitutionGroup">
-                        <li>
-                           <em>This element can be used wherever the following element is referenced:</em>
-                           <ul>
-                              <li>
-                                 <xsl:call-template name="PrintElementRef">
-                                    <xsl:with-param name="ref" select="@substitutionGroup"/>
-                                 </xsl:call-template>
-                              </li>
-                           </ul>
-                        </li>
-                     </xsl:if>
-                     <!-- Print substitution group that this element heads -->
-                     <xsl:if test="normalize-space($hasMembers)='true'">
-                        <li>
-                           <em>The following elements can be used wherever this element is referenced:</em>
-                           <xsl:copy-of select="$members"/>
-                        </li>
-                     </xsl:if>
-                  </ul>
-               </td>
-            </tr>
-         </table>
-      </xsl:if>
-   </xsl:template>
-
-   <!-- 
-     Prints out Hierarchy table for complex type definitions.
-     -->
-   <xsl:template match="xsd:complexType" mode="hierarchy">
-      <table class="hierarchy">
-         <!-- Print super types -->
-         <tr>
-            <th>
-               <xsl:choose>
-                  <xsl:when test="normalize-space(translate($printAllSuperTypes, 'TRUE', 'true'))='true'">
-                     <xsl:text>Super-types:</xsl:text>
-                  </xsl:when>
-                  <xsl:otherwise>
-                     <xsl:text>Parent type:</xsl:text>
-                  </xsl:otherwise>
-               </xsl:choose>
-            </th>
-            <td>
-               <xsl:choose>
-                  <xsl:when test="xsd:simpleContent or xsd:complexContent">
-                     <xsl:call-template name="PrintSupertypes">
-                        <xsl:with-param name="type" select="."/>
-                     </xsl:call-template>
-                  </xsl:when>
-                  <xsl:otherwise>
-                     <xsl:text>None</xsl:text>
-                  </xsl:otherwise>
-               </xsl:choose>
-            </td>
-         </tr>
-         <!-- Print sub types -->
-         <tr>
-            <th>
-               <xsl:choose>
-                  <xsl:when test="normalize-space(translate($printAllSubTypes, 'TRUE', 'true'))='true'">
-                     <xsl:text>Sub-types:</xsl:text>
-                  </xsl:when>
-                  <xsl:otherwise>
-                     <xsl:text>Direct sub-types:</xsl:text>
-                  </xsl:otherwise>
-               </xsl:choose>
-            </th>
-            <td>
-               <xsl:call-template name="PrintComplexSubtypes">
-                  <xsl:with-param name="type" select="."/>
-               </xsl:call-template>
-            </td>
-         </tr>
-      </table>
-   </xsl:template>
-
-   <!-- 
-     Prints out Hierarchy table for simple type definitions.
-     -->
-   <xsl:template match="xsd:simpleType" mode="hierarchy">
-      <table class="hierarchy">
-         <!-- Print super types -->
-         <tr>
-            <th>
-               <xsl:choose>
-                  <xsl:when test="normalize-space(translate($printAllSuperTypes, 'TRUE', 'true'))='true'">
-                     <xsl:text>Super-types:</xsl:text>
-                  </xsl:when>
-                  <xsl:otherwise>
-                     <xsl:text>Parent type:</xsl:text>
-                  </xsl:otherwise>
-               </xsl:choose>
-            </th>
-            <td>
-               <xsl:choose>
-                  <xsl:when test="xsd:restriction">
-                     <xsl:call-template name="PrintSupertypes">
-                        <xsl:with-param name="type" select="."/>
-                     </xsl:call-template>
-                  </xsl:when>
-                  <xsl:otherwise>
-                     <xsl:text>None</xsl:text>
-                  </xsl:otherwise>
-               </xsl:choose>
-            </td>
-         </tr>
-         <!-- Print sub types -->
-         <tr>
-            <th>
-               <xsl:choose>
-                  <xsl:when test="normalize-space(translate($printAllSubTypes, 'TRUE', 'true'))='true'">
-                     <xsl:text>Sub-types:</xsl:text>
-                  </xsl:when>
-                  <xsl:otherwise>
-                     <xsl:text>Direct sub-types:</xsl:text>
-                  </xsl:otherwise>
-               </xsl:choose>
-            </th>
-            <td>
-               <xsl:call-template name="PrintSimpleSubtypes">
-                  <xsl:with-param name="type" select="."/>
-               </xsl:call-template>
-            </td>
-         </tr>
-      </table>
-   </xsl:template>
-
-   <!--
-     Unmatched template for 'hierarchy' mode
-     -->
-   <xsl:template match="*" mode="hierarchy"/>
-
-   <!-- 
-     Prints out members, if any, of the substitution group that a 
-     given element declaration heads.
-     Assumes it will be called within XHTML <ul> tags.
-     Param(s):
-            element (Node) required
-              Top-level element declaration
-            elementList (String) optional
-                List of elements in this call chain. Name of element starts
-                with '*', and ends with '+'. (Used to prevent infinite
-                recursive loop.)
-     -->
-   <xsl:template name="PrintSGroupMembers">
-      <xsl:param name="element"/>
-      <xsl:param name="elementList"/>
-
-      <xsl:variable name="elemName" select="normalize-space($element/@name)"/>
-      <xsl:choose>
-         <xsl:when test="contains($elementList, concat('*', $elemName, '+'))">
-            <!-- Circular element substitution group hierarchy -->
-            <li>
-               <xsl:call-template name="HandleError">
-                  <xsl:with-param name="isTerminating">false</xsl:with-param>
-                  <xsl:with-param name="errorMsg">
-                     <xsl:text>Circular element reference to: </xsl:text>
-                     <xsl:value-of select="$elemName"/>
-                  </xsl:with-param>
-               </xsl:call-template>
-            </li>
-         </xsl:when>
-         <xsl:otherwise>
-            <!-- Get 'block' attribute. -->
-            <xsl:variable name="block">
-               <xsl:call-template name="PrintBlockSet">
-                  <xsl:with-param name="EBV">
-                     <xsl:choose>
-                        <xsl:when test="$element/@block">
-                           <xsl:value-of select="$element/@block"/>
-                        </xsl:when>
-                        <xsl:otherwise>
-                           <xsl:value-of select="/xsd:schema/@blockDefault"/>
-                        </xsl:otherwise>
-                     </xsl:choose>
-                  </xsl:with-param>
-               </xsl:call-template>
-            </xsl:variable>
-
-            <xsl:for-each select="/xsd:schema/xsd:element[normalize-space(@substitutionGroup)=$elemName or normalize-space(substring-after(@substitutionGroup, ':'))=$elemName]">
-               <li>
-                  <xsl:call-template name="PrintElementRef">
-                     <xsl:with-param name="name" select="@name"/>
-                  </xsl:call-template>
-               </li>
-               <!-- Recursively find members of a substitution group that 
-                    current element in list might head, since substitution 
-                    groups are transitive (unless 'substitution' is 
-                    blocked). 
-                -->
-               <xsl:if test="not(contains($block, 'substitution'))">
-                  <xsl:call-template name="PrintSGroupMembers">
-                     <xsl:with-param name="element" select="."/>
-                     <xsl:with-param name="elementList" select="concat($elementList, '*', $elemName, '+')"/>
-                  </xsl:call-template>
-               </xsl:if>
-            </xsl:for-each>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Prints out the super types of a given type definition.
-     Param(s):
-            type (Node) required
-                Type definition
-            isCallingType (boolean) optional
-                If true, 'type' is the type definition that starts 
-                this call. Otherwise, this is a recursive call from 
-                'PrintSupertypes' itself.
-            typeList (String) optional
-                List of types in this call chain. Name of type starts
-                with '*', and ends with '+'. (Used to prevent infinite
-                recursive loop.)
-     -->
-   <xsl:template name="PrintSupertypes">
-      <xsl:param name="type"/>
-      <xsl:param name="isCallingType">true</xsl:param>
-      <xsl:param name="typeList"/>
-
-      <xsl:variable name="typeName" select="$type/@name"/>
-      <xsl:choose>
-         <!-- Circular type hierarchy -->
-         <xsl:when test="contains($typeList, concat('*', $typeName, '+'))">
-            <!-- Note: Error message will be written out in the Sample Instance table. -->
-            <xsl:value-of select="$typeName"/>
-         </xsl:when>
-         <xsl:otherwise>
-            <!-- Get base type reference -->
-            <xsl:variable name="baseTypeRef">
-               <xsl:choose>
-                  <!-- Complex type definition -->
-                  <xsl:when test="local-name($type)='complexType'">
-                     <xsl:choose>
-                        <xsl:when test="$type/xsd:simpleContent/xsd:extension">
-                           <xsl:value-of select="$type/xsd:simpleContent/xsd:extension/@base"/>
-                        </xsl:when>
-                        <xsl:when test="$type/xsd:simpleContent/xsd:restriction">
-                           <xsl:value-of select="$type/xsd:simpleContent/xsd:restriction/@base"/>
-                        </xsl:when>
-                        <xsl:when test="$type/xsd:complexContent/xsd:extension">
-                           <xsl:value-of select="$type/xsd:complexContent/xsd:extension/@base"/>
-                        </xsl:when>
-                        <xsl:when test="$type/xsd:complexContent/xsd:restriction">
-                           <xsl:value-of select="$type/xsd:complexContent/xsd:restriction/@base"/>
-                        </xsl:when>
-                     </xsl:choose>
-                  </xsl:when>
-                  <!-- Simple type definition -->
-                  <xsl:when test="local-name($type)='simpleType'">
-                     <xsl:choose>
-                        <xsl:when test="$type/xsd:restriction/@base">
-                           <xsl:value-of select="$type/xsd:restriction/@base"/>
-                        </xsl:when>
-                        <xsl:when test="$type/xsd:restriction/xsd:simpleType">
-                           <xsl:text>Local type definition</xsl:text>
-                        </xsl:when>
-                     </xsl:choose>
-                  </xsl:when>
-               </xsl:choose>
-            </xsl:variable>
-
-            <!-- Get derivation method -->
-            <xsl:variable name="derive">
-               <!-- Complex type definition -->
-               <xsl:choose>
-                  <xsl:when test="local-name($type)='complexType'">
-                     <xsl:choose>
-                        <xsl:when test="$type/xsd:simpleContent/xsd:extension or $type/xsd:complexContent/xsd:extension">
-                           <xsl:text>extension</xsl:text>
-                        </xsl:when>
-                        <xsl:when test="$type/xsd:simpleContent/xsd:restriction or $type/xsd:complexContent/xsd:restriction">
-                           <xsl:text>restriction</xsl:text>
-                        </xsl:when>
-                     </xsl:choose>
-                  </xsl:when>
-                  <!-- Simple type definition -->
-                  <xsl:when test="local-name($type)='simpleType'">
-                     <xsl:text>restriction</xsl:text>
-                  </xsl:when>
-               </xsl:choose>
-            </xsl:variable>
-
-            <xsl:choose>
-               <!-- Print out entire hierarchy -->
-               <xsl:when test="normalize-space(translate($printAllSuperTypes, 'TRUE', 'true'))='true'">
-                  <xsl:choose>
-                     <xsl:when test="normalize-space($baseTypeRef)='Local type definition'">
-                        <xsl:value-of select="$baseTypeRef"/>
-                        <!-- Symbol to indicate type derivation-->
-                        <xsl:text> &lt; </xsl:text>
-                     </xsl:when>
-                     <xsl:when test="normalize-space($baseTypeRef)!=''">
-                        <!-- Get base type name from reference -->
-                        <xsl:variable name="baseTypeName">
-                           <xsl:call-template name="GetRefName">
-                              <xsl:with-param name="ref" select="$baseTypeRef"/>
-                           </xsl:call-template>
-                        </xsl:variable>
-                        <!-- Get base type definition from schema -->
-                        <xsl:variable name="baseType" select="key('type', $baseTypeName)"/>
-                        <xsl:choose>
-                           <!-- Base type was found in this schema -->
-                           <xsl:when test="$baseType">
-                              <!-- Make recursive call to print out base type and itself -->
-                              <xsl:call-template name="PrintSupertypes">
-                                 <xsl:with-param name="type" select="$baseType"/>
-                                 <xsl:with-param name="isCallingType">false</xsl:with-param>
-                                 <xsl:with-param name="typeList" select="concat($typeList, '*', $typeName, '+')"/>
-                              </xsl:call-template>
-                           </xsl:when>
-                           <!-- Base type was not found in this schema -->
-                           <xsl:otherwise>
-                              <xsl:call-template name="PrintTypeRef">
-                                 <xsl:with-param name="ref" select="$baseTypeRef"/>
-                              </xsl:call-template>
-                           </xsl:otherwise>
-                        </xsl:choose>
-                        <!-- Symbol to indicate type derivation -->
-                        <xsl:text> &lt; </xsl:text>
-                     </xsl:when>
-                     <xsl:otherwise>
-                        <!-- IGNORE: Base type may not be exist probably because 
-                            current type does not be derived from another type.
-                        -->
-                     </xsl:otherwise>
-                  </xsl:choose>
-                  <!-- Print out current type's name -->
-                  <xsl:choose>
-                     <xsl:when test="$isCallingType='true'">
-                        <strong><xsl:value-of select="$typeName"/></strong>
-                     </xsl:when>
-                     <xsl:otherwise>
-                        <xsl:call-template name="PrintTypeRef">
-                           <xsl:with-param name="name" select="$typeName"/>
-                        </xsl:call-template>
-                     </xsl:otherwise>
-                  </xsl:choose>
-                  <!-- Print out derivation method -->
-                  <xsl:if test="$derive != ''">
-                     <xsl:text> (by </xsl:text>
-                     <xsl:value-of select="$derive"/>
-                     <xsl:text>)</xsl:text>
-                  </xsl:if>
-               </xsl:when>
-               <!-- Print out parent type only -->
-               <xsl:otherwise>
-                  <!-- Print out base type reference -->
-                  <xsl:choose>
-                     <xsl:when test="normalize-space($baseTypeRef)='Local type definition'">
-                        <xsl:value-of select="$baseTypeRef"/>
-                     </xsl:when>
-                     <xsl:when test="$baseTypeRef!=''">
-                        <xsl:call-template name="PrintTypeRef">
-                           <xsl:with-param name="ref" select="$baseTypeRef"/>
-                        </xsl:call-template>
-                     </xsl:when>
-                     <xsl:otherwise>
-                        <!-- IGNORE: Base type may not be exist probably because 
-                             current type does not be derived from another type.
-                        -->
-                     </xsl:otherwise>
-                  </xsl:choose>
-                  <!-- Print out derivation method -->
-                  <xsl:if test="$derive != ''">
-                     <xsl:text> (derivation method: </xsl:text>
-                     <xsl:value-of select="$derive"/>
-                     <xsl:text>)</xsl:text>
-                  </xsl:if>
-               </xsl:otherwise>
-            </xsl:choose>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Prints out the sub types of a given complex type definition.
-     Param(s):
-            type (Node) required
-                Complex type definition
-            isCallingType (boolean) optional
-                If true, 'type' is the type definition that starts this 
-                call. Otherwise, this is a recursive call from 
-                'PrintComplexSubtypes' itself.
-            typeList (String) optional
-                List of types in this call chain. Name of type starts
-                with '*', and ends with '+'. (Used to prevent infinite
-                recursive loop.)
-     -->
-   <xsl:template name="PrintComplexSubtypes">
-      <xsl:param name="type"/>
-      <xsl:param name="isCallingType">true</xsl:param>
-      <xsl:param name="typeList"/>
-
-      <xsl:variable name="typeName" select="normalize-space($type/@name)"/>
-      <xsl:choose>
-         <!-- Circular type hierarchy -->
-         <xsl:when test="contains($typeList, concat('*', $typeName, '+'))">
-            <!-- Do nothing. Note: Error message will be written out in the Sample Instance table. -->
-         </xsl:when>
-         <xsl:otherwise>
-            <!-- Find sub types -->
-            <xsl:variable name="subTypes">
-               <ul>
-                  <xsl:for-each select="/xsd:schema/xsd:complexType/xsd:complexContent/xsd:restriction[normalize-space(@base)=$typeName or normalize-space(substring-after(@base, ':'))=$typeName] | /xsd:schema/xsd:complexType/xsd:complexContent/xsd:extension[normalize-space(@base)=$typeName or normalize-space(substring-after(@base, ':'))=$typeName]">
-                     <li>
-                        <xsl:variable name="subType" select="../.."/>
-                        <!-- Write out type name -->
-                        <xsl:call-template name="PrintTypeRef">
-                           <xsl:with-param name="name" select="$subType/@name"/>
-                        </xsl:call-template>
-                        <!-- Write derivation method -->
-                        <xsl:text> (by </xsl:text>
-                        <xsl:value-of select="local-name(.)"/>
-                        <xsl:text>)</xsl:text>
-                        <!-- Make recursive call to write sub-types of this sub-type -->
-                        <xsl:if test="normalize-space(translate($printAllSubTypes, 'TRUE', 'true'))='true'">
-                           <xsl:call-template name="PrintComplexSubtypes">
-                              <xsl:with-param name="type" select="$subType"/>
-                              <xsl:with-param name="isCallingType">false</xsl:with-param>
-                              <xsl:with-param name="typeList" select="concat($typeList, '*', $typeName, '+')"/>
-                           </xsl:call-template>
-                        </xsl:if>
-                     </li>
-                  </xsl:for-each>
-               </ul>
-            </xsl:variable>
-            <!-- Print out sub types -->
-            <xsl:choose>
-               <xsl:when test="normalize-space($subTypes)!=''">
-                  <xsl:copy-of select="$subTypes"/>
-               </xsl:when>
-               <xsl:when test="$isCallingType='true'">
-                  <xsl:text>None</xsl:text>
-               </xsl:when>
-            </xsl:choose>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-        Prints out the sub types of a given simple type definition.
-        Param(s):
-            type (Node) required
-                Simple type definition
-            isCallingType (boolean) optional
-                If true, 'type' is the type definition that starts this 
-                call. Otherwise, this is a recursive call from 
-                'PrintSimpleSubtypes'
-            typeList (String) optional
-                List of types in this call chain. Name of type starts
-                with '*', and ends with '+'. (Used to prevent infinite
-                recursive loop.)
-     -->
-   <xsl:template name="PrintSimpleSubtypes">
-      <xsl:param name="type"/>
-      <xsl:param name="isCallingType">true</xsl:param>
-      <xsl:param name="typeList"/>
-
-      <xsl:variable name="typeName" select="normalize-space($type/@name)"/>
-      <xsl:choose>
-         <!-- Circular type hierarchy -->
-         <xsl:when test="contains($typeList, concat('*', $typeName, '+'))">
-            <!-- Do nothing. Note: Error message will be written out in the Sample Instance table. -->
-         </xsl:when>
-         <xsl:otherwise>
-            <!-- Find sub-types that are simple type definitions -->
-            <xsl:variable name="simpleSubTypes">
-               <ul>
-                  <xsl:for-each select="/xsd:schema/xsd:simpleType/xsd:restriction[normalize-space(@base)=$typeName or normalize-space(substring-after(@base, ':'))=$typeName]">
-                     <li>
-                        <xsl:variable name="subType" select=".."/>
-                        <!-- Write out type name -->
-                        <xsl:call-template name="PrintTypeRef">
-                           <xsl:with-param name="name" select="$subType/@name"/>
-                        </xsl:call-template>
-                        <!-- Write derivation method -->
-                        <xsl:text> (by restriction)</xsl:text>
-                        <!-- Make recursive call to write sub-types of this sub-type -->
-                        <xsl:if test="normalize-space(translate($printAllSubTypes, 'TRUE', 'true'))='true'">
-                           <xsl:call-template name="PrintSimpleSubtypes">
-                              <xsl:with-param name="type" select="$subType"/>
-                              <xsl:with-param name="isCallingType">false</xsl:with-param>
-                              <xsl:with-param name="typeList" select="concat($typeList, '*', $typeName, '+')"/>
-                           </xsl:call-template>
-                        </xsl:if>
-                     </li>
-                  </xsl:for-each>
-               </ul>
-            </xsl:variable>
-            <!-- Find sub-types that are complex type definitions -->
-            <xsl:variable name="complexSubTypes">
-               <ul>
-                  <xsl:for-each select="/xsd:schema/xsd:complexType/xsd:simpleContent/xsd:restriction[normalize-space(@base)=$typeName or normalize-space(substring-after(@base, ':'))=$typeName] | /xsd:schema/xsd:complexType/xsd:simpleContent/xsd:extension[normalize-space(@base)=$typeName or normalize-space(substring-after(@base, ':'))=$typeName]">
-                     <li>
-                        <xsl:variable name="subType" select="../.."/>
-                        <!-- Write out type name -->
-                        <xsl:call-template name="PrintTypeRef">
-                           <xsl:with-param name="name" select="$subType/@name"/>
-                        </xsl:call-template>
-                        <!-- Write derivation method -->
-                        <xsl:text> (by </xsl:text>
-                        <xsl:value-of select="local-name(.)"/>
-                        <xsl:text>)</xsl:text>
-                        <!-- Make recursive call to write sub-types of this sub-type -->
-                        <xsl:if test="normalize-space(translate($printAllSubTypes, 'TRUE', 'true'))='true'">
-                           <xsl:call-template name="PrintComplexSubtypes">
-                              <xsl:with-param name="type" select="$subType"/>
-                              <xsl:with-param name="isCallingType">false</xsl:with-param>
-                              <xsl:with-param name="typeList" select="concat($typeList, '*', $typeName, '+')"/>
-                           </xsl:call-template>
-                        </xsl:if>
-                     </li>
-                  </xsl:for-each>
-               </ul>
-            </xsl:variable>
-
-            <xsl:variable name="hasSimpleSubTypes">
-               <xsl:if test="normalize-space($simpleSubTypes)!=''">
-                  <xsl:text>true</xsl:text>
-               </xsl:if>
-            </xsl:variable>
-            <xsl:variable name="hasComplexSubTypes">
-               <xsl:if test="normalize-space($complexSubTypes)!=''">
-                  <xsl:text>true</xsl:text>
-               </xsl:if>
-            </xsl:variable>
-            <!-- Print out sub types -->
-            <xsl:choose>
-               <xsl:when test="$hasSimpleSubTypes='true' or $hasComplexSubTypes='true'">
-                  <xsl:if test="$hasSimpleSubTypes='true'">
-                     <xsl:copy-of select="$simpleSubTypes"/>
-                  </xsl:if>
-                  <xsl:if test="$hasComplexSubTypes='true'">
-                     <xsl:copy-of select="$complexSubTypes"/>
-                  </xsl:if>
-               </xsl:when>
-               <xsl:when test="$isCallingType='true'">
-                  <xsl:text>None</xsl:text>
-               </xsl:when>
-            </xsl:choose>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-
-   <!-- ******** Properties table ******** -->
-
-   <!--
-     Prints out the contents of an 'appinfo' or a 'documentation'
-     element in the Properties table.
-     -->
-   <xsl:template match="xsd:appinfo | xsd:documentation" mode="properties">
-      <!-- Print out children using XML pretty printer templates -->
-      <xsl:choose>
-         <xsl:when test="local-name(.)='appinfo'">
-            <xsl:apply-templates select="* | text()" mode="xpp"/>
-         </xsl:when>
-         <xsl:otherwise>
-            <xsl:apply-templates select="* | text()" mode="html"/>
-         </xsl:otherwise>
-      </xsl:choose>
-
-      <!-- Print out URL in the source attribute. -->
-      <xsl:if test="@source">
-         <xsl:if test="* | text()"><br/></xsl:if>
-         <xsl:text> More information at: </xsl:text>
-         <xsl:call-template name="PrintURI">
-            <xsl:with-param name="uri" select="@source"/>
-         </xsl:call-template>
-         <xsl:text>.</xsl:text>
-      </xsl:if>
-   </xsl:template>
-
-   <!--
-     Prints out the Properties table for a top-level
-     attribute declaration.
-     -->
-   <xsl:template match="xsd:attribute" mode="properties">
-      <table class="properties">
-         <!-- Name -->
-         <tr>
-            <th>Name</th>
-            <td><xsl:value-of select="@name"/></td>
-         </tr>
-         <!-- Type -->
-         <tr>
-            <th>Type</th>
-            <td>
-               <xsl:choose>
-                  <xsl:when test="xsd:simpleType">
-                     <xsl:text>Locally-defined simple type</xsl:text>
-                  </xsl:when>
-                  <xsl:when test="@type">
-                     <xsl:call-template name="PrintTypeRef">
-                        <xsl:with-param name="ref" select="@type"/>
-                     </xsl:call-template>
-                  </xsl:when>
-                  <xsl:otherwise>
-                     <xsl:text>anySimpleType</xsl:text>
-                  </xsl:otherwise>
-               </xsl:choose>
-            </td>
-         </tr>
-         <!-- Default Value -->
-         <xsl:if test="@default">
-            <tr>
-               <th>Default Value</th>
-               <td><xsl:value-of select="@default"/></td>
-            </tr>
-         </xsl:if>
-         <!-- Fixed Value -->
-         <xsl:if test="@fixed">
-            <tr>
-               <th>Fixed Value</th>
-               <td><xsl:value-of select="@fixed"/></td>
-            </tr>
-         </xsl:if>
-         <!-- Annotation -->
-         <xsl:call-template name="PrintAnnotation">
-            <xsl:with-param name="component" select="."/>
-         </xsl:call-template>
-      </table>
-   </xsl:template>
-
-   <!--
-     Prints out Properties table for a top-level
-     attribute group or model group definition.
-     -->
-   <xsl:template match="xsd:attributeGroup | xsd:group" mode="properties">
-      <table class="properties">
-         <!-- Name -->
-         <tr>
-            <th>Name</th>
-            <td><xsl:value-of select="@name"/></td>
-         </tr>
-         <!-- Annotation -->
-         <xsl:call-template name="PrintAnnotation">
-            <xsl:with-param name="component" select="."/>
-         </xsl:call-template>
-      </table>
-   </xsl:template>
-
-   <!--
-     Prints out the Properties table for a top-level
-     complex type definition.
-     -->
-   <xsl:template match="xsd:complexType" mode="properties">
-      <table class="properties">
-         <!-- Name -->
-         <tr>
-            <th>Name</th>
-            <td><xsl:value-of select="@name"/></td>
-         </tr>
-         <!-- Abstract -->
-         <tr>
-            <th>
-               <xsl:call-template name="PrintGlossaryTermRef">
-                  <xsl:with-param name="code">Abstract</xsl:with-param>
-                  <xsl:with-param name="term">Abstract</xsl:with-param>
-               </xsl:call-template>
-            </th>
-            <td>
-               <xsl:call-template name="PrintBoolean">
-                  <xsl:with-param name="boolean" select="@abstract"/>
-               </xsl:call-template>
-            </td>
-         </tr>
-         <!-- Final -->
-         <xsl:variable name="final">
-            <xsl:call-template name="PrintDerivationSet">
-               <xsl:with-param name="EBV">
-                  <xsl:choose>
-                     <xsl:when test="@final">
-                        <xsl:value-of select="@final"/>
-                     </xsl:when>
-                     <xsl:otherwise>
-                        <xsl:value-of select="/xsd:schema/@finalDefault"/>
-                     </xsl:otherwise>
-                  </xsl:choose>
-               </xsl:with-param>
-            </xsl:call-template>
-         </xsl:variable>
-         <xsl:if test="normalize-space($final)!=''">
-            <tr>
-               <th>
-                  <xsl:call-template name="PrintGlossaryTermRef">
-                     <xsl:with-param name="code">TypeFinal</xsl:with-param>
-                     <xsl:with-param name="term">Prohibited Derivations</xsl:with-param>
-                  </xsl:call-template>
-               </th>
-               <td><xsl:value-of select="$final"/></td>
-            </tr>
-         </xsl:if>
-         <!-- Block -->
-         <xsl:variable name="block">
-            <xsl:call-template name="PrintDerivationSet">
-               <xsl:with-param name="EBV">
-                  <xsl:choose>
-                     <xsl:when test="@block">
-                        <xsl:value-of select="@block"/>
-                     </xsl:when>
-                     <xsl:otherwise>
-                        <xsl:value-of select="/xsd:schema/@blockDefault"/>
-                     </xsl:otherwise>
-                  </xsl:choose>
-               </xsl:with-param>
-            </xsl:call-template>
-         </xsl:variable>
-         <xsl:if test="normalize-space($block)!=''">
-            <tr>
-               <th>
-                  <xsl:call-template name="PrintGlossaryTermRef">
-                     <xsl:with-param name="code">TypeBlock</xsl:with-param>
-                     <xsl:with-param name="term">Prohibited Substitutions</xsl:with-param>
-                  </xsl:call-template>
-               </th>
-               <td><xsl:value-of select="$block"/></td>
-            </tr>
-         </xsl:if>
-         <!-- Annotation -->
-         <xsl:call-template name="PrintAnnotation">
-            <xsl:with-param name="component" select="."/>
-         </xsl:call-template>
-      </table>
-   </xsl:template>
-
-   <!--
-     Prints out the Properties table for a top-level
-     element declaration.
-     -->
-   <xsl:template match="xsd:element" mode="properties">
-      <table class="properties">
-         <!-- Name -->
-         <tr>
-            <th>Name</th>
-            <td><xsl:value-of select="@name"/></td>
-         </tr>
-         <!-- Type -->
-         <tr>
-            <th>Type</th>
-            <td>
-               <xsl:choose>
-                  <xsl:when test="xsd:simpleType">
-                     <xsl:text>Locally-defined simple type</xsl:text>
-                  </xsl:when>
-                  <xsl:when test="xsd:complexType">
-                     <xsl:text>Locally-defined complex type</xsl:text>
-                  </xsl:when>
-                  <xsl:when test="@type">
-                     <xsl:call-template name="PrintTypeRef">
-                        <xsl:with-param name="ref" select="@type"/>
-                     </xsl:call-template>
-                  </xsl:when>
-                  <xsl:otherwise>
-                     <xsl:text>anyType</xsl:text>
-                  </xsl:otherwise>
-               </xsl:choose>
-            </td>
-         </tr>
-         <!-- Nillable -->
-         <tr>
-            <th>
-               <xsl:call-template name="PrintGlossaryTermRef">
-                  <xsl:with-param name="code">Nillable</xsl:with-param>
-                  <xsl:with-param name="term">Nillable</xsl:with-param>
-               </xsl:call-template>
-            </th>
-            <td>
-               <xsl:call-template name="PrintBoolean">
-                  <xsl:with-param name="boolean" select="@nillable"/>
-               </xsl:call-template>
-            </td>
-         </tr>
-         <!-- Abstract -->
-         <tr>
-            <th>
-               <xsl:call-template name="PrintGlossaryTermRef">
-                  <xsl:with-param name="code">Abstract</xsl:with-param>
-                  <xsl:with-param name="term">Abstract</xsl:with-param>
-               </xsl:call-template>
-            </th>
-            <td>
-               <xsl:call-template name="PrintBoolean">
-                  <xsl:with-param name="boolean" select="@abstract"/>
-               </xsl:call-template>
-            </td>
-         </tr>
-         <!-- Default Value -->
-         <xsl:if test="@default">
-            <tr>
-               <th>Default Value</th>
-               <td><xsl:value-of select="@default"/></td>
-            </tr>
-         </xsl:if>
-         <!-- Fixed Value -->
-         <xsl:if test="@fixed">
-            <tr>
-               <th>Fixed Value</th>
-               <td><xsl:value-of select="@fixed"/></td>
-            </tr>
-         </xsl:if>
-         <!-- Final -->
-         <xsl:variable name="final">
-            <xsl:call-template name="PrintDerivationSet">
-               <xsl:with-param name="EBV">
-                  <xsl:choose>
-                     <xsl:when test="@final">
-                        <xsl:value-of select="@final"/>
-                     </xsl:when>
-                     <xsl:otherwise>
-                        <xsl:value-of select="/xsd:schema/@finalDefault"/>
-                     </xsl:otherwise>
-                  </xsl:choose>
-               </xsl:with-param>
-            </xsl:call-template>
-         </xsl:variable>
-         <xsl:if test="normalize-space($final)!=''">
-            <tr>
-               <th>
-                  <xsl:call-template name="PrintGlossaryTermRef">
-                     <xsl:with-param name="code">ElemFinal</xsl:with-param>
-                     <xsl:with-param name="term">Substitution Group Exclusions</xsl:with-param>
-                  </xsl:call-template>
-               </th>
-               <td><xsl:value-of select="$final"/></td>
-            </tr>
-         </xsl:if>
-         <!-- Block -->
-         <xsl:variable name="block">
-            <xsl:call-template name="PrintBlockSet">
-               <xsl:with-param name="EBV">
-                  <xsl:choose>
-                     <xsl:when test="@block">
-                        <xsl:value-of select="@block"/>
-                     </xsl:when>
-                     <xsl:otherwise>
-                        <xsl:value-of select="/xsd:schema/@blockDefault"/>
-                     </xsl:otherwise>
-                  </xsl:choose>
-               </xsl:with-param>
-            </xsl:call-template>
-         </xsl:variable>
-         <xsl:if test="normalize-space($block)!=''">
-            <tr>
-               <th>
-                  <xsl:call-template name="PrintGlossaryTermRef">
-                     <xsl:with-param name="code">ElemBlock</xsl:with-param>
-                     <xsl:with-param name="term">Disallowed Substitutions</xsl:with-param>
-                  </xsl:call-template>
-               </th>
-               <td><xsl:value-of select="$block"/></td>
-            </tr>
-         </xsl:if>
-         <!-- Annotation -->
-         <xsl:call-template name="PrintAnnotation">
-            <xsl:with-param name="component" select="."/>
-         </xsl:call-template>
-      </table>
-   </xsl:template>
-
-   <!--
-     Prints out the Properties table for a top-level
-     notation declaration.
-     -->
-   <xsl:template match="xsd:notation" mode="properties">
-      <table class="properties">
-         <!-- Name -->
-         <tr>
-            <th>Name</th>
-            <td><xsl:value-of select="@name"/></td>
-         </tr>
-         <!-- Public Identifier -->
-         <tr>
-            <th>Public Identifier</th>
-            <td><xsl:value-of select="@public"/></td>
-         </tr>
-         <!-- System Identifier -->
-         <xsl:if test="@system">
-            <tr>
-               <th>System Identifier</th>
-               <td><xsl:value-of select="@system"/></td>
-            </tr>
-         </xsl:if>
-         <!-- Annotation -->
-         <xsl:call-template name="PrintAnnotation">
-            <xsl:with-param name="component" select="."/>
-         </xsl:call-template>
-      </table>
-   </xsl:template>
-
-   <!--
-     Prints out the Properties table for the root
-     schema element.
-     -->
-   <xsl:template match="xsd:schema" mode="properties">
-      <table class="properties">
-         <!-- Target Namespace -->
-         <tr>
-            <th>
-               <xsl:call-template name="PrintGlossaryTermRef">
-                  <xsl:with-param name="code">TargetNS</xsl:with-param>
-                  <xsl:with-param name="term">Target Namespace</xsl:with-param>
-               </xsl:call-template>
-            </th>
-            <td>
-               <xsl:choose>
-                  <xsl:when test="@targetNamespace">
-                     <span class="targetNS">
-                        <xsl:value-of select="@targetNamespace"/>
-                     </span>
-                  </xsl:when>
-                  <xsl:otherwise>
-                     <xsl:text>None</xsl:text>
-                  </xsl:otherwise>
-               </xsl:choose>
-            </td>
-         </tr>
-         <!-- Version -->
-         <xsl:if test="@version">
-            <tr>
-               <th>Version</th>
-               <td><xsl:value-of select="@version"/></td>
-            </tr>
-         </xsl:if>
-         <!-- Language -->
-         <xsl:if test="@xml:lang">
-            <tr>
-               <th>Language</th>
-               <td><xsl:value-of select="@xml:lang"/></td>
-            </tr>
-         </xsl:if>
-         <!-- Element/Attribute Form Defaults -->
-         <tr>
-            <th>Element and Attribute Namespaces</th>
-            <td>
-               <ul>
-                  <li>Global element and attribute declarations belong to this schema's target namespace.</li>
-                  <li>
-                     <xsl:choose>
-                        <xsl:when test="normalize-space(@elementFormDefault)='qualified'">
-                           <xsl:text>By default, local element declarations belong to this schema's target namespace.</xsl:text>
-                        </xsl:when>
-                        <xsl:otherwise>
-                           <xsl:text>By default, local element declarations have no namespace.</xsl:text>
-                        </xsl:otherwise>
-                     </xsl:choose>
-                  </li>
-                  <li>
-                     <xsl:choose>
-                        <xsl:when test="normalize-space(@attributeFormDefault)='qualified'">
-                           <xsl:text>By default, local attribute declarations belong to this schema's target namespace.</xsl:text>
-                        </xsl:when>
-                        <xsl:otherwise>
-                           <xsl:text>By default, local attribute declarations have no namespace.</xsl:text>
-                        </xsl:otherwise>
-                     </xsl:choose>
-                  </li>
-               </ul>
-            </td>
-         </tr>
-         <!-- Schema Composition, e.g. include, import, redefine -->
-         <xsl:if test="xsd:include or xsd:import or xsd:redefine">
-            <tr>
-               <th>Schema Composition</th>
-               <td>
-                  <ul>
-                     <!-- Import -->
-                     <xsl:if test="xsd:import">
-                        <li>
-                           <xsl:text>This schema imports schema(s) from the following namespace(s):</xsl:text>
-                           <ul>
-                           <xsl:for-each select="xsd:import">
-                              <li>
-                                 <em><xsl:value-of select="@namespace"/></em>
-                                 <xsl:if test="@schemaLocation">
-                                    <xsl:text> (at </xsl:text>
-                                    <xsl:call-template name="PrintSchemaLink">
-                                       <xsl:with-param name="uri" select="@schemaLocation"/>
-                                    </xsl:call-template>
-                                    <xsl:text>)</xsl:text>
-                                 </xsl:if>
-                              </li>
-                           </xsl:for-each>
-                           </ul>
-                        </li>
-                     </xsl:if>
-                     <!-- Include -->
-                     <xsl:if test="xsd:include">
-                        <li>
-                           <xsl:text>This schema includes components from the following schema document(s):</xsl:text>
-                           <ul>
-                           <xsl:for-each select="xsd:include">
-                              <li>
-                                 <xsl:call-template name="PrintSchemaLink">
-                                    <xsl:with-param name="uri" select="@schemaLocation"/>
-                                 </xsl:call-template>
-                              </li>
-                           </xsl:for-each>
-                           </ul>
-                        </li>
-                     </xsl:if>
-                     <!-- Redefine -->
-                     <xsl:if test="xsd:redefine">
-                        <li>
-                           <xsl:text>This schema includes components from the following schema document(s), where some of the components have been redefined:</xsl:text>
-                           <ul>
-                              <xsl:for-each select="xsd:redefine">
-                                 <li>
-                                 <xsl:call-template name="PrintSchemaLink">
-                                    <xsl:with-param name="uri" select="@schemaLocation"/>
-                                 </xsl:call-template>
-                                 </li>
-                              </xsl:for-each>
-                           </ul>
-                        <xsl:text>See </xsl:text><a href="#Redefinitions">Redefined Schema Components</a><xsl:text> section.</xsl:text>
-                        </li>
-                     </xsl:if>
-                  </ul>
-               </td>
-            </tr>
-         </xsl:if>
-         <!-- Annotation -->
-         <xsl:call-template name="PrintAnnotation">
-            <xsl:with-param name="component" select="."/>
-         </xsl:call-template>
-      </table>
-   </xsl:template>
-
-   <!--
-     Prints out the Properties table for a top-level
-     simple type definition.
-     -->
-   <xsl:template match="xsd:simpleType" mode="properties">
-      <table class="properties">
-         <!-- Name -->
-         <tr>
-            <th>Name</th>
-            <td><xsl:value-of select="@name"/></td>
-         </tr>
-         <!-- Constraints -->
-         <tr>
-            <th>Content</th>
-            <td>
-               <xsl:call-template name="PrintSimpleConstraints">
-                  <xsl:with-param name="simpleContent" select="."/>
-               </xsl:call-template>
-            </td>
-         </tr>
-         <!-- Final -->
-         <xsl:variable name="final">
-            <xsl:call-template name="PrintSimpleDerivationSet">
-               <xsl:with-param name="EBV">
-                  <xsl:choose>
-                     <xsl:when test="@final">
-                        <xsl:value-of select="@final"/>
-                     </xsl:when>
-                     <xsl:otherwise>
-                        <xsl:value-of select="/xsd:schema/@finalDefault"/>
-                     </xsl:otherwise>
-                  </xsl:choose>
-               </xsl:with-param>
-            </xsl:call-template>
-         </xsl:variable>
-         <xsl:if test="normalize-space($final)!=''">
-            <tr>
-               <th>
-                  <xsl:call-template name="PrintGlossaryTermRef">
-                     <xsl:with-param name="code">TypeFinal</xsl:with-param>
-                     <xsl:with-param name="term">Prohibited Derivations</xsl:with-param>
-                  </xsl:call-template>
-               </th>
-               <td><xsl:value-of select="$final"/></td>
-            </tr>
-         </xsl:if>
-         <!-- Annotation -->
-         <xsl:call-template name="PrintAnnotation">
-            <xsl:with-param name="component" select="."/>
-         </xsl:call-template>
-      </table>
-   </xsl:template>
-
-   <!--
-     Unmatched template for 'properties' mode
-     -->
-   <xsl:template match="*" mode="properties"/>
-
-   <!--
-     Prints out the rows to display 'annotation' elements of an 
-     component in the Properties table. This template assumes it 
-     will be called within an HTML 'table' element.
-        Param(s):
-            component (Node) required
-                Schema component
-     -->
-   <xsl:template name="PrintAnnotation">
-      <xsl:param name="component"/>
-
-      <xsl:if test="$component/xsd:annotation/xsd:documentation">
-         <tr>
-            <th>Documentation</th>
-            <td>
-               <xsl:for-each select="$component/xsd:annotation/xsd:documentation">
-                  <xsl:if test="position()!=1"><br/><br/></xsl:if>
-                  <xsl:apply-templates select="." mode="properties"/>
-               </xsl:for-each>
-            </td>
-         </tr>
-      </xsl:if>
-      <xsl:if test="$component/xsd:annotation/xsd:appinfo">
-         <tr>
-            <th>Application Data</th>
-            <td>
-               <xsl:for-each select="$component/xsd:annotation/xsd:appinfo">
-                  <xsl:if test="position()!=1"><br/><br/></xsl:if>
-                  <xsl:apply-templates select="." mode="properties"/>
-               </xsl:for-each>
-            </td>
-         </tr>
-      </xsl:if>
-   </xsl:template>
-
-   <!--
-     Prints out the constraints of simple content
-     to be displayed within a Properties table.
-     Param(s):
-            simpleContent (Node) required
-                Node containing the simple content
-            typeList (String) optional
-                List of types in this call chain. Name of type starts
-                with '*', and ends with '+'. (Used to prevent infinite
-                recursive loop.)
-   -->
-   <xsl:template name="PrintSimpleConstraints">
-      <xsl:param name="simpleContent"/>
-      <xsl:param name="typeList"/>
-
-      <xsl:choose>
-         <!-- Derivation by restriction -->
-         <xsl:when test="$simpleContent/xsd:restriction">
-            <xsl:call-template name="PrintSimpleRestriction">
-               <xsl:with-param name="restriction" select="$simpleContent/xsd:restriction"/>
-               <xsl:with-param name="typeList" select="$typeList"/>
-            </xsl:call-template>
-         </xsl:when>
-         <!-- Derivation by list -->
-         <xsl:when test="$simpleContent/xsd:list">
-            <ul><li>
-               <xsl:text>List of: </xsl:text>
-               <xsl:choose>
-                  <!-- Globally-defined item type -->
-                  <xsl:when test="$simpleContent/xsd:list/@itemType">
-                     <xsl:call-template name="PrintTypeRef">
-                        <xsl:with-param name="ref" select="$simpleContent/xsd:list/@itemType"/>
-                     </xsl:call-template>
-                  </xsl:when>
-                  <!-- Locally-defined item type -->
-                  <xsl:otherwise>
-                     <ul>
-                        <li>
-                           <xsl:text>Locally defined type:</xsl:text>
-                           <xsl:call-template name="PrintSimpleConstraints">
-                              <xsl:with-param name="simpleContent" select="$simpleContent/xsd:list/xsd:simpleType"/>
-                              <xsl:with-param name="typeList" select="$typeList"/>
-                           </xsl:call-template>
-                        </li>
-                     </ul>
-                  </xsl:otherwise>
-               </xsl:choose>
-            </li></ul>
-         </xsl:when>
-         <!-- Derivation by union -->
-         <xsl:when test="$simpleContent/xsd:union">
-            <ul><li>
-               <xsl:text>Union of following types: </xsl:text>
-               <ul>
-                  <!-- Globally-defined member types -->
-                  <xsl:if test="$simpleContent/xsd:union/@memberTypes">
-                     <xsl:call-template name="PrintWhitespaceList">
-                        <xsl:with-param name="value" select="$simpleContent/xsd:union/@memberTypes"/>
-                        <xsl:with-param name="compType">type</xsl:with-param>
-                        <xsl:with-param name="isInList">true</xsl:with-param>
-                     </xsl:call-template>
-                  </xsl:if>
-                  <!-- Locally-defined member types -->
-                  <xsl:for-each select="$simpleContent/xsd:union/xsd:simpleType">
-                     <li>
-                        <xsl:text>Locally defined type:</xsl:text>
-                        <xsl:call-template name="PrintSimpleConstraints">
-                           <xsl:with-param name="simpleContent" select="."/>
-                           <xsl:with-param name="typeList" select="$typeList"/>
-                        </xsl:call-template>
-                     </li>
-                  </xsl:for-each>
-               </ul>
-            </li></ul>
-         </xsl:when>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Prints out the constraints of simple content derived by 
-     restriction, which is to be displayed in a Properties table.
-     Param(s):
-            restriction (Node) required
-                Node containing the restriction
-            typeList (String) optional
-                List of types in this call chain. Name of type starts
-                with '*', and ends with '+'. (Used to prevent infinite
-                recursive loop.)
-   -->
-   <xsl:template name="PrintSimpleRestriction">
-      <xsl:param name="restriction"/>
-      <xsl:param name="typeList"/>
-
-      <xsl:variable name="typeName" select="$restriction/parent::xsd:simpleType/@name"/>
-
-      <!-- Print out base type info -->
-      <xsl:choose>
-         <!-- Circular type hierarchy -->
-         <xsl:when test="$typeName != '' and contains($typeList, concat('*', $typeName, '+'))">
-            <li>
-               <xsl:call-template name="HandleError">
-                  <xsl:with-param name="isTerminating">false</xsl:with-param>
-                  <xsl:with-param name="errorMsg">
-                     <xsl:text>Circular type reference to '</xsl:text>
-                     <xsl:value-of select="$typeName"/>
-                     <xsl:text>' in type hierarchy.</xsl:text>
-                  </xsl:with-param>
-               </xsl:call-template>
-            </li>
-         </xsl:when>
-         <!-- Locally-defined base type -->
-         <xsl:when test="$restriction/xsd:simpleType">
-            <xsl:call-template name="PrintSimpleConstraints">
-               <xsl:with-param name="simpleContent" select="$restriction/xsd:simpleType"/>
-               <xsl:with-param name="typeList" select="$typeList"/>
-            </xsl:call-template>
-         </xsl:when>
-         <!-- Base type reference -->
-         <xsl:when test="$restriction">
-            <xsl:variable name="baseTypeRef" select="$restriction/@base"/>
-            <xsl:variable name="baseTypeName">
-               <xsl:call-template name="GetRefName">
-                  <xsl:with-param name="ref" select="$baseTypeRef"/>
-               </xsl:call-template>
-            </xsl:variable>
-            <xsl:variable name="baseTypeNS">
-               <xsl:call-template name="GetRefNS">
-                  <xsl:with-param name="ref" select="$baseTypeRef"/>
-               </xsl:call-template>
-            </xsl:variable>
-
-            <xsl:choose>
-               <!-- Base type is built-in XSD type -->
-               <xsl:when test="$baseTypeNS=$XSD_NS">
-                  <ul><li>
-                     <xsl:text>Base XSD Type: </xsl:text>
-                     <xsl:choose>
-                        <!-- Current schema is the schema for XSDL -->
-                        <xsl:when test="normalize-space(/xsd:schema/@targetNamespace)=$XSD_NS">
-                           <xsl:call-template name="PrintTypeRef">
-                              <xsl:with-param name="ref" select="$baseTypeRef"/>
-                           </xsl:call-template>
-                        </xsl:when>
-                        <!-- Current schema is not XSD namespace -->
-                        <xsl:otherwise>
-                           <xsl:value-of select="$baseTypeName"/>
-                        </xsl:otherwise>
-                     </xsl:choose>
-                  </li></ul>
-               </xsl:when>
-               <!-- Other types -->
-               <xsl:otherwise>
-                  <xsl:variable name="baseType" select="key('simpleType', $baseTypeName)"/>
-                  <xsl:choose>
-                     <!-- Base type found -->
-                     <xsl:when test="$baseType">
-                        <xsl:call-template name="PrintSimpleConstraints">
-                           <xsl:with-param name="simpleContent" select="$baseType"/>
-                           <xsl:with-param name="typeList" select="concat($typeList, '*', $typeName, '+')"/>
-                        </xsl:call-template>
-                     </xsl:when>
-                     <!-- Base type not found -->
-                     <xsl:otherwise>
-                        <ul><li><strong>
-                           <xsl:text>'</xsl:text>
-                           <xsl:value-of select="$baseTypeName"/>
-                           <xsl:text>' super type was not found in this schema. </xsl:text>
-                           <xsl:text>Its facets could not be printed out.</xsl:text>
-                        </strong></li></ul>
-                     </xsl:otherwise>
-                  </xsl:choose>
-               </xsl:otherwise>
-            </xsl:choose>
-         </xsl:when>
-      </xsl:choose>
-
-      <!-- Find constraints in current restriction -->
-      <xsl:variable name="enumeration">
-         <xsl:call-template name="PrintEnumFacets">
-            <xsl:with-param name="simpleRestrict" select="$restriction"/>
-         </xsl:call-template>
-      </xsl:variable>
-      <xsl:variable name="pattern">
-         <xsl:call-template name="PrintPatternFacet">
-            <xsl:with-param name="simpleRestrict" select="$restriction"/>
-         </xsl:call-template>
-      </xsl:variable>
-      <xsl:variable name="range">
-         <xsl:call-template name="PrintRangeFacets">
-            <xsl:with-param name="simpleRestrict" select="$restriction"/>
-         </xsl:call-template>
-      </xsl:variable>
-      <xsl:variable name="totalDigits">
-         <xsl:call-template name="PrintTotalDigitsFacet">
-            <xsl:with-param name="simpleRestrict" select="$restriction"/>
-         </xsl:call-template>
-      </xsl:variable>
-      <xsl:variable name="fractionDigits">
-         <xsl:call-template name="PrintFractionDigitsFacet">
-            <xsl:with-param name="simpleRestrict" select="$restriction"/>
-         </xsl:call-template>
-      </xsl:variable>
-      <xsl:variable name="length">
-         <xsl:call-template name="PrintLengthFacets">
-            <xsl:with-param name="simpleRestrict" select="$restriction"/>
-         </xsl:call-template>
-      </xsl:variable>
-      <xsl:variable name="whitespace">
-         <xsl:call-template name="PrintWhitespaceFacet">
-            <xsl:with-param name="simpleRestrict" select="$restriction"/>
-         </xsl:call-template>
-      </xsl:variable>
-
-      <!-- Print out facets -->
-      <xsl:if test="$enumeration!='' or $pattern!='' or $range!='' or $totalDigits!='' or $fractionDigits!='' or $length!='' or $whitespace!=''">
-         <ul>
-            <xsl:if test="$enumeration!=''">
-               <li>
-                  <xsl:copy-of select="$enumeration"/>
-               </li>
-            </xsl:if>
-            <xsl:if test="$pattern!=''">
-               <li>
-                  <xsl:copy-of select="$pattern"/>
-               </li>
-            </xsl:if>
-            <xsl:if test="$range!=''">
-               <li>
-                  <xsl:copy-of select="$range"/>
-               </li>
-            </xsl:if>
-            <xsl:if test="$totalDigits!=''">
-               <li>
-                  <xsl:copy-of select="$totalDigits"/>
-               </li>
-            </xsl:if>
-            <xsl:if test="$fractionDigits!=''">
-               <li>
-                  <xsl:copy-of select="$fractionDigits"/>
-               </li>
-            </xsl:if>
-            <xsl:if test="$length!=''">
-               <li>
-                  <xsl:copy-of select="$length"/>
-               </li>
-            </xsl:if>
-            <xsl:if test="$whitespace!=''">
-               <li>
-                  <xsl:copy-of select="$whitespace"/>
-               </li>
-            </xsl:if>
-         </ul>
-      </xsl:if>
-   </xsl:template>
-
-
-   <!-- ******** XML Instance Representation table ******** -->
-
-   <!-- 
-     Prints out the XML Instance Representation table for a top-level 
-     schema component. 
-     Param(s):
-            component (Node) required
-              Top-level schema component
-     -->
-   <xsl:template name="SampleInstanceTable">
-      <xsl:param name="component"/>
-
-      <!-- Not applicable for simple type definitions and notation 
-      declarations -->
-      <xsl:if test="local-name($component)!='simpleType' and local-name($component)!='notation'">
-         <xsl:variable name="componentID">
-            <xsl:call-template name="GetComponentID">
-               <xsl:with-param name="component" select="$component"/>
-            </xsl:call-template>
-         </xsl:variable>
-
-         <xsl:call-template name="CollapseableBox">
-            <xsl:with-param name="id" select="concat($componentID, '_xibox')"/>
-            <xsl:with-param name="styleClass">sample</xsl:with-param>
-            <xsl:with-param name="caption">XML Instance Representation</xsl:with-param>
-            <xsl:with-param name="contents">
-               <xsl:apply-templates select="$component" mode="sample"/>
-            </xsl:with-param>
-            <xsl:with-param name="isOpened">true</xsl:with-param>
-         </xsl:call-template>
-      </xsl:if>
-   </xsl:template>
-
-   <!--
-     Prints out a sample XML instance representation of an 'all' 
-     model group.
-     Param(s):
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-            isInherited (boolean) optional
-                If true, display elements using 'inherited' CSS class.
-            isNewField (boolean) optional
-                If true, display elements using 'newFields' CSS class.
-            schemaLoc (String) optional
-                Schema file containing this all model group;
-                if in current schema, 'schemaLoc' is set to 'this'
-            typeList (String) optional
-                List of types in this call chain. Name of type starts
-                with '*', and ends with '+'. (Used to prevent infinite
-                recursive loop.)
-     -->
-   <xsl:template match="xsd:all" mode="sample">
-      <xsl:param name="margin">0</xsl:param>
-      <xsl:param name="isInherited">false</xsl:param>
-      <xsl:param name="isNewField">false</xsl:param>
-      <xsl:param name="schemaLoc">this</xsl:param>
-      <xsl:param name="typeList"/>
-
-      <xsl:if test="normalize-space(@maxOccurs)!='0'">
-         <!-- Header -->
-         <span class="group" style="margin-left: {$margin}em">
-            <xsl:text>Start </xsl:text>
-            <xsl:call-template name="PrintGlossaryTermRef">
-               <xsl:with-param name="code">All</xsl:with-param>
-               <xsl:with-param name="term">All</xsl:with-param>
-            </xsl:call-template>
-            <!-- Min/max occurs information-->
-            <xsl:text> </xsl:text>
-            <xsl:call-template name="PrintOccurs">
-               <xsl:with-param name="component" select="."/>
-            </xsl:call-template>
-            <!-- Documentation -->
-            <xsl:call-template name="PrintSampleDocumentation">
-               <xsl:with-param name="component" select="."/>
-            </xsl:call-template>
-         </span><br/>
-
-         <!-- Content -->
-         <xsl:apply-templates select="xsd:*" mode="sample">
-            <xsl:with-param name="margin" select="number($margin) + number($ELEM_INDENT)"/>
-            <xsl:with-param name="isInherited" select="$isInherited"/>
-            <xsl:with-param name="isNewField" select="$isNewField"/>
-            <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-            <xsl:with-param name="typeList" select="$typeList"/>
-         </xsl:apply-templates>
-
-         <!-- Footer -->
-         <span class="group" style="margin-left: {$margin}em">
-            <xsl:text>End All</xsl:text>
-         </span><br/>
-      </xsl:if>
-   </xsl:template>
-
-   <!--
-     Prints out a sample XML instance representation of an element 
-     content wild card.
-     Param(s):
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-     -->
-   <xsl:template match="xsd:any | xsd:anyAttribute" mode="sample">
-      <xsl:param name="margin">0</xsl:param>
-
-      <div class="other" style="margin-left: {$margin}em">
-         <xsl:call-template name="PrintWildcard">
-            <xsl:with-param name="componentType">
-               <xsl:choose>
-                  <xsl:when test="local-name(.)='anyAttribute'">attribute</xsl:when>
-                  <xsl:otherwise>element</xsl:otherwise>
-               </xsl:choose>
-            </xsl:with-param>
-            <xsl:with-param name="namespace" select="@namespace"/>
-            <xsl:with-param name="processContents" select="@processContents"/>
-            <xsl:with-param name="minOccurs" select="@minOccurs"/>
-            <xsl:with-param name="maxOccurs" select="@maxOccurs"/>
-         </xsl:call-template>
-      </div>
-   </xsl:template>
-
-   <!--
-     Prints out a sample XML instance representation 
-     of an attribute declaration.
-     Param(s):
-            subTypeAttrs (String) optional
-                List of attributes in sub-types of the type that 
-                contains this attribute
-            isInherited (boolean) optional
-                If true, display attribute using 'inherited' CSS 
-                class.
-            isNewField (boolean) optional
-                If true, display attribute using 'newFields' CSS 
-                class.
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-            addBR (boolean) optional
-                If true, add <br/> before attribute.
-            schemaLoc (String) optional
-                Schema file containing this attribute declaration;
-                if in current schema, 'schemaLoc' is set to 'this'.
-     -->
-   <xsl:template match="xsd:attribute[@name]" mode="sample">
-      <xsl:param name="subTypeAttrs"/>
-      <xsl:param name="isInherited">false</xsl:param>
-      <xsl:param name="isNewField">false</xsl:param>
-      <xsl:param name="margin">0</xsl:param>
-      <xsl:param name="addBR">false</xsl:param>
-      <xsl:param name="schemaLoc">this</xsl:param>
-
-      <!-- Get attribute namespace -->
-      <xsl:variable name="attrNS">
-         <xsl:call-template name="GetAttributeNS">
-            <xsl:with-param name="attribute" select="."/>
-         </xsl:call-template>
-      </xsl:variable>
-
-      <xsl:choose>
-         <xsl:when test="contains($subTypeAttrs, concat('*', normalize-space($attrNS), '+', normalize-space(@name), '+'))">
-            <!-- IGNORE: Sub type has attribute with same name; 
-                 Sub-type's attribute declaration will override this 
-                 one. -->
-         </xsl:when>
-         <xsl:when test="@use and normalize-space(@use)='prohibited'">
-            <!-- IGNORE: Attribute is prohibited. -->
-         </xsl:when>
-         <xsl:otherwise>
-            <xsl:if test="$addBR!='false'"><br/></xsl:if>
-
-            <span style="margin-left: {$margin}em">
-               <xsl:choose>
-                  <xsl:when test="$isNewField!='false'">
-                     <xsl:attribute name="class">newFields</xsl:attribute>
-                  </xsl:when>
-                  <xsl:when test="$isInherited!='false'">
-                     <xsl:attribute name="class">inherited</xsl:attribute>
-                  </xsl:when>
-               </xsl:choose>
-
-               <xsl:text> </xsl:text>
-               <xsl:variable name="prefix">
-                  <xsl:call-template name="GetAttributePrefix">
-                     <xsl:with-param name="attribute" select="."/>
-                  </xsl:call-template>
-               </xsl:variable>
-               <xsl:call-template name="PrintNSPrefix">
-                  <xsl:with-param name="prefix" select="$prefix"/>
-                  <xsl:with-param name="schemaLoc" select="$schemaLoc"/> 
-               </xsl:call-template>
-               <xsl:value-of select="@name"/>
-               <xsl:text>="</xsl:text>
-
-               <xsl:choose>
-                  <!-- Fixed value is provided -->
-                  <xsl:when test="@fixed">
-                     <span class="fixed">
-                        <xsl:value-of select="@fixed"/>
-                     </span>
-                  </xsl:when>
-                  <!-- Type reference is provided -->
-                  <xsl:when test="@type">
-                     <xsl:call-template name="PrintTypeRef">
-                        <xsl:with-param name="ref" select="@type"/>
-                        <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                     </xsl:call-template>
-                  </xsl:when>
-                  <!-- Local type definition is provided -->
-                  <xsl:when test="xsd:simpleType">
-                     <xsl:apply-templates select="xsd:simpleType" mode="sample">
-                        <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                     </xsl:apply-templates>
-                  </xsl:when>
-                  <xsl:otherwise>
-                     <span class="type">anySimpleType</span>
-                  </xsl:otherwise>
-               </xsl:choose>
-
-               <!-- Don't print occurrence info and documentation
-                    for global attributes. -->
-               <xsl:if test="local-name(..)!='schema'">
-                  <!-- Occurrence info-->
-                  <xsl:text> </xsl:text>
-                  <xsl:call-template name="PrintOccurs">
-                     <xsl:with-param name="component" select="."/>
-                  </xsl:call-template>
-                  <!-- Documentation -->
-                  <xsl:call-template name="PrintSampleDocumentation">
-                     <xsl:with-param name="component" select="."/>
-                  </xsl:call-template>
-               </xsl:if>
-
-               <xsl:text>"</xsl:text>
-            </span>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Prints out a sample XML instance representation 
-     of an attribute reference.
-     Param(s):
-            subTypeAttrs (String) optional
-                List of attribute in sub-types of the type that 
-                contains this attribute
-            isInherited (boolean) optional
-                If true, display attributes using 'inherited' CSS 
-                class.
-            isNewField (boolean) optional
-                If true, display attributes using 'newFields' CSS 
-                class.
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-            addBR (boolean) optional
-                If true, add <br/> before attribute.
-            schemaLoc (String) optional
-                Schema file containing this attribute reference;
-                if in current schema, 'schemaLoc' is set to 'this'
-     -->
-   <xsl:template match="xsd:attribute[@ref]" mode="sample">
-      <xsl:param name="subTypeAttrs"/>
-      <xsl:param name="isInherited">false</xsl:param>
-      <xsl:param name="isNewField">false</xsl:param>
-      <xsl:param name="margin">0</xsl:param>
-      <xsl:param name="addBR">false</xsl:param>
-      <xsl:param name="schemaLoc">this</xsl:param>
-
-      <!-- Get attribute name -->
-      <xsl:variable name="attrName">
-         <xsl:call-template name="GetRefName">
-            <xsl:with-param name="ref" select="@ref"/>
-         </xsl:call-template>
-      </xsl:variable>
-
-      <!-- Get attribute namespace -->
-      <xsl:variable name="attrNS">
-         <xsl:call-template name="GetAttributeNS">
-            <xsl:with-param name="attribute" select="."/>
-         </xsl:call-template>
-      </xsl:variable>
-
-      <xsl:choose>
-         <xsl:when test="contains($subTypeAttrs, concat('*', normalize-space($attrNS), '+', normalize-space($attrName), '+'))">
-            <!-- IGNORE: Sub type has attribute with same name; 
-                 Sub-type's attribute declaration will override this 
-                 one. -->
-         </xsl:when>
-         <xsl:when test="@use and normalize-space(@use)='prohibited'">
-            <!-- IGNORE: Attribute is prohibited. -->
-         </xsl:when>
-         <xsl:otherwise>
-            <xsl:if test="$addBR!='false'"><br/></xsl:if>
-
-            <span style="margin-left: {$margin}em">
-               <xsl:choose>
-                  <xsl:when test="$isNewField!='false'">
-                     <xsl:attribute name="class">newFields</xsl:attribute>
-                  </xsl:when>
-                  <xsl:when test="$isInherited!='false'">
-                     <xsl:attribute name="class">inherited</xsl:attribute>
-                  </xsl:when>
-               </xsl:choose>
-
-               <xsl:text> </xsl:text>
-               <xsl:call-template name="PrintAttributeRef">
-                  <xsl:with-param name="ref" select="@ref"/>
-                  <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-               </xsl:call-template>
-               <xsl:text>="</xsl:text>
-               <!-- Fixed value is provided -->
-               <xsl:if test="@fixed">
-                  <span class="fixed">
-                     <xsl:value-of select="@fixed"/>
-                  </span>
-                  <xsl:text> </xsl:text>
-               </xsl:if>
-               <!-- Print occurs info-->
-               <xsl:call-template name="PrintOccurs">
-                  <xsl:with-param name="component" select="."/>
-               </xsl:call-template>
-               <!-- Documentation -->
-               <xsl:call-template name="PrintSampleDocumentation">
-                  <xsl:with-param name="component" select="."/>
-               </xsl:call-template>
-
-               <xsl:text>"</xsl:text>
-            </span>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Prints out a sample XML instance representation of an attribute 
-     group definition.
-     Param(s):
-            schemaLoc (String) optional
-                Schema file containing this attribute group 
-                definition; if in current schema, 'schemaLoc' is 
-                set to 'this'.
-     -->
-   <xsl:template match="xsd:attributeGroup[@name]" mode="sample">
-      <xsl:param name="schemaLoc">this</xsl:param>
-
-      <xsl:for-each select="xsd:attribute | xsd:attributeGroup | xsd:anyAttribute">
-         <xsl:variable name="addBR">
-            <xsl:choose>
-               <xsl:when test="position()!=1">
-                  <xsl:text>true</xsl:text>
-               </xsl:when>
-               <xsl:otherwise>
-                  <xsl:text>false</xsl:text>
-               </xsl:otherwise>
-            </xsl:choose>
-         </xsl:variable>
-
-         <xsl:apply-templates select="." mode="sample">
-            <xsl:with-param name="addBR" select="$addBR"/>
-            <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-         </xsl:apply-templates>
-      </xsl:for-each>
-   </xsl:template>
-
-   <!--
-     Prints out a sample XML instance representation of an attribute 
-     group reference.
-     Param(s):
-            subTypeAttrs (String) optional
-                List of attributes in sub-types of the type that 
-                contains this attribute group
-            isInherited (boolean) optional
-                If true, display attributes using 'inherited' CSS 
-                class.
-            isNewField (boolean) optional
-                If true, display attributes using 'newFields' CSS 
-                class.
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-            parentGroups (String) optional
-                List of parent attribute group definitions that 
-                contain this attribute group. Used to prevent 
-                infinite loops when displaying attribute group 
-                definitions. In such a case, writes out an error 
-                message and stops processing.
-            schemaLoc (String) optional
-                Schema file containing this attribute group 
-                reference if in current schema, 'schemaLoc' is 
-                set to 'this'.
-     -->
-   <xsl:template match="xsd:attributeGroup[@ref]" mode="sample">
-      <xsl:param name="subTypeAttrs"/>
-      <xsl:param name="isInherited">false</xsl:param>
-      <xsl:param name="isNewField">false</xsl:param>
-      <xsl:param name="margin">0</xsl:param>
-      <xsl:param name="parentGroups"/>
-      <xsl:param name="schemaLoc">this</xsl:param>
-
-      <!-- Get attribute group name -->
-      <xsl:variable name="attrGrpName">
-         <xsl:call-template name="GetRefName">
-            <xsl:with-param name="ref" select="@ref"/>
-         </xsl:call-template>
-      </xsl:variable>
-
-      <xsl:choose>
-         <xsl:when test="contains($parentGroups, concat('*', normalize-space($attrGrpName), '+'))">
-            <!-- Circular attribute group definition -->
-            <xsl:call-template name="HandleError">
-               <xsl:with-param name="isTerminating">false</xsl:with-param>
-               <xsl:with-param name="errorMsg">
-                  <xsl:text>Circular attribute group reference: </xsl:text>
-                  <xsl:value-of select="$attrGrpName"/>
-               </xsl:with-param>
-            </xsl:call-template>
-         </xsl:when>
-         <xsl:otherwise>
-            <!-- Look for attribute group definition -->
-            <xsl:variable name="defLoc">
-               <xsl:call-template name="FindComponent">
-                  <xsl:with-param name="ref" select="@ref"/>
-                  <xsl:with-param name="compType">attribute group</xsl:with-param>
-               </xsl:call-template>
-            </xsl:variable>
-
-            <xsl:choose>
-               <!-- Not found -->
-               <xsl:when test="normalize-space($defLoc)='' or normalize-space($defLoc)='none' or normalize-space($defLoc)='xml' or normalize-space($defLoc)='xsd'">
-                  <div class="other" style="margin-left: {$margin}em">
-                     <xsl:text>Attribute group reference (not shown): </xsl:text>
-                     <xsl:call-template name="PrintAttributeGroupRef">
-                        <xsl:with-param name="ref" select="@ref"/>
-                        <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                     </xsl:call-template>
-                     <!-- Documentation -->
-                     <xsl:call-template name="PrintSampleDocumentation">
-                        <xsl:with-param name="component" select="."/>
-                     </xsl:call-template>
-                  </div>
-               </xsl:when>
-               <!-- Found in current schema -->
-               <xsl:when test="normalize-space($defLoc)='this'">
-                  <xsl:variable name="attrGrpDef" select="key('attributeGroup', $attrGrpName)"/>
-                  <xsl:apply-templates select="$attrGrpDef/xsd:attribute | $attrGrpDef/xsd:attributeGroup" mode="sample">
-                     <xsl:with-param name="subTypeAttrs" select="$subTypeAttrs"/>
-                     <xsl:with-param name="isInherited" select="$isInherited"/>
-                     <xsl:with-param name="isNewField" select="$isNewField"/>
-                     <xsl:with-param name="parentGroups" select="concat($parentGroups, concat('*', normalize-space($attrGrpName), '+'))"/>
-                     <xsl:with-param name="margin" select="$margin"/>
-                     <xsl:with-param name="addBR">true</xsl:with-param>
-                     <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                  </xsl:apply-templates>
-               </xsl:when>
-               <!-- Found in external schema -->
-               <xsl:otherwise>
-                  <xsl:variable name="attrGrpDef" select="document($defLoc)/xsd:schema/xsd:attributeGroup[@name=$attrGrpName]"/>
-                  <xsl:apply-templates select="$attrGrpDef/xsd:attribute | $attrGrpDef/xsd:attributeGroup" mode="sample">
-                     <xsl:with-param name="subTypeAttrs" select="$subTypeAttrs"/>
-                     <xsl:with-param name="isInherited" select="$isInherited"/>
-                     <xsl:with-param name="isNewField" select="$isNewField"/>
-                     <xsl:with-param name="parentGroups" select="concat($parentGroups, concat('*', normalize-space($attrGrpName), '+'))"/>
-                     <xsl:with-param name="margin" select="$margin"/>
-                     <xsl:with-param name="addBR">true</xsl:with-param>
-                     <xsl:with-param name="schemaLoc" select="$defLoc"/>
-                  </xsl:apply-templates>
-               </xsl:otherwise>
-            </xsl:choose>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Prints out a sample XML instance representation of a 'choice' 
-     model group.
-     Param(s):
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-            isInherited (boolean) optional
-                If true, display elements using'inherited' CSS class.
-            isNewField (boolean) optional
-                If true, display elements using 'newFields' CSS class.
-            parentGroups (String) optional
-                List of parent model group definitions that contain this 
-                model group. Used to prevent infinite loops when 
-                displaying model group definitions.
-            schemaLoc (String) optional
-                Schema file containing this choice model group;
-                if in current schema, 'schemaLoc' is set to 'this'
-            typeList (String) optional
-                List of types in this call chain. Name of type starts
-                with '*', and ends with '+'. (Used to prevent infinite
-                recursive loop.)
-     -->
-   <xsl:template match="xsd:choice" mode="sample">
-      <xsl:param name="margin">0</xsl:param>
-      <xsl:param name="isInherited">false</xsl:param>
-      <xsl:param name="isNewField">false</xsl:param>
-      <xsl:param name="parentGroups"/>
-      <xsl:param name="schemaLoc">this</xsl:param>
-      <xsl:param name="typeList"/>
-
-      <xsl:if test="normalize-space(@maxOccurs)!='0'">
-         <!-- Header -->
-         <span class="group" style="margin-left: {$margin}em">
-            <xsl:text>Start </xsl:text>
-            <xsl:call-template name="PrintGlossaryTermRef">
-               <xsl:with-param name="code">Choice</xsl:with-param>
-               <xsl:with-param name="term">Choice</xsl:with-param>
-            </xsl:call-template>
-            <!-- Min/max occurrence -->
-            <xsl:text> </xsl:text>
-            <xsl:call-template name="PrintOccurs">
-               <xsl:with-param name="component" select="."/>
-            </xsl:call-template>
-            <!-- Documentation -->
-            <xsl:call-template name="PrintSampleDocumentation">
-               <xsl:with-param name="component" select="."/>
-            </xsl:call-template>
-         </span><br/>
-
-         <!-- Content -->
-         <xsl:apply-templates select="xsd:*" mode="sample">
-            <xsl:with-param name="margin" select="number($margin)+number($ELEM_INDENT)"/>
-            <xsl:with-param name="isInherited" select="$isInherited"/>
-            <xsl:with-param name="isNewField" select="$isNewField"/>
-            <xsl:with-param name="parentGroups" select="$parentGroups"/>
-            <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-            <xsl:with-param name="typeList" select="$typeList"/>
-         </xsl:apply-templates>
-
-         <!-- Footer -->
-         <span class="group" style="margin-left: {$margin}em">
-            <xsl:text>End Choice</xsl:text>
-         </span><br/>
-      </xsl:if>
-   </xsl:template>
-
-   <!--
-     Prints out a sample XML instance from a complex type definition.
-     Param(s):
-            schemaLoc (String) optional
-                Schema file containing this complex type definition; 
-                if in current schema, 'schemaLoc' is set to 'this'.
-     -->
-   <xsl:template match="xsd:complexType" mode="sample">
-      <xsl:param name="schemaLoc">this</xsl:param>
-      <xsl:param name="parentGroups"/>
-
-      <xsl:call-template name="PrintSampleComplexElement">
-         <xsl:with-param name="type" select="."/>
-         <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-	 <xsl:with-param name="parentGroups" select="$parentGroups"/>
-      </xsl:call-template>
-   </xsl:template>
-
-   <!--
-     Prints out a sample XML instance from an element declaration.
-     Param(s):
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-            isInherited (boolean) optional
-                If true, display elements using 'inherited' CSS class.
-            isNewField (boolean) optional
-                If true, display elements using 'newFields' CSS class.
-            schemaLoc (String) optional
-                Schema file containing this element declaration; 
-                if in current schema, 'schemaLoc' is set to 'this'.
-            typeList (String) optional
-                List of types in this call chain. Name of type starts
-                with '*', and ends with '+'. (Used to prevent infinite
-                recursive loop.)
-     -->
-   <xsl:template match="xsd:element[@name]" mode="sample">
-      <xsl:param name="margin">0</xsl:param>
-      <xsl:param name="isInherited">false</xsl:param>
-      <xsl:param name="isNewField">false</xsl:param>
-      <xsl:param name="schemaLoc">this</xsl:param>
-      <xsl:param name="typeList"/>
-      <xsl:param name="parentGroups"/>
-
-      <xsl:choose>
-         <!-- Prohibited element declaration -->
-         <xsl:when test="normalize-space(@maxOccurs)='0'">
-            <!-- IGNORE if max occurs is zero -->
-         </xsl:when>
-         <!-- Global element declaration -->
-         <xsl:when test="local-name(..)='schema'">
-            <xsl:choose>
-               <!-- With type reference -->
-               <xsl:when test="@type">
-                  <xsl:variable name="elemTypeName">
-                     <xsl:call-template name="GetRefName">
-                        <xsl:with-param name="ref" select="@type"/>
-                     </xsl:call-template>
-                  </xsl:variable>
-
-                  <!-- Look for complex type definition -->
-                  <xsl:variable name="defLoc">
-                     <xsl:call-template name="FindComponent">
-                        <xsl:with-param name="ref" select="@type"/>
-                        <xsl:with-param name="compType">complex type</xsl:with-param>
-                     </xsl:call-template>
-                  </xsl:variable>
-
-                  <xsl:choose>
-                     <!-- Complex type was found in current 
-                          schema. -->
-                     <xsl:when test="normalize-space($defLoc)='this'">
-                        <xsl:variable name="ctype" select="key('complexType', $elemTypeName)"/>
-                        <xsl:call-template name="PrintSampleComplexElement">
-                           <xsl:with-param name="element" select="."/>
-                           <xsl:with-param name="type" select="$ctype"/>
-			   <xsl:with-param name="parentGroups" select="$parentGroups"/>
-                        </xsl:call-template>
-                     </xsl:when>
-                     <!-- Complex type was not found. -->
-                     <xsl:when test="normalize-space($defLoc)='' or normalize-space($defLoc)='none' or normalize-space($defLoc)='xml' or normalize-space($defLoc)='xsd'">
-                        <xsl:call-template name="PrintSampleSimpleElement">
-                           <xsl:with-param name="element" select="."/>
-                           <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                        </xsl:call-template>
-                     </xsl:when>
-                     <!-- Complex type was found in external
-                          schema. -->
-                     <xsl:otherwise>
-                        <xsl:variable name="ctype" select="document($defLoc)/xsd:schema/xsd:complexType[@name=$elemTypeName]"/>
-                        <xsl:call-template name="PrintSampleComplexElement">
-                           <xsl:with-param name="element" select="."/>
-                           <xsl:with-param name="type" select="$ctype"/>
-			   <xsl:with-param name="parentGroups" select="$parentGroups"/>
-                        </xsl:call-template>
-                     </xsl:otherwise>
-                  </xsl:choose>
-               </xsl:when>
-               <!-- With local complex type definition -->
-               <xsl:when test="xsd:complexType">
-                  <xsl:call-template name="PrintSampleComplexElement">
-                     <xsl:with-param name="element" select="."/>
-                     <xsl:with-param name="type" select="xsd:complexType"/>
-                     <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                     <xsl:with-param name="parentGroups" select="$parentGroups"/>
-                  </xsl:call-template>
-               </xsl:when>
-               <xsl:otherwise>
-                  <xsl:call-template name="PrintSampleSimpleElement">
-                     <xsl:with-param name="element" select="."/>
-                     <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                  </xsl:call-template>
-               </xsl:otherwise>
-            </xsl:choose>
-         </xsl:when>
-         <!-- Local element declaration -->
-         <xsl:otherwise>
-            <xsl:choose>
-               <!-- With local complex type definition -->
-               <xsl:when test="xsd:complexType">
-                  <xsl:call-template name="PrintSampleComplexElement">
-                     <xsl:with-param name="element" select="."/>
-                     <xsl:with-param name="type" select="xsd:complexType"/>
-                     <xsl:with-param name="margin" select="$margin"/>
-                     <xsl:with-param name="isInherited" select="$isInherited"/>
-                     <xsl:with-param name="isNewField" select="$isNewField"/>
-                     <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                     <xsl:with-param name="typeList" select="$typeList"/>
-                     <xsl:with-param name="parentGroups" select="$parentGroups"/>
-                  </xsl:call-template>
-               </xsl:when>
-               <xsl:otherwise>
-                  <xsl:call-template name="PrintSampleSimpleElement">
-                     <xsl:with-param name="element" select="."/>
-                     <xsl:with-param name="margin" select="$margin"/>
-                     <xsl:with-param name="isInherited" select="$isInherited"/>
-                     <xsl:with-param name="isNewField" select="$isNewField"/>
-                     <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                     <xsl:with-param name="typeList" select="$typeList"/>
-                  </xsl:call-template>
-               </xsl:otherwise>
-            </xsl:choose>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Prints out a sample XML instance from an element
-     reference.
-     Param(s):
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-            isInherited (boolean) optional
-                If true, display elements using 'inherited' CSS class.
-            isNewField (boolean) optional
-                If true, display elements using 'newFields' CSS class.
-            schemaLoc (String) optional
-                Schema file containing this element reference; 
-                if in current schema, 'schemaLoc' is set to 'this'.
-     -->
-   <xsl:template match="xsd:element[@ref]" mode="sample">
-      <xsl:param name="margin">0</xsl:param>
-      <xsl:param name="isInherited">false</xsl:param>
-      <xsl:param name="isNewField">false</xsl:param>
-      <xsl:param name="schemaLoc">this</xsl:param>
-
-      <xsl:if test="normalize-space(@maxOccurs)!='0'">
-         <xsl:call-template name="PrintSampleSimpleElement">
-            <xsl:with-param name="element" select="."/>
-            <xsl:with-param name="margin" select="$margin"/>
-            <xsl:with-param name="isInherited" select="$isInherited"/>
-            <xsl:with-param name="isNewField" select="$isNewField"/>
-            <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-         </xsl:call-template>
-      </xsl:if>
-   </xsl:template>
-
-   <!--
-     Prints out a sample XML instance from a group definition.
-     Param(s):
-            schemaLoc (String) optional
-                Schema file containing this model group definition;
-                if in current schema, 'schemaLoc' is set to 'this'
-            typeList (String) optional
-                List of types in this call chain. Name of type starts
-                with '*', and ends with '+'. (Used to prevent infinite
-                recursive loop.)
-     -->
-   <xsl:template match="xsd:group[@name]" mode="sample">
-      <xsl:param name="schemaLoc">this</xsl:param>
-      <xsl:param name="typeList"/>
-
-      <xsl:apply-templates select="xsd:*" mode="sample">
-         <xsl:with-param name="parentGroups" select="concat('*', normalize-space(@name), '+')"/>
-         <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-         <xsl:with-param name="typeList" select="$typeList"/>
-      </xsl:apply-templates>
-   </xsl:template>
-
-   <!--
-     Prints out a sample XML instance from a group reference.
-     Param(s):
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-            isInherited (boolean) optional
-                If true, display elements using 'inherited' CSS 
-                class.
-            isNewField (boolean) optional
-                If true, display elements using 'newFields' CSS 
-                class.
-            parentGroups (String) optional
-                List of parent model group definitions that contain 
-                this  model group. Used to prevent infinite loops 
-                when displaying model group definitions.
-            schemaLoc (String) optional
-                Schema file containing this model group reference;
-                if in current schema, 'schemaLoc' is set to 'this'
-            typeList (String) optional
-                List of types in this call chain. Name of type starts
-                with '*', and ends with '+'. (Used to prevent infinite
-                recursive loop.)
-     -->
-   <xsl:template match="xsd:group[@ref]" mode="sample">
-      <xsl:param name="margin">0</xsl:param>
-      <xsl:param name="isInherited">false</xsl:param>
-      <xsl:param name="isNewField">false</xsl:param>
-      <xsl:param name="parentGroups"/>
-      <xsl:param name="schemaLoc">this</xsl:param>
-      <xsl:param name="typeList"/>
-
-      <!-- Get group name -->
-      <xsl:variable name="grpName">
-         <xsl:call-template name="GetRefName">
-            <xsl:with-param name="ref" select="@ref"/>
-         </xsl:call-template>
-      </xsl:variable>
-
-      <!-- Create link to the group definition -->
-      <xsl:variable name="grpLink">
-         <xsl:call-template name="PrintGroupRef">
-            <xsl:with-param name="ref" select="@ref"/>
-            <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-         </xsl:call-template>
-      </xsl:variable>
-
-      <!-- Get occurrence info -->
-      <xsl:variable name="occursInfo">
-         <xsl:call-template name="PrintOccurs">
-            <xsl:with-param name="component" select="."/>
-         </xsl:call-template>
-      </xsl:variable>
-
-      <xsl:choose>
-         <!-- Circular group definition -->
-         <xsl:when test="contains($parentGroups, concat('*', normalize-space($grpName), '+'))">
-            <!-- Don't show contents -->
-            <div class="other" style="margin-left: {$margin}em">
-               <xsl:text>Circular model group reference: </xsl:text>
-               <xsl:copy-of select="$grpLink"/>
-               <!-- Occurrence info -->
-               <xsl:text> </xsl:text>
-               <xsl:copy-of select="$occursInfo"/>
-               <!-- Documentation -->
-               <xsl:call-template name="PrintSampleDocumentation">
-                  <xsl:with-param name="component" select="."/>
-               </xsl:call-template>
-            </div>
-         </xsl:when>
-         <xsl:otherwise>
-            <!-- Look for group definition -->
-            <xsl:variable name="grpDefLoc">
-               <xsl:call-template name="FindComponent">
-                  <xsl:with-param name="ref" select="@ref"/>
-                  <xsl:with-param name="compType">group</xsl:with-param>
-               </xsl:call-template>
-            </xsl:variable>
-
-            <xsl:choose>
-               <!-- Not found -->
-               <xsl:when test="normalize-space($grpDefLoc)='' or normalize-space($grpDefLoc)='none' or normalize-space($grpDefLoc)='xml' or normalize-space($grpDefLoc)='xsd'">
-                  <div class="other" style="margin-left: {$margin}em">
-                     <xsl:text>Model group reference (not shown): </xsl:text>
-                     <xsl:copy-of select="$grpLink"/>
-                     <!-- Occurrence info -->
-                     <xsl:text> </xsl:text>
-                     <xsl:copy-of select="$occursInfo"/>
-                     <!-- Documentation -->
-                     <xsl:call-template name="PrintSampleDocumentation">
-                        <xsl:with-param name="component" select="."/>
-                     </xsl:call-template>
-                  </div>
-               </xsl:when>
-               <!-- Found in current schema -->
-               <xsl:when test="normalize-space($grpDefLoc)='this'">
-                  <xsl:variable name="grpDef" select="key('group', $grpName)"/>
-                  <xsl:call-template name="PrintSampleGroup">
-                     <xsl:with-param name="margin" select="$margin"/>
-                     <xsl:with-param name="isInherited" select="$isInherited"/>
-                     <xsl:with-param name="isNewField" select="$isNewField"/>
-                     <xsl:with-param name="parentGroups" select="concat($parentGroups, concat('*', normalize-space($grpName), '+'))"/>
-                     <xsl:with-param name="occursInfo" select="$occursInfo"/>
-                     <xsl:with-param name="grpLink" select="$grpLink"/>
-                     <xsl:with-param name="grpRef" select="."/>
-                     <xsl:with-param name="grpDef" select="$grpDef"/>
-                     <xsl:with-param name="grpDefLoc" select="$grpDefLoc"/>
-                     <xsl:with-param name="typeList" select="$typeList"/>
-                  </xsl:call-template>
-               </xsl:when>
-               <!-- Found in external schema -->
-               <xsl:otherwise>
-                  <xsl:variable name="grpDef" select="document($grpDefLoc)/xsd:schema/xsd:group[@name=$grpName]"/>
-                  <xsl:call-template name="PrintSampleGroup">
-                     <xsl:with-param name="margin" select="$margin"/>
-                     <xsl:with-param name="isInherited" select="$isInherited"/>
-                     <xsl:with-param name="isNewField" select="$isNewField"/>
-                     <xsl:with-param name="parentGroups" select="concat($parentGroups, concat('*', normalize-space($grpName), '+'))"/>
-                     <xsl:with-param name="occursInfo" select="$occursInfo"/>
-                     <xsl:with-param name="grpLink" select="$grpLink"/>
-                     <xsl:with-param name="grpRef" select="."/>
-                     <xsl:with-param name="grpDef" select="$grpDef"/>
-                     <xsl:with-param name="grpDefLoc" select="$grpDefLoc"/>
-                     <xsl:with-param name="typeList" select="$typeList"/>
-                  </xsl:call-template>
-               </xsl:otherwise>
-            </xsl:choose>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Prints out a sample XML instance from a 'sequence' model group.
-     Param(s):
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-            isInherited (boolean) optional
-                If true, display elements using 'inherited' CSS class.
-            isNewField (boolean) optional
-                If true, display elements using 'newFields' CSS class.
-            parentGroups (String) optional
-                List of parent model group definitions that contain 
-                this model group. Used to prevent infinite loops when 
-                displaying model group definitions.
-            schemaLoc (String) optional
-                Schema file containing this sequence model group;
-                if in current schema, 'schemaLoc' is set to 'this'
-            typeList (String) optional
-                List of types in this call chain. Name of type starts
-                with '*', and ends with '+'. (Used to prevent infinite
-                recursive loop.)
-     -->
-   <xsl:template match="xsd:sequence" mode="sample">
-      <xsl:param name="margin">0</xsl:param>
-      <xsl:param name="isInherited">false</xsl:param>
-      <xsl:param name="isNewField">false</xsl:param>
-      <xsl:param name="parentGroups"/>
-      <xsl:param name="schemaLoc">this</xsl:param>
-      <xsl:param name="typeList"/>
-
-      <xsl:if test="normalize-space(@maxOccurs)!='0'">
-         <!-- Get occurrence info -->
-         <xsl:variable name="occursInfo">
-            <xsl:call-template name="PrintOccurs">
-               <xsl:with-param name="component" select="."/>
-            </xsl:call-template>
-         </xsl:variable>
-
-         <!-- Header -->
-         <xsl:if test="normalize-space($occursInfo)!='[1]'">
-            <!-- Don't display header if min/max occurs is one. -->
-            <span class="group" style="margin-left: {$margin}em">
-               <xsl:text>Start </xsl:text>
-               <xsl:call-template name="PrintGlossaryTermRef">
-                  <xsl:with-param name="code">Sequence</xsl:with-param>
-                  <xsl:with-param name="term">Sequence</xsl:with-param>
-               </xsl:call-template>
-
-               <xsl:text> </xsl:text>
-               <xsl:copy-of select="$occursInfo"/>
-               <!-- Documentation -->
-               <xsl:call-template name="PrintSampleDocumentation">
-                  <xsl:with-param name="component" select="."/>
-               </xsl:call-template>
-            </span><br/>
-         </xsl:if>
-
-         <xsl:apply-templates select="xsd:*" mode="sample">
-            <xsl:with-param name="margin">
-               <xsl:choose>
-                  <xsl:when test="normalize-space($occursInfo)='[1]'">
-                     <xsl:value-of select="$margin"/>
-                  </xsl:when>
-                  <xsl:otherwise>
-                     <xsl:value-of select="number($margin)+number($ELEM_INDENT)"/>
-                  </xsl:otherwise>
-               </xsl:choose>
-            </xsl:with-param>
-            <xsl:with-param name="isInherited" select="$isInherited"/>
-            <xsl:with-param name="isNewField" select="$isNewField"/>
-            <xsl:with-param name="parentGroups" select="$parentGroups"/>
-            <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-            <xsl:with-param name="typeList" select="$typeList"/>
-         </xsl:apply-templates>
-
-         <!-- Footer -->
-         <xsl:if test="normalize-space($occursInfo)!='[1]'">
-            <!-- Don't display footer if min/max occurs is one. -->
-            <span class="group" style="margin-left: {$margin}em">
-               <xsl:text>End Sequence</xsl:text>
-            </span><br/>
-         </xsl:if>
-      </xsl:if>
-   </xsl:template>
-
-   <!--
-     Prints out the constraints of a complex type with simple content 
-     to be displayed within a sample XML instance.
-     Param(s):
-            schemaLoc (String) optional
-                Schema file containing this simple content 
-                restriction; if in current schema, 'schemaLoc' is 
-                set to 'this'
-     -->
-   <xsl:template match="xsd:simpleContent[xsd:restriction]" mode="sample">
-      <xsl:param name="schemaLoc">this</xsl:param>
-
-      <span class="constraint">
-         <xsl:call-template name="PrintSampleSimpleRestriction">
-            <xsl:with-param name="restriction" select="./xsd:restriction"/>
-            <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-         </xsl:call-template>
-      </span>
-   </xsl:template>
-
-   <!--
-     Prints out the constraints of a simple type definition to be 
-     displayed within a sample XML instance.
-     Param(s):
-            schemaLoc (String) optional
-                Schema file containing this simple type definition; 
-                if in current schema, 'schemaLoc' is set to 'this'
-     -->
-   <xsl:template match="xsd:simpleType" mode="sample">
-      <xsl:param name="schemaLoc">this</xsl:param>
-
-      <span class="constraint">
-         <xsl:call-template name="PrintSampleSimpleConstraints">
-            <xsl:with-param name="simpleContent" select="."/>
-            <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-         </xsl:call-template>
-      </span>
-   </xsl:template>
-
-   <!--
-     Prints out the identity constraints of an element to be displayed 
-     within a sample XML instance.
-     Param(s):
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-            schemaLoc (String) optional
-                Schema file containing this simple type definition; 
-                if in current schema, 'schemaLoc' is set to 'this'
-     -->
-   <xsl:template match="xsd:unique | xsd:key | xsd:keyref" mode="sample">
-      <xsl:param name="margin">0</xsl:param>
-      <xsl:param name="schemaLoc">this</xsl:param>
-
-      <div class="other" style="margin-left: {$margin}em">
-         <xsl:text>&lt;!-- </xsl:text><br/>
-
-         <xsl:choose>
-            <xsl:when test="local-name(.)='unique'">
-               <xsl:call-template name="PrintGlossaryTermRef">
-                  <xsl:with-param name="code">Unique</xsl:with-param>
-                  <xsl:with-param name="term">Uniqueness</xsl:with-param>
-               </xsl:call-template>
-            </xsl:when>
-            <xsl:when test="local-name(.)='key'">
-               <xsl:call-template name="PrintGlossaryTermRef">
-                  <xsl:with-param name="code">Key</xsl:with-param>
-                  <xsl:with-param name="term">Key</xsl:with-param>
-               </xsl:call-template>
-            </xsl:when>
-            <xsl:otherwise>
-               <xsl:call-template name="PrintGlossaryTermRef">
-                  <xsl:with-param name="code">KeyRef</xsl:with-param>
-                  <xsl:with-param name="term">Key Reference</xsl:with-param>
-               </xsl:call-template>
-            </xsl:otherwise>
-         </xsl:choose>
-         <xsl:text> Constraint - </xsl:text>
-         <strong>
-            <xsl:choose>
-               <xsl:when test="local-name(.)='keyref'">
-                  <xsl:value-of select="@name"/>
-               </xsl:when>
-               <xsl:otherwise>
-                  <xsl:variable name="componentID">
-                     <xsl:call-template name="GetComponentID">
-                        <xsl:with-param name="component" select="."/>
-                     </xsl:call-template>
-                  </xsl:variable>
-                  <a name="{$componentID}"><xsl:value-of select="@name"/></a>
-               </xsl:otherwise>
-            </xsl:choose>
-         </strong><br/>
-
-         <xsl:text>Selector - </xsl:text>
-         <strong>
-            <xsl:value-of select="xsd:selector/@xpath"/>
-         </strong><br/>
-
-         <xsl:text>Field(s) - </xsl:text>
-         <xsl:for-each select="xsd:field">
-            <xsl:if test="position()!=1">
-               <xsl:text>, </xsl:text>
-            </xsl:if>
-            <strong>
-               <xsl:value-of select="@xpath"/>
-            </strong>
-         </xsl:for-each>
-         <br/>
-
-         <xsl:if test="local-name(.)='keyref'">
-            <xsl:text>Refers to - </xsl:text>
-            <xsl:call-template name="PrintKeyRef">
-               <xsl:with-param name="ref" select="@refer"/>
-               <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-            </xsl:call-template>
-            <br/>
-         </xsl:if>
-
-         <xsl:text>--></xsl:text>
-      </div>
-   </xsl:template>
-
-   <!--
-     Unmatched template for 'sample' mode
-     -->
-   <xsl:template match="*" mode="sample"/>
-
-   <!--
-     Prints out a link which will open up a window, displaying a 
-     schema component's documentation.
-     Param(s):
-            component (Node) required
-                Schema component
-  -->
-   <xsl:template name="PrintSampleDocumentation">
-      <xsl:param name="component"/>
-
-      <xsl:if test="normalize-space(translate($useJavaScript,'TRUE','true'))='true' and $component and $component/xsd:annotation/xsd:documentation">
-         <xsl:variable name="documentation">
-            <xsl:for-each select="$component/xsd:annotation/xsd:documentation">
-               <!-- Check for two dashes, which will break the JavaScript 
-                    code -->
-               <xsl:if test="contains(., '--') or contains(@source, '--')">
-                  <xsl:call-template name="HandleError">
-                     <xsl:with-param name="isTerminating">true</xsl:with-param>
-                     <xsl:with-param name="errorMsg">
-A local schema component contains two dashes in 
-'documentation' elements within its 'annotation' element.
-                     </xsl:with-param>
-                  </xsl:call-template>
-               </xsl:if>
-
-               <xsl:if test="position()!=1">
-                  <xsl:text>,</xsl:text>
-               </xsl:if>
-               <xsl:text>'</xsl:text>
-               <xsl:choose>
-                  <xsl:when test="@source">
-                     <xsl:text>More information at: </xsl:text>
-                     <xsl:call-template name="EscapeQuotes">
-                        <xsl:with-param name="value" select="@source"/>
-                     </xsl:call-template>
-                     <xsl:text>.</xsl:text>
-                  </xsl:when>
-                  <xsl:when test="normalize-space(.)!=''">
-                     <xsl:call-template name="EscapeQuotes">
-                        <xsl:with-param name="value" select="normalize-space(.)"/>
-                     </xsl:call-template>
-                  </xsl:when>
-               </xsl:choose>
-               <xsl:text>'</xsl:text>
-            </xsl:for-each>
-         </xsl:variable>
-
-         <xsl:text> </xsl:text>
-         <a href="javascript:void(0)" title="View Documentation" class="documentation">
-            <!-- onclick attribute -->
-            <xsl:attribute name="onclick">
-               <xsl:text>docArray = new Array(</xsl:text>
-               <xsl:value-of select="$documentation"/>
-               <xsl:text>); viewDocumentation('</xsl:text>
-               <xsl:call-template name="GetComponentDescription">
-                  <xsl:with-param name="component" select="$component"/>
-               </xsl:call-template>
-               <xsl:text>', '</xsl:text>
-               <xsl:choose>
-                  <xsl:when test="$component/@name">
-                     <xsl:value-of select="$component/@name"/>
-                  </xsl:when>
-                  <xsl:when test="$component/@ref">
-                     <xsl:call-template name="GetRefName">
-                        <xsl:with-param name="ref" select="$component/@ref"/>
-                     </xsl:call-template>
-                  </xsl:when>
-               </xsl:choose>
-               <xsl:text>', docArray);</xsl:text>
-            </xsl:attribute>
-            <xsl:text>?</xsl:text>
-         </a>
-      </xsl:if>
-   </xsl:template>
-
-   <!--
-     Translates occurrences of single and double quotes
-     in a piece of text with single and double quote
-     escape characters.
-     Param(s):
-            value (String) required
-                Text to translate
-     -->
-   <xsl:template name="EscapeQuotes">
-      <xsl:param name="value"/>
-
-      <xsl:variable name="noSingleQuotes">
-         <xsl:call-template name="TranslateStr">
-            <xsl:with-param name="value" select="$value"/>
-            <xsl:with-param name="strToReplace">'</xsl:with-param>
-            <xsl:with-param name="replacementStr">\'</xsl:with-param>
-         </xsl:call-template>
-      </xsl:variable>
-      <xsl:variable name="noDoubleQuotes">
-         <xsl:call-template name="TranslateStr">
-            <xsl:with-param name="value" select="$noSingleQuotes"/>
-            <xsl:with-param name="strToReplace">"</xsl:with-param>
-            <xsl:with-param name="replacementStr">\"</xsl:with-param>
-         </xsl:call-template>
-      </xsl:variable>
-      <xsl:value-of select="$noDoubleQuotes"/>
-   </xsl:template>
-
-   <!--
-     Helper template for template, match="xsd:group[@ref]" 
-     mode="sample". Basically prints out a group reference, for 
-     which we are able to look up the group definition that it
-     is referring to. This template is a work-around because XSLT
-     doesn't have variables (in the traditional sense of 
-     programming languages) and it doesn't allow you to query
-     result tree fragments. 
-     Param(s):
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-            isInherited (boolean) optional
-                If true, display elements using 'inherited' CSS class.
-            isNewField (boolean) optional
-                If true, display elements using 'newFields' CSS class.
-            parentGroups (String) optional
-                List of parent model group definitions that contain this 
-                model group. Used to prevent infinite loops when 
-                displaying model group definitions.
-            occursInfo (Result tree fragment) required
-                Pre-formatted occurrence info of group reference
-            grpLink (Result tree fragment) required
-                Pre-formatted <a> link representing group reference
-            grpRef (Node) required
-                Group reference
-            grpDef (Node) required
-                Group definition that the reference is pointing to
-            grpDefLoc (String) optional
-                Schema file containing 'grpDef' group definition;
-                if current schema, 'schemaLoc' is set to 'this'
-            typeList (String) optional
-                List of types in this call chain. Name of type starts
-                with '*', and ends with '+'. (Used to prevent infinite
-                recursive loop.)
-     -->
-   <xsl:template name="PrintSampleGroup">
-      <xsl:param name="margin">0</xsl:param>
-      <xsl:param name="isInherited">false</xsl:param>
-      <xsl:param name="isNewField">false</xsl:param>
-      <xsl:param name="parentGroups"/>
-      <xsl:param name="occursInfo"/>
-      <xsl:param name="grpLink"/>
-      <xsl:param name="grpRef"/>
-      <xsl:param name="grpDef"/>
-      <xsl:param name="grpDefLoc">this</xsl:param>
-      <xsl:param name="typeList"/>
-
-      <!-- Header -->
-      <xsl:if test="normalize-space($occursInfo)!='[1]'">
-         <!-- Don't print out header if min/max occurs is one. -->
-         <span class="group" style="margin-left: {$margin}em">
-            <xsl:text>Start Group: </xsl:text>
-            <xsl:copy-of select="$grpLink"/>
-            <!-- Occurrence info -->
-            <xsl:text> </xsl:text>
-            <xsl:copy-of select="$occursInfo"/>
-            <!-- Documentation -->
-            <xsl:call-template name="PrintSampleDocumentation">
-               <xsl:with-param name="component" select="$grpRef"/>
-            </xsl:call-template>
-         </span><br/>
-      </xsl:if>
-
-      <!-- Content -->
-      <xsl:apply-templates select="$grpDef/xsd:*" mode="sample">
-         <xsl:with-param name="margin">
-            <xsl:choose>
-               <xsl:when test="normalize-space($occursInfo)!='[1]'">
-                  <xsl:value-of select="number($margin)+number($ELEM_INDENT)"/>
-               </xsl:when>
-               <xsl:otherwise>
-                  <xsl:value-of select="$margin"/>
-               </xsl:otherwise>
-            </xsl:choose>
-         </xsl:with-param>
-         <xsl:with-param name="isInherited" select="$isInherited"/>
-         <xsl:with-param name="isNewField" select="$isNewField"/>
-         <xsl:with-param name="parentGroups" select="$parentGroups"/>
-         <xsl:with-param name="schemaLoc" select="$grpDefLoc"/>
-         <xsl:with-param name="typeList" select="$typeList"/>
-      </xsl:apply-templates>
-
-      <!-- Footer -->
-      <xsl:if test="normalize-space($occursInfo)!='[1]'">
-         <!-- Don't print out footer if min/max occurs is one. -->
-         <span class="group" style="margin-left: {$margin}em">
-            <xsl:text>End Group: </xsl:text>
-            <xsl:copy-of select="$grpLink"/>
-         </span><br/>
-      </xsl:if>
-   </xsl:template>
-
-   <!--
-     Prints out a sample element instance in one line.
-     Param(s):
-            element (Node) required
-                Element declaration or reference
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-            isInherited (boolean) optional
-                If true, display element using 'inherited' CSS class.
-            isNewField (boolean) optional
-                If true, display element using 'newFields' CSS class.
-            schemaLoc (String) optional
-                Schema file containing this element declaration
-                or reference; if in current schema, 'schemaLoc' is 
-                set to 'this'.
-     -->
-   <xsl:template name="PrintSampleSimpleElement">
-      <xsl:param name="element"/>
-      <xsl:param name="margin">0</xsl:param>
-      <xsl:param name="isInherited">false</xsl:param>
-      <xsl:param name="isNewField">false</xsl:param>
-      <xsl:param name="schemaLoc">this</xsl:param>
-
-      <!-- Element Tag -->
-      <xsl:variable name="elemTag">
-         <!-- Local Name -->
-         <xsl:choose>
-            <!-- Element reference -->
-            <xsl:when test="$element/@ref">
-               <!-- Note: Prefix will be automatically written out
-                    in call to 'PrintElementRef'. -->
-               <xsl:call-template name="PrintElementRef">
-                  <xsl:with-param name="ref" select="@ref"/>
-                  <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-               </xsl:call-template>
-            </xsl:when>
-            <!-- Element declaration -->
-            <xsl:otherwise>
-               <!-- Prefix -->
-               <xsl:variable name="prefix">
-                  <xsl:call-template name="GetElementPrefix">
-                     <xsl:with-param name="element" select="$element"/>
-                  </xsl:call-template>
-               </xsl:variable>
-               <xsl:call-template name="PrintNSPrefix">
-                  <xsl:with-param name="prefix" select="$prefix"/>
-                  <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-               </xsl:call-template>
-               <xsl:value-of select="$element/@name"/>
-            </xsl:otherwise>
-         </xsl:choose>
-      </xsl:variable>
-
-      <div style="margin-left: {$margin}em">
-         <xsl:choose>
-            <xsl:when test="$isNewField!='false'">
-               <xsl:attribute name="class">newFields</xsl:attribute>
-            </xsl:when>
-            <xsl:when test="$isInherited!='false'">
-               <xsl:attribute name="class">inherited</xsl:attribute>
-            </xsl:when>
-         </xsl:choose>
-
-         <!-- Start Tag -->
-         <xsl:text>&lt;</xsl:text>
-         <xsl:copy-of select="$elemTag"/>
-         <xsl:text>></xsl:text>
-
-         <!-- Contents -->
-         <xsl:text> </xsl:text>
-         <xsl:choose>
-            <!-- Fixed value is provided -->
-            <xsl:when test="$element/@fixed">
-               <span class="fixed">
-                  <xsl:value-of select="$element/@fixed"/>
-               </span>
-            </xsl:when>
-            <!-- Type reference is provided -->
-            <xsl:when test="$element/@name and $element/@type">
-               <xsl:call-template name="PrintTypeRef">
-                  <xsl:with-param name="ref" select="$element/@type"/>
-                  <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-               </xsl:call-template>
-            </xsl:when>
-            <!-- Local simple type definition is provided -->
-            <xsl:when test="$element/@name and $element/xsd:simpleType">
-               <xsl:apply-templates select="$element/xsd:simpleType" mode="sample">
-                  <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-               </xsl:apply-templates>
-            </xsl:when>
-            <xsl:otherwise>
-               <xsl:text>...</xsl:text>
-            </xsl:otherwise>
-         </xsl:choose>
-         <xsl:text> </xsl:text>
-
-         <!-- Identity Constraints -->
-         <xsl:if test="$element/xsd:unique or $element/xsd:key or $element/xsd:keyref">
-            <xsl:apply-templates select="$element/xsd:unique | $element/xsd:key | $element/xsd:keyref" mode="sample">
-               <xsl:with-param name="margin" select="$ELEM_INDENT"/>
-               <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-            </xsl:apply-templates>
-         </xsl:if>
-
-         <!-- End Tag -->
-         <xsl:text>&lt;/</xsl:text>
-         <xsl:copy-of select="$elemTag"/>
-         <xsl:text>></xsl:text>
-
-         <xsl:if test="local-name($element/..)!='schema'">
-            <!-- Min/max occurs information -->
-            <xsl:text> </xsl:text>
-            <xsl:call-template name="PrintOccurs">
-               <xsl:with-param name="component" select="$element"/>
-            </xsl:call-template>
-            <!-- Documentation -->
-            <xsl:call-template name="PrintSampleDocumentation">
-               <xsl:with-param name="component" select="$element"/>
-            </xsl:call-template>
-         </xsl:if>
-      </div>
-   </xsl:template>
-
-   <!--
-     Prints out a sample element instance that has complex content.
-     Param(s):
-            type (Node) required
-                Complex type definition
-            element (Node) optional
-                Element declaration
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-            isInherited (boolean) optional
-                If true, display element using 'inherited' CSS class.
-            isNewField (boolean) optional
-                If true, display element using 'newFields' CSS class.
-            schemaLoc (String) optional
-                Schema file containing this element declaration
-                or type definition; if in current schema, 'schemaLoc' 
-                is set to 'this'.
-            typeList (String) optional
-                List of types in this call chain. Name of type starts
-                with '*', and ends with '+'. (Used to prevent infinite
-                recursive loop.)
-     -->
-   <xsl:template name="PrintSampleComplexElement">
-      <xsl:param name="type"/>
-      <xsl:param name="element"/>
-      <xsl:param name="margin">0</xsl:param>
-      <xsl:param name="isInherited">false</xsl:param>
-      <xsl:param name="isNewField">false</xsl:param>
-      <xsl:param name="schemaLoc">this</xsl:param>
-      <xsl:param name="typeList"/>
-      <xsl:param name="parentGroups"/>
-
-      <xsl:choose>
-         <!-- Circular type hierarchy -->
-         <xsl:when test="$type/@name and contains($typeList, concat('*', $type/@name, '+'))"/>
-         <xsl:otherwise>
-            <xsl:variable name="tag">
-               <xsl:choose>
-                  <xsl:when test="$element">
-                     <!-- Prefix -->
-                     <xsl:variable name="prefix">
-                        <xsl:call-template name="GetElementPrefix">
-                           <xsl:with-param name="element" select="$element"/>
-                        </xsl:call-template>
-                     </xsl:variable>
-                     <xsl:call-template name="PrintNSPrefix">
-                        <xsl:with-param name="prefix" select="$prefix"/>
-                        <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                     </xsl:call-template>
-                     <xsl:value-of select="$element/@name"/>
-                  </xsl:when>
-                  <xsl:otherwise>
-                     <xsl:text>...</xsl:text>
-                  </xsl:otherwise>
-               </xsl:choose>
-            </xsl:variable>
-
-            <xsl:variable name="fromTopCType">
-               <xsl:choose>
-                  <xsl:when test="not($element) and local-name($type/..)='schema'">
-                     <xsl:text>true</xsl:text>
-                  </xsl:when>
-                  <xsl:otherwise>
-                     <xsl:text>false</xsl:text>
-                  </xsl:otherwise>
-               </xsl:choose>
-            </xsl:variable>
-
-            <div style="margin-left: {$margin}em">
-               <xsl:choose>
-                  <xsl:when test="$isNewField!='false'">
-                     <xsl:attribute name="class">newFields</xsl:attribute>
-                  </xsl:when>
-                  <xsl:when test="$isInherited!='false'">
-                     <xsl:attribute name="class">inherited</xsl:attribute>
-                  </xsl:when>
-               </xsl:choose>
-         
-               <!-- Start Tag -->
-               <xsl:text>&lt;</xsl:text>
-               <xsl:copy-of select="$tag"/>
-
-               <!-- Print attributes -->
-               <xsl:call-template name="PrintSampleTypeAttrs">
-                  <xsl:with-param name="type" select="$type"/>
-                  <xsl:with-param name="isInherited" select="$isInherited"/>
-                  <xsl:with-param name="isNewField" select="$isNewField"/>
-                  <xsl:with-param name="margin" select="$ATTR_INDENT"/>
-                  <xsl:with-param name="fromTopCType" select="$fromTopCType"/>
-                  <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                  <xsl:with-param name="typeList" select="$typeList"/>
-               </xsl:call-template>
-
-               <!-- Get content -->
-               <xsl:variable name="content">
-                  <xsl:call-template name="PrintSampleTypeContent">
-                     <xsl:with-param name="type" select="$type"/>
-                     <xsl:with-param name="margin" select="$ELEM_INDENT"/>
-                     <xsl:with-param name="isInherited" select="$isInherited"/>
-                     <xsl:with-param name="isNewField" select="$isNewField"/>
-                     <xsl:with-param name="fromTopCType" select="$fromTopCType"/>
-                     <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                     <xsl:with-param name="typeList" select="$typeList"/>
-                     <xsl:with-param name="parentGroups" select="$parentGroups"/>
-                  </xsl:call-template>
-               </xsl:variable>
-
-               <!-- Find out if content type is mixed -->
-               <xsl:variable name="mixed">
-                  <xsl:choose>
-                     <xsl:when test="normalize-space(translate($type/xsd:complexContent/@mixed, 'TRUE', 'true'))='true' or normalize-space($type/xsd:complexContent/@mixed)='1'">
-                        <xsl:text>true</xsl:text>
-                     </xsl:when>
-                     <xsl:when test="normalize-space(translate($type/@mixed, 'TRUE', 'true'))='true' or normalize-space($type/@mixed)='1'">
-                        <xsl:text>true</xsl:text>
-                     </xsl:when>
-                     <xsl:otherwise>
-                        <xsl:text>false</xsl:text>
-                     </xsl:otherwise>
-                  </xsl:choose>
-               </xsl:variable>
-
-               <!-- Find out if there are identity constraints -->
-               <xsl:variable name="hasIdConstraints">
-                  <xsl:if test="$element and ($element/xsd:unique or $element/xsd:key or $element/xsd:keyref)">
-                     <xsl:text>true</xsl:text>
-                  </xsl:if>
-               </xsl:variable>
-
-               <!-- Print content -->
-               <xsl:choose>
-                  <!-- Empty content -->
-                  <xsl:when test="$hasIdConstraints!='true' and normalize-space($content)=''">
-                     <!-- Close start tag -->
-                     <xsl:text>/> </xsl:text>
-
-                     <xsl:if test="$element and local-name($element/..)!='schema'">
-                        <!-- Occurrence info -->
-                        <xsl:text> </xsl:text>
-                        <xsl:call-template name="PrintOccurs">
-                           <xsl:with-param name="component" select="$element"/>
-                        </xsl:call-template>
-
-                        <!-- Documentation -->
-                        <xsl:call-template name="PrintSampleDocumentation">
-                           <xsl:with-param name="component" select="$element"/>
-                        </xsl:call-template>
-                     </xsl:if>
-                  </xsl:when>
-                  <xsl:otherwise>
-                     <!-- Close start tag -->
-                     <xsl:text>> </xsl:text>
-
-                     <xsl:if test="$element and local-name($element/..)!='schema'">
-                        <!-- Occurrence info -->
-                        <xsl:text> </xsl:text>
-                        <xsl:call-template name="PrintOccurs">
-                           <xsl:with-param name="component" select="$element"/>
-                        </xsl:call-template>
-
-                        <!-- Documentation -->
-                        <xsl:text> </xsl:text>
-                        <xsl:call-template name="PrintSampleDocumentation">
-                           <xsl:with-param name="component" select="$element"/>
-                        </xsl:call-template>
-                     </xsl:if>
-
-                     <!-- Identity Constraints -->
-                     <xsl:if test="$element">
-                        <xsl:apply-templates select="$element/xsd:unique | $element/xsd:key | $element/xsd:keyref" mode="sample">
-                           <xsl:with-param name="margin" select="$ELEM_INDENT"/>
-                        </xsl:apply-templates>
-                     </xsl:if>
-
-                     <!-- Print out restriction/extension information -->
-                     <xsl:choose>
-                        <xsl:when test="false()">
-                        <!--<xsl:when test="$type/xsd:complexContent/xsd:restriction/@base">-->
-                           <br/><span class="other" style="margin-left: {$ELEM_INDENT}em">
-                              <xsl:text>&lt;!-- Restricts : </xsl:text>
-                              <xsl:call-template name="PrintTypeRef">
-                                 <xsl:with-param name="ref" select="$type/xsd:complexContent/xsd:restriction/@base"/>
-                                 <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                              </xsl:call-template>
-                              <xsl:text> --></xsl:text>
-                           </span>
-                        </xsl:when>
-                        <xsl:when test="false()">
-                        <!--<xsl:when test="$type/xsd:complexContent/xsd:extension/@base">-->
-                           <br/><span class="other" style="margin-left: {$ELEM_INDENT}em">
-                              <xsl:text>&lt;!-- Extends : </xsl:text>
-                              <xsl:call-template name="PrintTypeRef">
-                                 <xsl:with-param name="ref" select="$type/xsd:complexContent/xsd:extension/@base"/>
-                                 <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                              </xsl:call-template>
-                              <xsl:text> --></xsl:text>
-                           </span>
-                        </xsl:when>
-                     </xsl:choose>
-
-                     <!-- Print out message if has mixed content -->
-                     <xsl:if test="$mixed='true'">
-                        <br/><span class="other" style="margin-left: {$ELEM_INDENT}em">
-                           <xsl:text>&lt;!-- Mixed content --></xsl:text>
-                        </span>
-                     </xsl:if>
-
-                     <!-- Element Content -->
-                     <xsl:copy-of select="$content"/>
-
-                     <!-- End Tag -->
-                     <xsl:text>&lt;/</xsl:text>
-                     <xsl:copy-of select="$tag"/>
-                     <xsl:text>></xsl:text>
-                  </xsl:otherwise>
-               </xsl:choose>
-            </div>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Prints out attributes of a complex type definition, including 
-     those inherited from a base type.
-     Param(s):
-            type (Node) required
-                Complex type definition
-            subTypeAttrs (String) optional
-                List of attributes in sub-types of this current type 
-                definition
-            isInherited (boolean) optional
-                If true, display attributes using 'inherited' CSS class.
-            isNewField (boolean) optional
-                If true, display attributes using 'newFields' CSS class.
-            fromTopCType (boolean) optional
-                Set to true if this is being displayed in the XML 
-                Instance Representation table of a top-level complex 
-                type definition, in which case, 'inherited' attributes 
-                and elements are distinguished.
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-            schemaLoc (String) optional
-                Schema file containing this complex type definition; 
-                if in current schema, 'schemaLoc' is set to 'this'.
-            typeList (String) optional
-                List of types in this call chain. Name of type starts
-                with '*', and ends with '+'. (Used to prevent infinite
-                recursive loop.)
-     -->
-   <xsl:template name="PrintSampleTypeAttrs">
-      <xsl:param name="type"/>
-      <xsl:param name="subTypeAttrs"/>
-      <xsl:param name="isInherited">false</xsl:param>
-      <xsl:param name="isNewField">false</xsl:param>
-      <xsl:param name="fromTopCType">false</xsl:param>
-      <xsl:param name="margin">0</xsl:param>
-      <xsl:param name="schemaLoc">this</xsl:param>
-      <xsl:param name="typeList"/>
-
-      <xsl:choose>
-         <!-- Circular type hierarchy -->
-         <xsl:when test="$type/@name and contains($typeList, concat('*', $type/@name, '+'))">
-            <!-- Do nothing. 
-                 Error message will be written out by 'PrintSampleTypeContent' template. 
-            -->
-         </xsl:when>
-         <!-- Derivation -->
-         <xsl:when test="$type/xsd:complexContent or $type/xsd:simpleContent">
-            <xsl:choose>
-               <xsl:when test="$type/xsd:complexContent/xsd:restriction">
-                  <xsl:call-template name="PrintSampleDerivedTypeAttrs">
-                     <xsl:with-param name="derivationElem" select="$type/xsd:complexContent/xsd:restriction"/>
-                     <xsl:with-param name="subTypeAttrs" select="$subTypeAttrs"/>
-                     <xsl:with-param name="isInherited" select="$isInherited"/>
-                     <xsl:with-param name="isNewField" select="$isNewField"/>
-                     <xsl:with-param name="fromTopCType" select="$fromTopCType"/>
-                     <xsl:with-param name="margin" select="$margin"/>
-                     <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                     <xsl:with-param name="typeList" select="concat($typeList, '*', $type/@name, '+')"/>
-                  </xsl:call-template>
-               </xsl:when>
-               <xsl:when test="$type/xsd:simpleContent/xsd:restriction">
-                  <xsl:call-template name="PrintSampleDerivedTypeAttrs">
-                     <xsl:with-param name="derivationElem" select="$type/xsd:simpleContent/xsd:restriction"/>
-                     <xsl:with-param name="subTypeAttrs" select="$subTypeAttrs"/>
-                     <xsl:with-param name="isInherited" select="$isInherited"/>
-                     <xsl:with-param name="isNewField" select="$isNewField"/>
-                     <xsl:with-param name="fromTopCType" select="$fromTopCType"/>
-                     <xsl:with-param name="margin" select="$margin"/>
-                     <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                     <xsl:with-param name="typeList" select="concat($typeList, '*', $type/@name, '+')"/>
-                  </xsl:call-template>
-               </xsl:when>
-               <xsl:when test="$type/xsd:complexContent/xsd:extension">
-                  <xsl:call-template name="PrintSampleDerivedTypeAttrs">
-                     <xsl:with-param name="derivationElem" select="$type/xsd:complexContent/xsd:extension"/>
-                     <xsl:with-param name="subTypeAttrs" select="$subTypeAttrs"/>
-                     <xsl:with-param name="isInherited" select="$isInherited"/>
-                     <xsl:with-param name="isNewField" select="$isNewField"/>
-                     <xsl:with-param name="fromTopCType" select="$fromTopCType"/>
-                     <xsl:with-param name="margin" select="$margin"/>
-                     <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                     <xsl:with-param name="typeList" select="concat($typeList, '*', $type/@name, '+')"/>
-                  </xsl:call-template>
-               </xsl:when>
-               <xsl:when test="$type/xsd:simpleContent/xsd:extension">
-                  <xsl:call-template name="PrintSampleDerivedTypeAttrs">
-                     <xsl:with-param name="derivationElem" select="$type/xsd:simpleContent/xsd:extension"/>
-                     <xsl:with-param name="subTypeAttrs" select="$subTypeAttrs"/>
-                     <xsl:with-param name="isInherited" select="$isInherited"/>
-                     <xsl:with-param name="isNewField" select="$isNewField"/>
-                     <xsl:with-param name="fromTopCType" select="$fromTopCType"/>
-                     <xsl:with-param name="margin" select="$margin"/>
-                     <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                     <xsl:with-param name="typeList" select="concat($typeList, '*', $type/@name, '+')"/>
-                  </xsl:call-template>
-               </xsl:when>
-            </xsl:choose>
-         </xsl:when>
-         <!-- No derivation -->
-         <xsl:when test="local-name($type)='complexType'">
-            <xsl:call-template name="PrintSampleAttrList">
-               <xsl:with-param name="list" select="$type"/>
-               <xsl:with-param name="subTypeAttrs" select="$subTypeAttrs"/>
-               <xsl:with-param name="isInherited" select="$isInherited"/>
-               <xsl:with-param name="isNewField" select="$isNewField"/>
-               <xsl:with-param name="margin" select="$margin"/>
-               <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-               <xsl:with-param name="typeList" select="concat($typeList, '*', $type/@name, '+')"/>
-            </xsl:call-template>
-         </xsl:when>
-         <!-- Ignore base types that are simple types -->
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Helper function 'PrintSampleTypeAttrs' template to
-     handle case of derived types.
-     Param(s):
-            derivationElem (Node) required
-                'restriction' or 'extension' element
-            subTypeAttrs (String) optional
-                List of attributes in sub-types of 
-                this current type definition
-            isInherited (boolean) optional
-                If true, display attributes using 'inherited' CSS class.
-            isNewField (boolean) optional
-                If true, display attributes using 'newFields' CSS class.
-            fromTopCType (boolean) optional
-                Set to true if this is being displayed 
-                in the XML Instance Representation table 
-                of a top-level complex type definition, in
-                which case, 'inherited' attributes and
-                elements are distinguished.
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-            schemaLoc (String) optional
-                Schema file containing this derivation element; 
-                if in current schema, 'schemaLoc' is set to 'this'.
-            typeList (String) optional
-                List of types in this call chain. Name of type starts
-                with '*', and ends with '+'. (Used to prevent infinite
-                recursive loop.)
-     -->
-   <xsl:template name="PrintSampleDerivedTypeAttrs">
-      <xsl:param name="derivationElem"/>
-      <xsl:param name="subTypeAttrs"/>
-      <xsl:param name="isInherited">false</xsl:param>
-      <xsl:param name="isNewField">false</xsl:param>
-      <xsl:param name="fromTopCType">false</xsl:param>
-      <xsl:param name="margin">0</xsl:param>
-      <xsl:param name="schemaLoc">this</xsl:param>
-      <xsl:param name="typeList"/>
-
-      <!-- Get attributes from this type to add to 
-            'subTypeAttrs' list for recursive call on base type -->
-      <xsl:variable name="thisAttrs">
-         <xsl:call-template name="GetAttrList">
-            <xsl:with-param name="list" select="$derivationElem"/>
-         </xsl:call-template>
-      </xsl:variable>
-
-      <!-- Look for base type -->
-      <xsl:variable name="baseTypeName">
-         <xsl:call-template name="GetRefName">
-            <xsl:with-param name="ref" select="$derivationElem/@base"/>
-         </xsl:call-template>
-      </xsl:variable>
-      <xsl:variable name="defLoc">
-         <xsl:call-template name="FindComponent">
-            <xsl:with-param name="ref" select="$derivationElem/@base"/>
-            <xsl:with-param name="compType">complex type</xsl:with-param>
-         </xsl:call-template>
-      </xsl:variable>
-      <xsl:choose>
-         <!-- Complex type was found in current schema. -->
-         <xsl:when test="normalize-space($defLoc)='this'">
-            <xsl:variable name="ctype" select="key('complexType', $baseTypeName)"/>
-            <xsl:call-template name="PrintSampleTypeAttrs">
-               <xsl:with-param name="type" select="$ctype"/>
-               <xsl:with-param name="subTypeAttrs" select="concat($subTypeAttrs, $thisAttrs)"/>
-               <xsl:with-param name="isInherited">
-                  <xsl:choose>
-                     <xsl:when test="$fromTopCType!='false'">
-                        <xsl:text>true</xsl:text>
-                     </xsl:when>
-                     <xsl:otherwise>
-                        <xsl:text>false</xsl:text>
-                     </xsl:otherwise>
-                  </xsl:choose>
-               </xsl:with-param>
-               <xsl:with-param name="isNewField" select="$isNewField"/>
-               <xsl:with-param name="fromTopCType" select="$fromTopCType"/>
-               <xsl:with-param name="margin" select="$margin"/>
-               <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-               <xsl:with-param name="typeList" select="$typeList"/>
-            </xsl:call-template>
-         </xsl:when>
-         <!-- Complex type was not found. -->
-         <xsl:when test="normalize-space($defLoc)='' or normalize-space($defLoc)='none' or normalize-space($defLoc)='xml' or normalize-space($defLoc)='xsd'">
-            <!-- IGNORE: Error message will be printed out be
-                 'PrintSampleTypeContent' template. -->
-         </xsl:when>
-         <!-- Complex type was found in external schema. -->
-         <xsl:otherwise>
-            <xsl:variable name="ctype" select="document($defLoc)/xsd:schema/xsd:complexType[@name=$baseTypeName]"/>
-            <xsl:call-template name="PrintSampleTypeAttrs">
-               <xsl:with-param name="type" select="$ctype"/>
-               <xsl:with-param name="subTypeAttrs" select="concat($subTypeAttrs, $thisAttrs)"/>
-               <xsl:with-param name="isInherited">
-                  <xsl:choose>
-                     <xsl:when test="$fromTopCType!='false'">
-                        <xsl:text>true</xsl:text>
-                     </xsl:when>
-                     <xsl:otherwise>
-                        <xsl:text>false</xsl:text>
-                     </xsl:otherwise>
-                  </xsl:choose>
-               </xsl:with-param>
-               <xsl:with-param name="isNewField" select="$isNewField"/>
-               <xsl:with-param name="fromTopCType" select="$fromTopCType"/>
-               <xsl:with-param name="margin" select="$margin"/>
-               <xsl:with-param name="schemaLoc" select="$defLoc"/>
-               <xsl:with-param name="typeList" select="$typeList"/>
-            </xsl:call-template>
-         </xsl:otherwise>
-      </xsl:choose>
-
-      <!-- Print out attributes in this type -->
-      <xsl:call-template name="PrintSampleAttrList">
-         <xsl:with-param name="list" select="$derivationElem"/>
-         <xsl:with-param name="subTypeAttrs" select="$subTypeAttrs"/>
-         <xsl:with-param name="isInherited" select="$isInherited"/>
-         <xsl:with-param name="isNewField">
-            <xsl:choose>
-               <xsl:when test="$fromTopCType!='false' and $isInherited='false'">
-                  <xsl:text>true</xsl:text>
-               </xsl:when>
-               <xsl:otherwise>
-                  <xsl:text>false</xsl:text>
-               </xsl:otherwise>
-            </xsl:choose>
-         </xsl:with-param>
-         <xsl:with-param name="margin" select="$margin"/>
-         <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-      </xsl:call-template>
-   </xsl:template>
-
-   <!--
-     Returns the names and namespaces of attributes
-     in a list of attributes and attribute groups.
-     Param(s):
-            list (Node) required
-                Node containing list of attributes and attribute groups
-     -->
-   <xsl:template name="GetAttrList">
-      <xsl:param name="list"/>
-
-      <xsl:if test="$list">
-         <xsl:for-each select="$list/xsd:attribute | $list/xsd:attributeGroup | $list/xsd:anyAttribute">
-            <xsl:choose>
-               <!-- Attribute declaration -->
-               <xsl:when test="local-name(.)='attribute' and @name">
-                  <!-- Get attribute name -->
-                  <xsl:variable name="attrName" select="@name"/>
-                  <!-- Get attribute namespace -->
-                  <xsl:variable name="attrNS">
-                     <xsl:call-template name="GetAttributeNS">
-                        <xsl:with-param name="attribute" select="."/>
-                     </xsl:call-template>
-                  </xsl:variable>
-
-                  <xsl:value-of select="concat('*', normalize-space($attrNS), '+', normalize-space($attrName), '+')"/>
-               </xsl:when>
-               <!-- Attribute reference -->
-               <xsl:when test="local-name(.)='attribute' and @ref">
-                  <!-- Get attribute name -->
-                  <xsl:variable name="attrName">
-                     <xsl:call-template name="GetRefName">
-                        <xsl:with-param name="ref" select="@ref"/>
-                     </xsl:call-template>
-                  </xsl:variable>
-                  <!-- Get attribute namespace -->
-                  <xsl:variable name="attrNS">
-                     <xsl:call-template name="GetAttributeNS">
-                        <xsl:with-param name="attribute" select="."/>
-                     </xsl:call-template>
-                  </xsl:variable>
-
-                  <xsl:value-of select="concat('*', normalize-space($attrNS), '+', normalize-space($attrName), '+')"/>
-               </xsl:when>
-               <!-- Attribute Group reference -->
-               <xsl:when test="local-name(.)='attributeGroup' and @ref">
-                  <xsl:variable name="attrGrpName">
-                     <xsl:call-template name="GetRefName">
-                        <xsl:with-param name="ref" select="@ref"/>
-                     </xsl:call-template>
-                  </xsl:variable>
-                  <xsl:call-template name="GetAttrList">
-                     <xsl:with-param name="list" select="key('attributeGroup', $attrGrpName)"/>
-                  </xsl:call-template>
-               </xsl:when>
-               <!-- Attribute wildcard -->
-               <xsl:when test="local-name(.)='anyAttribute'">
-               </xsl:when>
-            </xsl:choose>
-         </xsl:for-each>
-      </xsl:if>
-   </xsl:template>
-
-   <!--
-     Prints out sample XML instances from a list of attributes and 
-     attribute groups.
-     Param(s):
-            list (Node) required
-                Node containing list of attributes and attribute groups
-            subTypeAttrs (String) optional
-                List of attributes in sub-types of 
-                the type definition containing this list
-            isInherited (boolean) optional
-                If true, display attributes using 'inherited' CSS class.
-            isNewField (boolean) optional
-                If true, display attributes using 'newFields' CSS class.
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-            schemaLoc (String) optional
-                Schema file containing this attribute list; 
-                if in current schema, 'schemaLoc' is set to 'this'.
-     -->
-   <xsl:template name="PrintSampleAttrList">
-      <xsl:param name="list"/>
-      <xsl:param name="subTypeAttrs"/>
-      <xsl:param name="isInherited">false</xsl:param>
-      <xsl:param name="isNewField">false</xsl:param>
-      <xsl:param name="margin">0</xsl:param>
-      <xsl:param name="schemaLoc">this</xsl:param>
-
-      <xsl:apply-templates select="$list/xsd:attribute | $list/xsd:attributeGroup | $list/xsd:anyAttribute" mode="sample">
-         <xsl:with-param name="subTypeAttrs" select="$subTypeAttrs"/>
-         <xsl:with-param name="isInherited" select="$isInherited"/>
-         <xsl:with-param name="isNewField" select="$isNewField"/>
-         <xsl:with-param name="margin" select="$margin"/>
-         <xsl:with-param name="addBR">true</xsl:with-param>
-         <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-      </xsl:apply-templates>
-   </xsl:template>
-
-   <!--
-     Prints out the element content of a complex type definition,
-     including those inherited from a base type.
-     Param(s):
-            type (Node) required
-                Complex type definition
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-            isInherited (boolean) optional
-                If true, display elements using 'inherited' CSS class.
-            isNewField (boolean) optional
-                If true, display elements using 'newFields' CSS class.
-            fromTopCType (boolean) optional
-                Set to true if this is being displayed in the XML 
-                Instance Representation table of a top-level complex 
-                type definition, in which case, 'inherited' attributes 
-                and elements are distinguished.
-            addBR (boolean) optional
-                If true, can add <br/> before element content.
-                Applicable only if displaying complex content.
-            schemaLoc (String) optional
-                Schema file containing this type definition; 
-                if in current schema, 'schemaLoc' is set to 'this'.
-            typeList (String) optional
-                List of types in this call chain. Name of type starts
-                with '*', and ends with '+'. (Used to prevent infinite
-                recursive loop.)
-     -->
-   <xsl:template name="PrintSampleTypeContent">
-      <xsl:param name="type"/>
-      <xsl:param name="margin">0</xsl:param>
-      <xsl:param name="isInherited">false</xsl:param>
-      <xsl:param name="isNewField">false</xsl:param>
-      <xsl:param name="fromTopCType">false</xsl:param>
-      <xsl:param name="addBR">true</xsl:param>
-      <xsl:param name="schemaLoc">this</xsl:param>
-      <xsl:param name="typeList"/>
-      <xsl:param name="parentGroups"/>
-
-      <xsl:if test="$addBR='true'"><br/></xsl:if>
-
-      <xsl:choose>
-         <!-- Circular type hierarchy -->
-         <xsl:when test="$type/@name and contains($typeList, concat('*', $type/@name, '+'))"/>
-         <!-- Derivation by restriction on complex content -->
-         <xsl:when test="$type/xsd:complexContent/xsd:restriction">
-            <xsl:variable name="restriction" select="$type/xsd:complexContent/xsd:restriction"/>
-
-            <!-- Test if base type is in schema to print out warning comment-->
-            <xsl:variable name="baseTypeName">
-               <xsl:call-template name="GetRefName">
-                  <xsl:with-param name="ref" select="$restriction/@base"/>
-               </xsl:call-template>
-            </xsl:variable>
-            <!-- Look for base type -->
-            <xsl:variable name="defLoc">
-               <xsl:call-template name="FindComponent">
-                  <xsl:with-param name="ref" select="$restriction/@base"/>
-                  <xsl:with-param name="compType">complex type</xsl:with-param>
-               </xsl:call-template>
-            </xsl:variable>
-
-            <xsl:choose>
-               <!-- Complex type was not found. -->
-               <xsl:when test="normalize-space($defLoc)='' or normalize-space($defLoc)='none' or normalize-space($defLoc)='xml' or normalize-space($defLoc)='xsd'">
-                  <div class="other" style="margin-left: {$margin}em;">
-                     <xsl:text>&lt;!-- '</xsl:text>
-                     <xsl:call-template name="PrintTypeRef">
-                        <xsl:with-param name="ref" select="$restriction/@base"/>
-                        <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                     </xsl:call-template>
-                     <xsl:text>' super type was not found in this schema. Some elements and attributes may be missing. --></xsl:text>
-                  </div>
-               </xsl:when>
-               <!-- Complex type was found. -->
-               <xsl:otherwise>
-                  <!-- IGNORE element content of base type if by restriction,
-                       since current content will override restricted
-                       base type's content. -->
-               </xsl:otherwise>
-            </xsl:choose>
-
-            <!-- Print out content from this type -->
-            <xsl:if test="$restriction/xsd:*[local-name(.)!='annotation']">
-               <xsl:call-template name="PrintSampleParticleList">
-                  <xsl:with-param name="list" select="$restriction"/>
-                  <xsl:with-param name="margin" select="$margin"/>
-                  <xsl:with-param name="isInherited" select="$isInherited"/>
-                  <xsl:with-param name="isNewField">
-                     <xsl:choose>
-                        <xsl:when test="$fromTopCType!='false' and $isInherited='false'">
-                           <xsl:text>true</xsl:text>
-                        </xsl:when>
-                        <xsl:otherwise>
-                           <xsl:text>false</xsl:text>
-                        </xsl:otherwise>
-                     </xsl:choose>
-                  </xsl:with-param>
-                  <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                  <xsl:with-param name="typeList" select="concat($typeList, '*', $type/@name, '+')"/>
-                  <xsl:with-param name="parentGroups" select="$parentGroups"/>
-               </xsl:call-template>
-            </xsl:if>
-         </xsl:when>
-         <!-- Derivation by extension on complex content -->
-         <xsl:when test="$type/xsd:complexContent/xsd:extension">
-            <xsl:variable name="extension" select="$type/xsd:complexContent/xsd:extension"/>
-
-            <xsl:variable name="baseTypeName">
-               <xsl:call-template name="GetRefName">
-                  <xsl:with-param name="ref" select="$extension/@base"/>
-               </xsl:call-template>
-            </xsl:variable>
-
-            <xsl:choose>
-               <xsl:when test="contains($typeList, concat('*', $baseTypeName, '+'))">
-                  <div class="other" style="margin-left: {$margin}em">
-                     <xsl:text>&lt;-- Extends: </xsl:text>
-                     <xsl:call-template name="PrintTypeRef">
-                        <xsl:with-param name="ref" select="$extension/@base"/>
-                        <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                     </xsl:call-template>
-                     <xsl:text> (Circular type hierarchy) --&gt;</xsl:text>
-                  </div>
-               </xsl:when>
-               <xsl:otherwise>
-                  <!-- Look for base type -->
-                  <xsl:variable name="defLoc">
-                     <xsl:call-template name="FindComponent">
-                        <xsl:with-param name="ref" select="$extension/@base"/>
-                        <xsl:with-param name="compType">complex type</xsl:with-param>
-                     </xsl:call-template>
-                  </xsl:variable>
-
-                  <xsl:choose>
-                     <!-- Complex type was found in current schema. -->
-                     <xsl:when test="normalize-space($defLoc)='this'">
-                        <xsl:variable name="ctype" select="key('complexType', $baseTypeName)"/>
-                        <xsl:call-template name="PrintSampleTypeContent">
-                           <xsl:with-param name="type" select="$ctype"/>
-                           <xsl:with-param name="margin" select="$margin"/>
-                           <xsl:with-param name="isInherited">
-                              <xsl:choose>
-                                 <xsl:when test="$fromTopCType!='false'">
-                                    <xsl:text>true</xsl:text>
-                                 </xsl:when>
-                                 <xsl:otherwise>
-                                    <xsl:text>false</xsl:text>
-                                 </xsl:otherwise>
-                              </xsl:choose>
-                           </xsl:with-param>
-                           <xsl:with-param name="isNewField" select="$isNewField"/>
-                           <xsl:with-param name="fromTopCType" select="$fromTopCType"/>
-                           <xsl:with-param name="addBR">false</xsl:with-param>
-                           <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                           <xsl:with-param name="typeList" select="concat($typeList, '*', $type/@name, '+')"/>
-			   <xsl:with-param name="parentGroups" select="$parentGroups"/>
-                        </xsl:call-template>
-                     </xsl:when>
-                     <!-- Complex type was not found. -->
-                     <xsl:when test="normalize-space($defLoc)='' or normalize-space($defLoc)='none' or normalize-space($defLoc)='xml' or normalize-space($defLoc)='xsd'">
-                        <div class="other" style="margin-left: {$margin}em;">
-                           <xsl:text>&lt;!-- '</xsl:text>
-                           <xsl:call-template name="PrintTypeRef">
-                              <xsl:with-param name="ref" select="$extension/@base"/>
-                              <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                           </xsl:call-template>
-                           <xsl:text>' super type was not found in this schema. Some elements and attributes may be missing. --></xsl:text>
-                        </div>
-                     </xsl:when>
-                     <!-- Complex type was found in external schema. -->
-                     <xsl:otherwise>
-                        <xsl:variable name="ctype" select="document($defLoc)/xsd:schema/xsd:complexType[@name=$baseTypeName]"/>
-                        <xsl:call-template name="PrintSampleTypeContent">
-                           <xsl:with-param name="type" select="$ctype"/>
-                           <xsl:with-param name="margin" select="$margin"/>
-                           <xsl:with-param name="isInherited">
-                              <xsl:choose>
-                                 <xsl:when test="$fromTopCType!='false'">
-                                    <xsl:text>true</xsl:text>
-                                 </xsl:when>
-                                 <xsl:otherwise>
-                                    <xsl:text>false</xsl:text>
-                                 </xsl:otherwise>
-                              </xsl:choose>
-                           </xsl:with-param>
-                           <xsl:with-param name="isNewField" select="$isNewField"/>
-                           <xsl:with-param name="fromTopCType" select="$fromTopCType"/>
-                           <xsl:with-param name="addBR">false</xsl:with-param>
-                           <xsl:with-param name="schemaLoc" select="$defLoc"/>
-                           <xsl:with-param name="typeList" select="concat($typeList, '*', $type/@name, '+')"/>
-			   <xsl:with-param name="parentGroups" select="$parentGroups"/>
-                        </xsl:call-template>
-                     </xsl:otherwise>
-                  </xsl:choose>
-
-                  <!-- Print out content from this type -->
-                  <xsl:if test="$extension/xsd:*[local-name(.)!='annotation']">
-                     <xsl:call-template name="PrintSampleParticleList">
-                        <xsl:with-param name="list" select="$extension"/>
-                        <xsl:with-param name="margin" select="$margin"/>
-                        <xsl:with-param name="isInherited" select="$isInherited"/>
-                        <xsl:with-param name="isNewField">
-                           <xsl:choose>
-                              <xsl:when test="$fromTopCType!='false' and $isInherited='false'">
-                                 <xsl:text>true</xsl:text>
-                              </xsl:when>
-                              <xsl:otherwise>
-                                 <xsl:text>false</xsl:text>
-                              </xsl:otherwise>
-                           </xsl:choose>
-                        </xsl:with-param>
-                        <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                        <xsl:with-param name="typeList" select="concat($typeList, '*', $type/@name, '+')"/>
-			<xsl:with-param name="parentGroups" select="$parentGroups"/>
-                     </xsl:call-template>
-                  </xsl:if>
-               </xsl:otherwise>
-            </xsl:choose>
-         </xsl:when>
-         <!-- Derivation by restriction on simple content -->
-         <xsl:when test="$type/xsd:simpleContent/xsd:restriction">
-            <!-- Print out simple type constraints-->
-            <span style="margin-left: {$margin}em">
-               <xsl:text> </xsl:text>
-               <xsl:apply-templates select="$type/xsd:simpleContent" mode="sample">
-                  <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-               </xsl:apply-templates>
-               <xsl:text> </xsl:text>
-            </span><br/>
-         </xsl:when>
-         <!-- Derivation by extension on simple content -->
-         <xsl:when test="$type/xsd:simpleContent/xsd:extension">
-            <!-- Print out base type name -->
-            <span style="margin-left: {$margin}em">
-               <xsl:text> </xsl:text>
-               <xsl:call-template name="PrintTypeRef">
-                  <xsl:with-param name="ref" select="$type/xsd:simpleContent/xsd:extension/@base"/>
-                  <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-               </xsl:call-template>
-               <xsl:text> </xsl:text>
-            </span><br/>
-         </xsl:when>
-         <!-- No derivation: complex type definition -->
-         <xsl:when test="local-name($type)='complexType'">
-            <!-- Print out content from this type -->
-            <xsl:call-template name="PrintSampleParticleList">
-               <xsl:with-param name="list" select="$type"/>
-               <xsl:with-param name="margin" select="$margin"/>
-               <xsl:with-param name="isInherited" select="$isInherited"/>
-               <xsl:with-param name="isNewField" select="$isNewField"/>
-               <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-               <xsl:with-param name="typeList" select="concat($typeList, '*', $type/@name, '+')"/>
-		<xsl:with-param name="parentGroups" select="$parentGroups"/>
-            </xsl:call-template>
-         </xsl:when>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Prints out sample XML instances from a list of 
-     element particle.
-     Param(s):
-            list (Node) required
-                Node containing list of element particles
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-            isInherited (boolean) optional
-                If true, display elements using 'inherited' CSS class.
-            isNewField (boolean) optional
-                If true, display elements using 'newFields' CSS class.
-            schemaLoc (String) optional
-                Schema file containing this particle list; 
-                if in current schema, 'schemaLoc' is set to 'this'.
-            typeList (String) optional
-                List of types in this call chain. Name of type starts
-                with '*', and ends with '+'. (Used to prevent infinite
-                recursive loop.)
-     -->
-   <xsl:template name="PrintSampleParticleList">
-      <xsl:param name="list"/>
-      <xsl:param name="margin">0</xsl:param>
-      <xsl:param name="isInherited">false</xsl:param>
-      <xsl:param name="isNewField">false</xsl:param>
-      <xsl:param name="schemaLoc">this</xsl:param>
-      <xsl:param name="typeList"/>
-      <xsl:param name="parentGroups"/>
-
-      <xsl:if test="$list">
-         <xsl:apply-templates select="$list/xsd:group | $list/xsd:sequence | $list/xsd:choice | $list/xsd:all | $list/xsd:element" mode="sample">
-            <xsl:with-param name="margin" select="$margin"/>
-            <xsl:with-param name="isInherited" select="$isInherited"/>
-            <xsl:with-param name="isNewField" select="$isNewField"/>
-            <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-            <xsl:with-param name="typeList" select="$typeList"/>
-	    <xsl:with-param name="parentGroups" select="$parentGroups"/>
-         </xsl:apply-templates>
-      </xsl:if>
-   </xsl:template>
-
-   <!--
-     Prints out the constraints of simple content
-     to be displayed within a sample XML instance.
-     Param(s):
-            simpleContent (Node) required
-                Node containing with the simple content
-            schemaLoc (String) optional
-                Schema file containing these simple constraints; 
-                if in current schema, 'schemaLoc' is set to 'this'.
-     -->
-   <xsl:template name="PrintSampleSimpleConstraints">
-      <xsl:param name="simpleContent"/>
-      <xsl:param name="schemaLoc">this</xsl:param>
-      <xsl:param name="typeList"/>
-
-      <xsl:choose>
-         <!-- Derivation by restriction -->
-         <xsl:when test="$simpleContent/xsd:restriction">
-            <xsl:call-template name="PrintSampleSimpleRestriction">
-               <xsl:with-param name="restriction" select="$simpleContent/xsd:restriction"/>
-               <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-               <xsl:with-param name="typeList" select="$typeList"/>
-            </xsl:call-template>
-         </xsl:when>
-         <!-- Derivation by list -->
-         <xsl:when test="$simpleContent/xsd:list">
-            <xsl:choose>
-               <xsl:when test="$simpleContent/xsd:list/@itemType">
-                  <xsl:text>list of: </xsl:text>
-                  <xsl:call-template name="PrintTypeRef">
-                     <xsl:with-param name="ref" select="$simpleContent/xsd:list/@itemType"/>
-                     <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                  </xsl:call-template>
-               </xsl:when>
-               <xsl:otherwise>
-                  <xsl:text>list of: [ </xsl:text>
-                  <xsl:call-template name="PrintSampleSimpleConstraints">
-                     <xsl:with-param name="simpleContent" select="$simpleContent/xsd:list/xsd:simpleType"/>
-                     <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-                  </xsl:call-template>
-                  <xsl:text> ]</xsl:text>
-               </xsl:otherwise>
-            </xsl:choose>
-         </xsl:when>
-         <!-- Derivation by union -->
-         <xsl:when test="$simpleContent/xsd:union">
-            <xsl:text>union of: [ </xsl:text>
-
-            <xsl:variable name="hasMemberTypes">
-               <xsl:if test="normalize-space($simpleContent/xsd:union/@memberTypes)!=''">
-                  <xsl:text>true</xsl:text>
-               </xsl:if>
-            </xsl:variable>
-            <xsl:if test="$hasMemberTypes='true'">
-               <xsl:call-template name="PrintWhitespaceList">
-                  <xsl:with-param name="value" select="$simpleContent/xsd:union/@memberTypes"/>
-                  <xsl:with-param name="compType">type</xsl:with-param>
-                  <xsl:with-param name="separator">,</xsl:with-param>
-                  <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-               </xsl:call-template>
-            </xsl:if>
-            <xsl:for-each select="$simpleContent/xsd:union/xsd:simpleType">
-               <xsl:if test="position()!=1 or $hasMemberTypes='true'">
-                  <xsl:text>, </xsl:text>
-               </xsl:if>
-               <xsl:text>[ </xsl:text>
-               <xsl:call-template name="PrintSampleSimpleConstraints">
-                  <xsl:with-param name="simpleContent" select="."/>
-                  <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-               </xsl:call-template>
-               <xsl:text> ]</xsl:text>
-            </xsl:for-each>
-
-            <xsl:text> ]</xsl:text>
-         </xsl:when>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Prints out the constraints of simple content
-     derived by restriction, which is to be displayed 
-     within a sample XML instance.
-     Param(s):
-            restriction (Node) required
-                Node containing with the restriction
-            schemaLoc (String) optional
-                Schema file containing this restriction element; 
-                if in current schema, 'schemaLoc' is set to 'this'.
-     -->
-   <xsl:template name="PrintSampleSimpleRestriction">
-      <xsl:param name="restriction"/>
-      <xsl:param name="schemaLoc">this</xsl:param>
-      <xsl:param name="typeList"/>
-
-      <xsl:variable name="typeName" select="$restriction/parent::xsd:simpleType/@name"/>
-
-      <!-- Print out base type info -->
-      <xsl:choose>
-         <!-- Circular type hierarchy -->
-         <xsl:when test="$typeName != '' and contains($typeList, concat('*', $typeName, '+'))">
-            <xsl:call-template name="HandleError">
-               <xsl:with-param name="isTerminating">false</xsl:with-param>
-               <xsl:with-param name="errorMsg">
-                  <xsl:text>Circular type reference to '</xsl:text>
-                  <xsl:value-of select="$typeName"/>
-                  <xsl:text>' in type hierarchy.</xsl:text>
-               </xsl:with-param>
-            </xsl:call-template>
-         </xsl:when>
-         <!-- Locally-defined base type -->
-         <xsl:when test="$restriction/xsd:simpleType">
-            <xsl:call-template name="PrintSampleSimpleConstraints">
-               <xsl:with-param name="simpleContent" select="$restriction/xsd:simpleType"/>
-               <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-               <xsl:with-param name="typeList" select="$typeList"/>
-            </xsl:call-template>
-         </xsl:when>
-         <!-- Base type reference -->
-         <xsl:when test="$restriction">
-            <xsl:variable name="baseTypeRef" select="$restriction/@base"/>
-            <xsl:variable name="baseTypeName">
-               <xsl:call-template name="GetRefName">
-                  <xsl:with-param name="ref" select="$baseTypeRef"/>
-               </xsl:call-template>
-            </xsl:variable>
-            <xsl:variable name="baseTypeNS">
-               <xsl:call-template name="GetRefNS">
-                  <xsl:with-param name="ref" select="$baseTypeRef"/>
-               </xsl:call-template>
-            </xsl:variable>
-            <!-- Write out reference to base type -->
-            <xsl:call-template name="PrintTypeRef">
-               <xsl:with-param name="ref" select="$baseTypeRef"/>
-               <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-            </xsl:call-template>
-         </xsl:when>
-      </xsl:choose>
-
-      <!-- Regular Expression Pattern -->
-      <xsl:variable name="pattern">
-         <xsl:call-template name="PrintPatternFacet">
-            <xsl:with-param name="simpleRestrict" select="$restriction"/>
-         </xsl:call-template>
-      </xsl:variable>
-      <!-- Range -->
-      <xsl:variable name="range">
-         <xsl:call-template name="PrintRangeFacets">
-            <xsl:with-param name="simpleRestrict" select="$restriction"/>
-         </xsl:call-template>
-      </xsl:variable>
-      <!-- Length -->
-      <xsl:variable name="length">
-         <xsl:call-template name="PrintLengthFacets">
-            <xsl:with-param name="simpleRestrict" select="$restriction"/>
-         </xsl:call-template>
-      </xsl:variable>
-
-      <!-- Print out facets -->
-      <xsl:if test="$restriction/xsd:enumeration">
-         <xsl:text> (</xsl:text>
-         <xsl:call-template name="PrintEnumFacets">
-            <xsl:with-param name="simpleRestrict" select="$restriction"/>
-         </xsl:call-template>
-         <xsl:text>)</xsl:text>
-      </xsl:if>
-      <xsl:if test="$pattern !=''">
-         <xsl:text> (</xsl:text>
-         <xsl:copy-of select="$pattern"/>
-         <xsl:text>)</xsl:text>
-      </xsl:if>
-      <xsl:if test="$range !=''">
-         <xsl:text> (</xsl:text>
-         <xsl:copy-of select="$range"/>
-         <xsl:text>)</xsl:text>
-      </xsl:if>
-      <xsl:if test="$restriction/xsd:totalDigits">
-         <xsl:text> (</xsl:text>
-         <xsl:call-template name="PrintTotalDigitsFacet">
-            <xsl:with-param name="simpleRestrict" select="$restriction"/>
-         </xsl:call-template>
-         <xsl:text>)</xsl:text>
-      </xsl:if>
-      <xsl:if test="$restriction/xsd:fractionDigits">
-         <xsl:text> (</xsl:text>
-         <xsl:call-template name="PrintFractionDigitsFacet">
-            <xsl:with-param name="simpleRestrict" select="$restriction"/>
-         </xsl:call-template>
-         <xsl:text>)</xsl:text>
-      </xsl:if>
-      <xsl:if test="$length !=''">
-         <xsl:text> (</xsl:text>
-         <xsl:copy-of select="$length"/>
-         <xsl:text>)</xsl:text>
-      </xsl:if>
-      <xsl:if test="$restriction/xsd:whiteSpace">
-         <xsl:text> (</xsl:text>
-         <xsl:call-template name="PrintWhitespaceFacet">
-            <xsl:with-param name="simpleRestrict" select="$restriction"/>
-         </xsl:call-template>
-         <xsl:text>)</xsl:text>
-      </xsl:if>
-   </xsl:template>
-
-   <!-- ******** Schema Component Representation table ******** -->
-
-   <!-- 
-     Prints out the Schema Component Representation table 
-     for a top-level schema component. 
-     Param(s):
-            component (Node) required
-              Top-level schema component
-     -->
-   <xsl:template name="SchemaComponentTable">
-      <xsl:param name="component"/>
-
-      <xsl:variable name="componentID">
-         <xsl:call-template name="GetComponentID">
-            <xsl:with-param name="component" select="$component"/>
-         </xsl:call-template>
-      </xsl:variable>
-
-      <xsl:call-template name="CollapseableBox">
-         <xsl:with-param name="id" select="concat($componentID, '_scbox')"/>
-         <xsl:with-param name="styleClass">schemaComponent</xsl:with-param>
-         <xsl:with-param name="caption">Schema Component Representation</xsl:with-param>
-         <xsl:with-param name="contents">
-            <xsl:apply-templates select="$component" mode="schemaComponent"/>
-         </xsl:with-param>
-         <xsl:with-param name="isOpened">false</xsl:with-param>
-      </xsl:call-template>
-   </xsl:template>
-
-   <!--
-     Prints out schema component representation of 
-     declarations.
-     Param(s):
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-     -->
-   <xsl:template match="xsd:attribute[@name] | xsd:element[@name]" mode="schemaComponent">
-      <xsl:param name="margin">0</xsl:param>
-
-      <xsl:call-template name="DisplaySchemaComponent">
-         <xsl:with-param name="component" select="."/>
-         <xsl:with-param name="margin" select="$margin"/>
-         <xsl:with-param name="attributes">
-            <!-- Attribute: name -->
-            <xsl:call-template name="DisplayAttr">
-               <xsl:with-param name="attrName">name</xsl:with-param>
-               <xsl:with-param name="attrValue" select="normalize-space(@name)"/>
-            </xsl:call-template>
-            <!-- Attribute: type -->
-            <xsl:if test="@type">
-               <xsl:call-template name="DisplayAttr">
-                  <xsl:with-param name="attrName">type</xsl:with-param>
-                  <xsl:with-param name="attrValue">
-                     <xsl:call-template name="PrintTypeRef">
-                        <xsl:with-param name="ref" select="normalize-space(@type)"/>
-                     </xsl:call-template>
-                  </xsl:with-param>
-               </xsl:call-template>
-            </xsl:if>
-            <!-- Other attributes -->
-            <xsl:call-template name="DisplayOtherAttributes">
-               <xsl:with-param name="component" select="."/>
-               <xsl:with-param name="attrsNotToDisplay">*name+*type+</xsl:with-param>
-            </xsl:call-template>
-         </xsl:with-param>
-         <xsl:with-param name="excludeFilter">*annotation+</xsl:with-param>
-      </xsl:call-template>
-   </xsl:template>
-
-   <!--
-     Prints out schema component representation of 
-     definitions and key/uniqueness constraints.
-     Param(s):
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-     -->
-   <xsl:template match="xsd:attributeGroup[@name] | xsd:complexType[@name] | xsd:simpleType[@name] | xsd:group[@name] | xsd:key | xsd:unique" mode="schemaComponent">
-      <xsl:param name="margin">0</xsl:param>
-
-      <xsl:call-template name="DisplaySchemaComponent">
-         <xsl:with-param name="component" select="."/>
-         <xsl:with-param name="margin" select="$margin"/>
-         <xsl:with-param name="attributes">
-            <!-- Attribute: name -->
-            <xsl:call-template name="DisplayAttr">
-               <xsl:with-param name="attrName">name</xsl:with-param>
-               <xsl:with-param name="attrValue" select="normalize-space(@name)"/>
-            </xsl:call-template>
-            <!-- Other attributes -->
-            <xsl:call-template name="DisplayOtherAttributes">
-               <xsl:with-param name="component" select="."/>
-               <xsl:with-param name="attrsNotToDisplay">*name+</xsl:with-param>
-            </xsl:call-template>
-         </xsl:with-param>
-         <xsl:with-param name="excludeFilter">*annotation+</xsl:with-param>
-      </xsl:call-template>
-   </xsl:template>
-
-   <!--
-     Prints out schema component representation of attribute
-     references.
-     Param(s):
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-     -->
-   <xsl:template match="xsd:attribute[@ref]" mode="schemaComponent">
-      <xsl:param name="margin">0</xsl:param>
-
-      <xsl:call-template name="DisplaySchemaComponent">
-         <xsl:with-param name="component" select="."/>
-         <xsl:with-param name="margin" select="$margin"/>
-         <xsl:with-param name="attributes">
-            <!-- Attribute: ref -->
-            <xsl:call-template name="DisplayAttr">
-               <xsl:with-param name="attrName">ref</xsl:with-param>
-               <xsl:with-param name="attrValue">
-                  <xsl:call-template name="PrintAttributeRef">
-                     <xsl:with-param name="ref" select="normalize-space(@ref)"/>
-                  </xsl:call-template>
-               </xsl:with-param>
-            </xsl:call-template>
-            <!-- Other attributes -->
-            <xsl:call-template name="DisplayOtherAttributes">
-               <xsl:with-param name="component" select="."/>
-               <xsl:with-param name="attrsNotToDisplay">*ref+</xsl:with-param>
-            </xsl:call-template>
-         </xsl:with-param>
-         <xsl:with-param name="excludeFilter">*annotation+</xsl:with-param>
-      </xsl:call-template>
-   </xsl:template>
-
-   <!--
-     Prints out schema component representation of attribute group
-     references.
-     Param(s):
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-     -->
-   <xsl:template match="xsd:attributeGroup[@ref]" mode="schemaComponent">
-      <xsl:param name="margin">0</xsl:param>
-
-      <xsl:call-template name="DisplaySchemaComponent">
-         <xsl:with-param name="component" select="."/>
-         <xsl:with-param name="margin" select="$margin"/>
-         <xsl:with-param name="attributes">
-            <!-- Attribute: ref -->
-            <xsl:call-template name="DisplayAttr">
-               <xsl:with-param name="attrName">ref</xsl:with-param>
-               <xsl:with-param name="attrValue">
-                  <xsl:call-template name="PrintAttributeGroupRef">
-                     <xsl:with-param name="ref" select="normalize-space(@ref)"/>
-                  </xsl:call-template>
-               </xsl:with-param>
-            </xsl:call-template>
-            <!-- Other attributes -->
-            <xsl:call-template name="DisplayOtherAttributes">
-               <xsl:with-param name="component" select="."/>
-               <xsl:with-param name="attrsNotToDisplay">*ref+</xsl:with-param>
-            </xsl:call-template>
-         </xsl:with-param>
-         <xsl:with-param name="excludeFilter">*annotation+</xsl:with-param>
-      </xsl:call-template>
-   </xsl:template>
-
-   <!--
-     Prints out schema component representation of element 
-     references.
-     Param(s):
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-     -->
-   <xsl:template match="xsd:element[@ref]" mode="schemaComponent">
-      <xsl:param name="margin">0</xsl:param>
-
-      <xsl:call-template name="DisplaySchemaComponent">
-         <xsl:with-param name="component" select="."/>
-         <xsl:with-param name="margin" select="$margin"/>
-         <xsl:with-param name="attributes">
-            <!-- Attribute: ref -->
-            <xsl:call-template name="DisplayAttr">
-               <xsl:with-param name="attrName">ref</xsl:with-param>
-               <xsl:with-param name="attrValue">
-                  <xsl:call-template name="PrintElementRef">
-                     <xsl:with-param name="ref" select="normalize-space(@ref)"/>
-                  </xsl:call-template>
-               </xsl:with-param>
-            </xsl:call-template>
-            <!-- Other attributes -->
-            <xsl:call-template name="DisplayOtherAttributes">
-               <xsl:with-param name="component" select="."/>
-               <xsl:with-param name="attrsNotToDisplay">*ref+</xsl:with-param>
-            </xsl:call-template>
-         </xsl:with-param>
-         <xsl:with-param name="excludeFilter">*annotation+</xsl:with-param>
-      </xsl:call-template>
-   </xsl:template>
-
-   <!--
-     Prints out schema component representation of model group
-     references.
-     Param(s):
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-     -->
-   <xsl:template match="xsd:group[@ref]" mode="schemaComponent">
-      <xsl:param name="margin">0</xsl:param>
-
-      <xsl:call-template name="DisplaySchemaComponent">
-         <xsl:with-param name="component" select="."/>
-         <xsl:with-param name="margin" select="$margin"/>
-         <xsl:with-param name="attributes">
-            <!-- Attribute: ref -->
-            <xsl:call-template name="DisplayAttr">
-               <xsl:with-param name="attrName">ref</xsl:with-param>
-               <xsl:with-param name="attrValue">
-                  <xsl:call-template name="PrintGroupRef">
-                     <xsl:with-param name="ref" select="normalize-space(@ref)"/>
-                  </xsl:call-template>
-               </xsl:with-param>
-            </xsl:call-template>
-            <!-- Other attributes -->
-            <xsl:call-template name="DisplayOtherAttributes">
-               <xsl:with-param name="component" select="."/>
-               <xsl:with-param name="attrsNotToDisplay">*ref+</xsl:with-param>
-            </xsl:call-template>
-         </xsl:with-param>
-         <xsl:with-param name="excludeFilter">*annotation+</xsl:with-param>
-      </xsl:call-template>
-   </xsl:template>
-
-   <!--
-     Prints out schema component representation of 
-     'appinfo' and 'documentation' elements.
-     Param(s):
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-     -->
-   <xsl:template match="xsd:appinfo | xsd:documentation" mode="schemaComponent">
-      <xsl:param name="margin">0</xsl:param>
-
-      <xsl:call-template name="DisplaySchemaComponent">
-         <xsl:with-param name="component" select="."/>
-         <xsl:with-param name="margin" select="$margin"/>
-         <xsl:with-param name="attributes">
-            <!-- Attribute: source -->
-            <xsl:if test="@source">
-               <xsl:call-template name="DisplayAttr">
-                  <xsl:with-param name="attrName">source</xsl:with-param>
-                  <xsl:with-param name="attrValue">
-                     <xsl:call-template name="PrintURI">
-                        <xsl:with-param name="uri" select="normalize-space(@source)"/>
-                     </xsl:call-template>
-                  </xsl:with-param>
-               </xsl:call-template>
-            </xsl:if>
-            <!-- Other attributes -->
-            <xsl:call-template name="DisplayOtherAttributes">
-               <xsl:with-param name="component" select="."/>
-               <xsl:with-param name="attrsNotToDisplay">*source+</xsl:with-param>
-            </xsl:call-template>
-         </xsl:with-param>
-         <xsl:with-param name="hasAnyContent">true</xsl:with-param>
-      </xsl:call-template>
-   </xsl:template>
-
-   <!--
-     Prints out schema component representation of 
-     key reference constraints.
-     Param(s):
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-     -->
-   <xsl:template match="xsd:keyref" mode="schemaComponent">
-      <xsl:param name="margin">0</xsl:param>
-
-      <xsl:call-template name="DisplaySchemaComponent">
-         <xsl:with-param name="component" select="."/>
-         <xsl:with-param name="margin" select="$margin"/>
-         <xsl:with-param name="attributes">
-            <!-- Attribute: name -->
-            <xsl:call-template name="DisplayAttr">
-               <xsl:with-param name="attrName">name</xsl:with-param>
-               <xsl:with-param name="attrValue" select="normalize-space(@name)"/>
-            </xsl:call-template>
-            <!-- Attribute: refers -->
-            <xsl:call-template name="DisplayAttr">
-               <xsl:with-param name="attrName">refer</xsl:with-param>
-               <xsl:with-param name="attrValue">
-                  <xsl:call-template name="PrintKeyRef">
-                     <xsl:with-param name="ref">
-                        <xsl:value-of select="normalize-space(@refer)"/>
-                     </xsl:with-param>
-                  </xsl:call-template>
-               </xsl:with-param>
-            </xsl:call-template>
-            <!-- Other attributes -->
-            <xsl:call-template name="DisplayOtherAttributes">
-               <xsl:with-param name="component" select="."/>
-               <xsl:with-param name="attrsNotToDisplay">*name+*refer+</xsl:with-param>
-            </xsl:call-template>
-         </xsl:with-param>
-         <xsl:with-param name="excludeFilter">*annotation+</xsl:with-param>
-      </xsl:call-template>
-   </xsl:template>
-
-   <!--
-     Prints out schema component representation of 
-     derivations by extension and restrictions.
-     Param(s):
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-     -->
-   <xsl:template match="xsd:extension | xsd:restriction" mode="schemaComponent">
-      <xsl:param name="margin">0</xsl:param>
-
-      <xsl:call-template name="DisplaySchemaComponent">
-         <xsl:with-param name="component" select="."/>
-         <xsl:with-param name="margin" select="$margin"/>
-         <xsl:with-param name="attributes">
-            <!-- Attribute: base -->
-            <xsl:if test="@base">
-               <xsl:call-template name="DisplayAttr">
-                  <xsl:with-param name="attrName">base</xsl:with-param>
-                  <xsl:with-param name="attrValue">
-                     <xsl:call-template name="PrintTypeRef">
-                        <xsl:with-param name="ref" select="normalize-space(@base)"/>
-                     </xsl:call-template>
-                  </xsl:with-param>
-               </xsl:call-template>
-            </xsl:if>
-            <!-- Other attributes -->
-            <xsl:call-template name="DisplayOtherAttributes">
-               <xsl:with-param name="component" select="."/>
-               <xsl:with-param name="attrsNotToDisplay">*base+</xsl:with-param>
-            </xsl:call-template>
-         </xsl:with-param>
-         <xsl:with-param name="excludeFilter">*annotation+</xsl:with-param>
-      </xsl:call-template>
-   </xsl:template>
-
-   <!--
-     Prints out schema component representation of 
-     derivations by list.
-     Param(s):
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-     -->
-   <xsl:template match="xsd:list" mode="schemaComponent">
-      <xsl:param name="margin">0</xsl:param>
-
-      <xsl:call-template name="DisplaySchemaComponent">
-         <xsl:with-param name="component" select="."/>
-         <xsl:with-param name="margin" select="$margin"/>
-         <xsl:with-param name="attributes">
-            <!-- Attribute: itemType-->
-            <xsl:if test="@itemType">
-               <xsl:call-template name="DisplayAttr">
-                  <xsl:with-param name="attrName">itemType</xsl:with-param>
-                  <xsl:with-param name="attrValue">
-                     <xsl:call-template name="PrintTypeRef">
-                        <xsl:with-param name="ref" select="normalize-space(@itemType)"/>
-                     </xsl:call-template>
-                  </xsl:with-param>
-               </xsl:call-template>
-            </xsl:if>
-            <!-- Other attributes -->
-            <xsl:call-template name="DisplayOtherAttributes">
-               <xsl:with-param name="component" select="."/>
-               <xsl:with-param name="attrsNotToDisplay">*itemType+</xsl:with-param>
-            </xsl:call-template>
-         </xsl:with-param>
-         <xsl:with-param name="excludeFilter">*annotation+</xsl:with-param>
-      </xsl:call-template>
-   </xsl:template>
-
-   <!--
-     Prints out schema component representation of 
-     derivations by union.
-     Param(s):
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-     -->
-   <xsl:template match="xsd:union" mode="schemaComponent">
-      <xsl:param name="margin">0</xsl:param>
-
-      <xsl:call-template name="DisplaySchemaComponent">
-         <xsl:with-param name="component" select="."/>
-         <xsl:with-param name="margin" select="$margin"/>
-         <xsl:with-param name="attributes">
-            <!-- Attribute: memberTypes-->
-            <xsl:if test="@memberTypes">
-               <xsl:call-template name="DisplayAttr">
-                  <xsl:with-param name="attrName">memberTypes</xsl:with-param>
-                  <xsl:with-param name="attrValue">
-                     <xsl:call-template name="PrintWhitespaceList">
-                        <xsl:with-param name="value" select="normalize-space(@memberTypes)"/>
-                        <xsl:with-param name="compType">type</xsl:with-param>
-                     </xsl:call-template>
-                  </xsl:with-param>
-               </xsl:call-template>
-            </xsl:if>
-            <!-- Other attributes -->
-            <xsl:call-template name="DisplayOtherAttributes">
-               <xsl:with-param name="component" select="."/>
-               <xsl:with-param name="attrsNotToDisplay">*memberTypes+</xsl:with-param>
-            </xsl:call-template>
-         </xsl:with-param>
-         <xsl:with-param name="excludeFilter">*annotation+</xsl:with-param>
-      </xsl:call-template>
-   </xsl:template>
-
-   <!--
-     Prints out schema component representation of 
-     the root schema element.
-     Param(s):
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-     -->
-   <xsl:template match="xsd:schema" mode="schemaComponent">
-      <xsl:param name="margin">0</xsl:param>
-
-      <xsl:call-template name="DisplaySchemaComponent">
-         <xsl:with-param name="component" select="."/>
-         <xsl:with-param name="margin" select="$margin"/>
-         <xsl:with-param name="attributes">
-            <!-- Attribute: source -->
-            <xsl:if test="@xml:lang">
-               <xsl:call-template name="DisplayAttr">
-                  <xsl:with-param name="attrName">xml:lang</xsl:with-param>
-                  <xsl:with-param name="attrValue" select="normalize-space(@xml:lang)"/>
-               </xsl:call-template>
-            </xsl:if>
-            <!-- Other attributes -->
-            <xsl:call-template name="DisplayOtherAttributes">
-               <xsl:with-param name="component" select="."/>
-               <xsl:with-param name="attrsNotToDisplay">*lang+</xsl:with-param>
-            </xsl:call-template>
-         </xsl:with-param>
-         <xsl:with-param name="includeFilter">*include+*import+*redefine+</xsl:with-param>
-      </xsl:call-template>
-   </xsl:template>
-
-   <!--
-     Default way to print out schema component representation.
-     Param(s):
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-     -->
-   <xsl:template match="*" mode="schemaComponent">
-      <xsl:param name="margin">0</xsl:param>
-
-      <xsl:call-template name="DisplaySchemaComponent">
-         <xsl:with-param name="component" select="."/>
-         <xsl:with-param name="margin" select="$margin"/>
-         <xsl:with-param name="attributes">
-            <xsl:call-template name="DisplayOtherAttributes">
-               <xsl:with-param name="component" select="."/>
-            </xsl:call-template>
-         </xsl:with-param>
-         <xsl:with-param name="excludeFilter">*annotation+</xsl:with-param>
-      </xsl:call-template>
-   </xsl:template>
-
-   <!--
-     Prints out comments in schema component representation.
-     Param(s):
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-     -->
-   <xsl:template match="comment()" mode="schemaComponent">
-      <xsl:param name="margin">0</xsl:param>
-
-      <div class="comment" style="margin-left: {$margin}em">
-         <xsl:text>&lt;--</xsl:text>
-         <xsl:value-of select="."/>
-         <xsl:text>--&gt;</xsl:text>
-      </div>
-   </xsl:template>
-
-   <!--
-     Displays a schema element in the correct format
-     for the Schema Component Representation table, e.g.
-     tags are one color, and content are another.
-     Param(s):
-            component (Node) required
-                Schema element to be displayed
-            attributes (Result Tree Fragment) optional
-                Pre-formatted attributes of schema element
-            margin (nonNegativeInteger) optional
-                Number of 'em' to indent from left
-            hasAnyContent (boolean) optional
-                Set to true if schema element can accept 
-                child elements from namespaces other than
-                the schema namespace, e.g. 'documentation'
-                and 'appinfo'
-            includeFilter (String) optional
-                List of element names, sandwiched between the
-                characters, '*' and '+'. If specified, only the
-                child elements of the component with tags in 
-                the list will be displayed.
-            excludeFilter (String) optional
-                List of element names, sandwiched between the
-                characters, '*' and '+'. If specified, display
-                all child elements of the component, except
-                those with tags in the list.
-     -->
-   <xsl:template name="DisplaySchemaComponent">
-      <xsl:param name="component"/>
-      <xsl:param name="attributes"/>
-      <xsl:param name="margin">0</xsl:param>
-      <xsl:param name="hasAnyContent">false</xsl:param>
-      <xsl:param name="includeFilter"/>
-      <xsl:param name="excludeFilter"/>
-
-      <xsl:variable name="tag">
-         <xsl:call-template name="PrintNSPrefix">
-            <xsl:with-param name="prefix">
-               <xsl:call-template name="GetXSDPrefix"/>
-            </xsl:with-param>
-            <xsl:with-param name="nolink">true</xsl:with-param>
-         </xsl:call-template>
-         <xsl:value-of select="local-name($component)"/>
-      </xsl:variable>
-
-      <div style="margin-left: {$margin}em">
-         <!-- Start Tag -->
-         <xsl:text>&lt;</xsl:text>
-         <span class="scTag">
-            <xsl:copy-of select="$tag"/>
-         </span>
-         <!-- Attributes -->
-         <xsl:copy-of select="$attributes"/>
-         <!-- Content -->
-         <xsl:variable name="content">
-            <xsl:choose>
-               <!-- Include filter is on -->
-               <xsl:when test="$includeFilter!=''">
-                  <xsl:apply-templates select="$component/xsd:*[contains($includeFilter, concat('*', local-name(.), '+'))]" mode="schemaComponent">
-                     <xsl:with-param name="margin" select="$ELEM_INDENT"/>
-                  </xsl:apply-templates>
-                  <div class="scContent" style="margin-left: {$ELEM_INDENT}em">...</div>
-               </xsl:when>
-               <!-- Exclude filter is on -->
-               <xsl:when test="$excludeFilter!=''">
-                  <xsl:apply-templates select="comment() | $component/xsd:*[not(contains($excludeFilter, concat('*', local-name(.), '+')))]" mode="schemaComponent">
-                     <xsl:with-param name="margin" select="$ELEM_INDENT"/>
-                  </xsl:apply-templates>
-               </xsl:when>
-               <!-- Permits any content -->
-               <xsl:when test="$hasAnyContent='true'">
-                  <div class="scContent" style="margin-left: {$ELEM_INDENT}em">
-                     <xsl:apply-templates select="comment() | $component/* | $component/text()" mode="xpp"/>
-                  </div>
-               </xsl:when>
-               <!-- Contains schema elements -->
-               <xsl:otherwise>
-                  <xsl:apply-templates select="comment() | $component/xsd:*" mode="schemaComponent">
-                     <xsl:with-param name="margin" select="$ELEM_INDENT"/>
-                  </xsl:apply-templates>
-               </xsl:otherwise>
-            </xsl:choose>
-         </xsl:variable>
-
-         <xsl:choose>
-            <!-- Has content -->
-            <xsl:when test="normalize-space($content)!=''">
-               <!-- End of start tag -->
-               <xsl:text>></xsl:text>
-
-               <!-- Content -->
-               <xsl:copy-of select="$content"/>
-
-               <!-- End Tag -->
-               <xsl:text>&lt;/</xsl:text>
-               <span class="scTag">
-                  <xsl:copy-of select="$tag"/>
-               </span>
-               <xsl:text>></xsl:text>
-            </xsl:when>
-            <!-- Empty content -->
-            <xsl:otherwise>
-               <!-- End of start tag -->
-               <xsl:text>/></xsl:text>
-            </xsl:otherwise>
-         </xsl:choose>
-      </div>
-   </xsl:template>
-
-   <!--
-     Displays a schema attribute in the correct format
-     for the Schema Component Representation table, e.g.
-     tags are one color, and content are another.
-     Param(s):
-            attrName (String) required
-                Name of attribute
-            attrValue (Result Tree Fragment) required
-                Value of attribute, which may be links
-     -->
-   <xsl:template name="DisplayAttr">
-      <xsl:param name="attrName"/>
-      <xsl:param name="attrValue"/>
-
-      <xsl:text> </xsl:text>
-      <span class="scTag">
-         <xsl:value-of select="$attrName"/>
-      </span>
-      <xsl:text>="</xsl:text>
-      <xsl:if test="normalize-space($attrValue)!=''">
-         <span class="scContent">
-            <xsl:copy-of select="$attrValue"/>
-         </span>
-      </xsl:if>
-      <xsl:text>"</xsl:text>
-   </xsl:template>
-
-   <!--
-     Displays attributes from a schema element, unless
-     otherwise specified, in the correct format
-     for the Schema Component Representation table, e.g.
-     tags are one color, and content are another.
-     Param(s):
-            component (Node) required
-                Schema element whose attributes are to be displayed
-            attrsNotToDisplay (String) required
-                List of attributes not to be displayed
-                Each attribute name should prepended with '*'
-                and appended with '+'
-     -->
-   <xsl:template name="DisplayOtherAttributes">
-      <xsl:param name="component"/>
-      <xsl:param name="attrsNotToDisplay"/>
-
-      <xsl:for-each select="$component/attribute::*">
-         <xsl:variable name="attrName" select="local-name(.)"/>
-         <xsl:if test="not(contains($attrsNotToDisplay, concat('*', $attrName, '+')))">
-            <xsl:call-template name="DisplayAttr">
-               <xsl:with-param name="attrName" select="normalize-space($attrName)"/>
-               <xsl:with-param name="attrValue" select="normalize-space(.)"/>
-            </xsl:call-template>
-         </xsl:if>
-      </xsl:for-each>
-   </xsl:template>
-
-
-   <!-- ******** XML Pretty Printer ******** -->
-
-   <!--
-     Puts XHTML elements into the result.
-     -->
-   <xsl:template match="html:*" mode="html">
-      <xsl:element name="{local-name(.)}">
-         <xsl:for-each select="@*">
-            <xsl:copy-of select="."/>
-         </xsl:for-each>
-         <xsl:apply-templates select="* | text()" mode="html"/>
-      </xsl:element>
-   </xsl:template>
-
-   <!--
-     Displays non-XHTML elements found within XHTML elements.
-     -->
-   <xsl:template match="*" mode="html">
-      <xsl:call-template name="WriteElement">
-         <xsl:with-param name="element" select="."/>
-         <xsl:with-param name="mode">html</xsl:with-param>
-      </xsl:call-template>
-   </xsl:template>
-
-   <!--
-     Displays text node.
-     -->
-   <xsl:template match="text()" mode="html">
-      <xsl:value-of select="."/>
-   </xsl:template>
-
-   <!--
-     Displays an arbitrary XML element.
-     -->
-   <xsl:template match="*" mode="xpp">
-      <code>
-         <xsl:call-template name="WriteElement">
-            <xsl:with-param name="element" select="."/>
-            <xsl:with-param name="mode">xpp</xsl:with-param>
-         </xsl:call-template>
-      </code>
-   </xsl:template>
-
-   <!--
-     Displays an arbitrary XML text node.
-     -->
-   <xsl:template match="text()" mode="xpp">
-      <xsl:value-of select="."/>
-   </xsl:template>
-
-   <!--
-     Displays an XML comment.
-     -->
-   <xsl:template match="comment()" mode="xpp">
-      <div class="comment">
-         <xsl:text>&lt;--</xsl:text>
-         <xsl:value-of select="."/>
-         <xsl:text>--&gt;</xsl:text>
-      </div>
-   </xsl:template>
-
-   <!--
-     Displays an XML element in the documentation, e.g.
-     tags are escaped.
-     Param(s):
-            element (Node) required
-                XML element to display
-            mode (xpp|html) required
-                Which mode to invoke for child elements
-     -->
-   <xsl:template name="WriteElement">
-      <xsl:param name="element"/>
-      <xsl:param name="mode">xpp</xsl:param>
-
-      <!-- Start Tag -->
-      <xsl:text>&lt;</xsl:text>
-      <xsl:call-template name="PrintNSPrefix">
-         <xsl:with-param name="prefix">
-            <xsl:call-template name="GetRefPrefix">
-               <xsl:with-param name="ref" select="name($element)"/>
-            </xsl:call-template>
-         </xsl:with-param>
-      </xsl:call-template>
-      <xsl:value-of select="local-name($element)"/>
-      <!-- Attributes -->
-      <xsl:for-each select="$element/@*">
-         <xsl:text> </xsl:text>
-         <xsl:value-of select="name(.)"/>
-         <xsl:text>="</xsl:text>
-         <xsl:value-of select="."/>
-         <xsl:text>"</xsl:text>
-      </xsl:for-each>
-
-      <xsl:choose>
-         <xsl:when test="$element/* | $element/text()">
-            <!-- Close Start Tag -->
-            <xsl:text>> </xsl:text>
-            <!-- Content -->
-            <xsl:choose>
-               <xsl:when test="$mode!='xpp'">
-                  <xsl:apply-templates select="$element/* | $element/text()" mode="html"/>
-               </xsl:when>
-               <xsl:otherwise>
-                  <div style="margin-left: {$ELEM_INDENT}em">
-                     <xsl:apply-templates select="$element/* | $element/text()" mode="xpp"/>
-                  </div>
-               </xsl:otherwise>
-            </xsl:choose>
-            <!-- End Tag -->
-            <xsl:text>&lt;/</xsl:text>
-            <xsl:call-template name="PrintNSPrefix">
-               <xsl:with-param name="prefix">
-                  <xsl:call-template name="GetRefPrefix">
-                     <xsl:with-param name="ref" select="name($element)"/>
-                  </xsl:call-template>
-               </xsl:with-param>
-            </xsl:call-template>
-            <xsl:value-of select="local-name($element)"/>
-            <xsl:text>></xsl:text>
-         </xsl:when>
-         <xsl:otherwise>
-            <!-- Close Start Tag -->
-            <xsl:text>/></xsl:text>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-
-   <!-- ******** Templates for Handling References ******** -->
-
-   <!--
-     Prints out a reference to a term in the glossary section.
-     Param(s):
-            code (String) required
-              Unique ID of glossary term
-            term (String) optional
-              Glossary term
-     -->
-   <xsl:template name="PrintGlossaryTermRef">
-      <xsl:param name="code"/>
-      <xsl:param name="term"/>
-
-      <xsl:choose>
-         <xsl:when test="$code !='' and normalize-space(translate($printGlossary,'TRUE','true'))='true'">
-            <a title="Look up '{$term}' in glossary" href="#{concat($TERM_PREFIX, $code)}">
-               <xsl:choose>
-                  <xsl:when test="$term!=''">
-                     <xsl:value-of select="$term"/>
-                  </xsl:when>
-                  <xsl:otherwise>
-                     <xsl:text>[term]</xsl:text>
-                  </xsl:otherwise>
-               </xsl:choose>
-            </a>
-         </xsl:when>
-         <xsl:otherwise>
-            <xsl:value-of select="$term"/>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Prints out a reference to a namespace in the schema.
-     Param(s):
-            prefix (String) required
-              Namespace prefix referenced
-            schemaLoc (String) optional
-                Schema file containing this namespace prefix;
-                if in current schema, 'schemaLoc' is set to 'this'
-     -->
-   <xsl:template name="PrintNamespaceRef">
-      <xsl:param name="prefix"/>
-      <xsl:param name="schemaLoc">this</xsl:param>
-
-      <xsl:if test="$prefix!=''">
-         <xsl:choose>
-            <xsl:when test="/xsd:schema/namespace::*[local-name(.)=normalize-space($prefix)]">
-               <xsl:variable name="link">
-                  <xsl:if test="normalize-space($schemaLoc)!='this'">
-                     <xsl:call-template name="GetSchemaDocLocation">
-                        <xsl:with-param name="uri" select="$schemaLoc"/>
-                     </xsl:call-template>
-                  </xsl:if>
-                  <xsl:value-of select="concat('#', $NS_PREFIX, $prefix)"/>
-               </xsl:variable>
-               <a href="{$link}" title="Find out namespace of '{$prefix}' prefix">
-                  <xsl:value-of select="$prefix"/>
-               </a>
-            </xsl:when>
-            <xsl:otherwise>
-               <xsl:variable name="title">
-                  <xsl:text>Unknown namespace prefix, </xsl:text>
-                  <xsl:value-of select="$prefix"/>
-                  <xsl:text>.</xsl:text>
-               </xsl:variable>
-               <a href="javascript:void(0)" onclick="alert('{$title}')" title="{$title}">
-                  <xsl:value-of select="$prefix"/>
-               </a>
-            </xsl:otherwise>
-         </xsl:choose>
-      </xsl:if>
-   </xsl:template>
-
-   <!--
-     Generates a link to an attribute.
-     Param(s):
-            name (String) optional
-                Name of attribute
-            ref (String) optional
-                Reference to attribute
-            (One of 'name' and 'ref' must be provided.)
-            schemaLoc (String) optional
-                Schema file containing this attribute reference
-                if in current schema, 'schemaLoc' is set to 'this'
-     -->
-   <xsl:template name="PrintAttributeRef">
-      <xsl:param name="name"/>
-      <xsl:param name="ref"/>
-      <xsl:param name="schemaLoc">this</xsl:param>
-
-      <xsl:choose>
-         <xsl:when test="$name!=''">
-            <xsl:call-template name="PrintCompName">
-               <xsl:with-param name="name" select="$name"/>
-               <xsl:with-param name="compType">attribute</xsl:with-param>
-               <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-            </xsl:call-template>
-         </xsl:when>
-         <xsl:when test="$ref!=''">
-            <xsl:call-template name="PrintCompRef">
-               <xsl:with-param name="ref" select="$ref"/>
-               <xsl:with-param name="compType">attribute</xsl:with-param>
-               <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-            </xsl:call-template>
-         </xsl:when>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Generates a link to an attribute group.
-     Param(s):
-            name (String) optional
-                Name of attribute group
-            ref (String) optional
-                Reference to attribute group
-            (One of 'name' and 'ref' must be provided.)
-            schemaLoc (String) optional
-                Schema file containing this attribute group reference
-                if in current schema, 'schemaLoc' is set to 'this'
-     -->
-   <xsl:template name="PrintAttributeGroupRef">
-      <xsl:param name="name"/>
-      <xsl:param name="ref"/>
-      <xsl:param name="schemaLoc">this</xsl:param>
-
-      <xsl:choose>
-         <xsl:when test="$name!=''">
-            <xsl:call-template name="PrintCompName">
-               <xsl:with-param name="name" select="$name"/>
-               <xsl:with-param name="compType">attribute group</xsl:with-param>
-               <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-            </xsl:call-template>
-         </xsl:when>
-         <xsl:when test="$ref!=''">
-            <xsl:call-template name="PrintCompRef">
-               <xsl:with-param name="ref" select="$ref"/>
-               <xsl:with-param name="compType">attribute group</xsl:with-param>
-               <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-            </xsl:call-template>
-         </xsl:when>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Generates a link to an element.
-     Param(s):
-            name (String) optional
-                Name of element
-            ref (String) optional
-                Reference to element
-            (One of 'name' and 'ref' must be provided.)
-            schemaLoc (String) optional
-                Schema file containing this element reference
-                if in current schema, 'schemaLoc' is set to 'this'
-     -->
-   <xsl:template name="PrintElementRef">
-      <xsl:param name="name"/>
-      <xsl:param name="ref"/>
-      <xsl:param name="schemaLoc">this</xsl:param>
-
-      <xsl:choose>
-         <xsl:when test="$name!=''">
-            <xsl:call-template name="PrintCompName">
-               <xsl:with-param name="name" select="$name"/>
-               <xsl:with-param name="compType">element</xsl:with-param>
-               <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-            </xsl:call-template>
-         </xsl:when>
-         <xsl:when test="$ref!=''">
-            <xsl:call-template name="PrintCompRef">
-               <xsl:with-param name="ref" select="$ref"/>
-               <xsl:with-param name="compType">element</xsl:with-param>
-               <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-            </xsl:call-template>
-         </xsl:when>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Generates a link to a group.
-     Param(s):
-            name (String) optional
-                Name of group
-            ref (String) optional
-                Reference to group
-            (One of 'name' and 'ref' must be provided.)
-            schemaLoc (String) optional
-                Schema file containing this group reference
-                if in current schema, 'schemaLoc' is set to 'this'
-     -->
-   <xsl:template name="PrintGroupRef">
-      <xsl:param name="name"/>
-      <xsl:param name="ref"/>
-      <xsl:param name="schemaLoc">this</xsl:param>
-
-      <xsl:choose>
-         <xsl:when test="$name!=''">
-            <xsl:call-template name="PrintCompName">
-               <xsl:with-param name="name" select="$name"/>
-               <xsl:with-param name="compType">group</xsl:with-param>
-               <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-            </xsl:call-template>
-         </xsl:when>
-         <xsl:when test="$ref!=''">
-            <xsl:call-template name="PrintCompRef">
-               <xsl:with-param name="ref" select="$ref"/>
-               <xsl:with-param name="compType">group</xsl:with-param>
-               <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-            </xsl:call-template>
-         </xsl:when>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Generates a link to a key/uniqueness constraint.
-     Param(s):
-            name (String) optional
-                Name of key/uniqueness constraint
-            ref (String) optional
-                Reference to key/uniqueness constraint
-            (One of 'name' and 'ref' must be provided.)
-            schemaLoc (String) optional
-                Schema file containing this key/uniqueness constraint
-                reference; if in current schema, 'schemaLoc' is set 
-                to 'this'
-     -->
-   <xsl:template name="PrintKeyRef">
-      <xsl:param name="name"/>
-      <xsl:param name="ref"/>
-      <xsl:param name="schemaLoc">this</xsl:param>
-
-      <xsl:choose>
-         <xsl:when test="$name!=''">
-            <xsl:call-template name="PrintCompName">
-               <xsl:with-param name="name" select="$name"/>
-               <xsl:with-param name="compType">uniqueness/key constraint</xsl:with-param>
-               <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-            </xsl:call-template>
-         </xsl:when>
-         <xsl:when test="$ref!=''">
-            <xsl:call-template name="PrintCompRef">
-               <xsl:with-param name="ref" select="$ref"/>
-               <xsl:with-param name="compType">uniqueness/key constraint</xsl:with-param>
-               <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-            </xsl:call-template>
-         </xsl:when>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Generates a link to a type.
-     Param(s):
-            name (String) optional
-                Name of type
-            ref (String) optional
-                Reference to type
-            (One of 'name' and 'ref' must be provided.)
-            schemaLoc (String) optional
-                Schema file containing this type reference'
-                if in current schema, 'schemaLoc' is set 
-                to 'this'
-     -->
-   <xsl:template name="PrintTypeRef">
-      <xsl:param name="name"/>
-      <xsl:param name="ref"/>
-      <xsl:param name="schemaLoc">this</xsl:param>
-
-      <xsl:choose>
-         <xsl:when test="$name!=''">
-            <span class="type">
-               <xsl:call-template name="PrintCompName">
-                  <xsl:with-param name="name" select="$name"/>
-                  <xsl:with-param name="compType">type</xsl:with-param>
-                  <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-               </xsl:call-template>
-            </span>
-         </xsl:when>
-         <xsl:when test="$ref!=''">
-            <span class="type">
-               <xsl:call-template name="PrintCompRef">
-                  <xsl:with-param name="ref" select="$ref"/>
-                  <xsl:with-param name="compType">type</xsl:with-param>
-                  <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-               </xsl:call-template>
-            </span>
-         </xsl:when>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Prints out a link to a schema component's section.
-     Param(s):
-            baseFile (String) optional
-                Documentation file of schema containing this 
-                component.
-                If this component belongs to the current schema, 
-                omit this variable.
-                If this component is from an included or imported 
-                schema, provide this variable.
-            name (String) required
-                Name of schema component
-            compType (String) required
-                Type of schema component
-            errMsg (String) optional
-                Sentence fragment.
-                If specified, link will open up an alert box with 
-                an error message. For example, if 'errMsg' was set 
-                to "could not be found", 'name' was "x", and
-                'compType' was "type", the error message would be:
-                "x" type definition could not be found.
-                The sentence fragment should not:
-                -start with a capital letter.
-                -have a space in front
-                -end with a period.
-            schemaLoc (String) optional
-                Schema file containing this component;
-                if in current schema, 'schemaLoc' is set to 'this'
-     -->
-   <xsl:template name="PrintCompName">
-      <xsl:param name="baseFile"/>
-      <xsl:param name="name"/>
-      <xsl:param name="compType"/>
-      <xsl:param name="schemaLoc">this</xsl:param>
-      <xsl:param name="errMsg"/>
-
-      <!-- Get correct terminology for statements -->
-      <xsl:variable name="noun">
-         <xsl:choose>
-            <xsl:when test="$compType='element' or $compType='attribute'">
-               <xsl:text>declaration</xsl:text>
-            </xsl:when>
-            <xsl:otherwise>
-               <xsl:text>definition</xsl:text>
-            </xsl:otherwise>
-         </xsl:choose>
-      </xsl:variable>
-
-      <!-- Get prefix to use in anchor name. -->
-      <xsl:variable name="compPrefix">
-         <xsl:choose>
-            <xsl:when test="$compType='attribute'">
-               <xsl:value-of select="$ATTR_PREFIX"/>
-            </xsl:when>
-            <xsl:when test="$compType='attribute group'">
-               <xsl:value-of select="$ATTR_GRP_PREFIX"/>
-            </xsl:when>
-            <xsl:when test="$compType='element'">
-               <xsl:value-of select="$ELEM_PREFIX"/>
-            </xsl:when>
-            <xsl:when test="$compType='group'">
-               <xsl:value-of select="$GRP_PREFIX"/>
-            </xsl:when>
-            <xsl:when test="$compType='type'">
-               <xsl:value-of select="$TYPE_PREFIX"/>
-            </xsl:when>
-            <xsl:when test="$compType='uniqueness/key constraint'">
-               <xsl:value-of select="$KEY_PREFIX"/>
-            </xsl:when>
-         </xsl:choose>
-      </xsl:variable>
-
-      <!-- Get base URI. -->
-      <xsl:variable name="baseURI">
-         <xsl:choose>
-            <xsl:when test="$baseFile!=''">
-               <xsl:value-of select="$baseFile"/>
-            </xsl:when>
-            <xsl:when test="normalize-space($schemaLoc)!='this'">
-               <xsl:call-template name="GetSchemaDocLocation">
-                  <xsl:with-param name="uri" select="$schemaLoc"/>
-               </xsl:call-template>
-            </xsl:when>
-         </xsl:choose>
-      </xsl:variable>
-
-      <!-- Generate message. -->
-      <xsl:variable name="title">
-         <xsl:choose>
-            <!-- Error message was provided. -->
-            <xsl:when test="$errMsg!=''">
-               <xsl:text>"</xsl:text><xsl:value-of select="$name"/><xsl:text>" </xsl:text>
-               <xsl:value-of select="$compType"/><xsl:text> </xsl:text>
-               <xsl:value-of select="$noun"/><xsl:text> </xsl:text>
-               <xsl:value-of select="$errMsg"/>
-            </xsl:when>
-            <!-- There exists a link to the schema component's
-                 documentation. -->
-            <xsl:otherwise>
-               <xsl:text>Jump to "</xsl:text>
-               <xsl:value-of select="$name"/>
-               <xsl:text>" </xsl:text>
-               <xsl:value-of select="$compType"/>
-               <xsl:text> </xsl:text>
-               <xsl:value-of select="$noun"/>
-               <!-- External link -->
-               <xsl:if test="normalize-space($baseURI)!=''">
-                  <xsl:text>(located in external schema documentation)</xsl:text>
-               </xsl:if>
-            </xsl:otherwise>
-         </xsl:choose>
-         <xsl:text>.</xsl:text>
-      </xsl:variable>
-
-      <!-- Generate href link -->
-      <xsl:variable name="link">
-         <xsl:choose>
-            <!-- Error message was provided. -->
-            <xsl:when test="$errMsg!=''">
-               <xsl:text>javascript:void(0)</xsl:text>
-            </xsl:when>
-            <!-- There exists a link to the schema component's
-                 documentation. -->
-            <xsl:otherwise>
-               <!-- Base URI -->
-               <xsl:value-of select="normalize-space($baseURI)"/>
-               <!-- Anchor within URI -->
-               <xsl:value-of select="concat('#',normalize-space($compPrefix),normalize-space($name))"/>
-            </xsl:otherwise>
-         </xsl:choose>
-      </xsl:variable>
-
-      <a title="{$title}" href="{$link}">
-         <!-- External link -->
-         <xsl:if test="normalize-space($baseURI)!=''">
-            <xsl:attribute name="class">externalLink</xsl:attribute>
-         </xsl:if>
-
-         <!-- Error message was provided. -->
-         <xsl:if test="$errMsg!=''">
-            <xsl:attribute name="onclick">
-               <xsl:text>alert('</xsl:text>
-               <xsl:value-of select="$title"/>
-               <xsl:text>');</xsl:text>
-            </xsl:attribute>
-         </xsl:if>
-
-         <xsl:value-of select="$name"/>
-      </a>
-   </xsl:template>
-
-   <!--
-     Prints out a reference to a schema component.
-     This template will try to work out which schema that this
-     component belongs to and print out the appropriate link.
-     component.
-     It will also print out the namespace prefix given
-     in the reference.
-     Param(s):
-            ref (String) required
-                Reference to schema component
-            compType (String) required
-                Type of schema component
-            schemaLoc (String) optional
-                Schema file containing this component reference;
-                if in current schema, 'schemaLoc' is set to 'this'
-     -->
-   <xsl:template name="PrintCompRef">
-      <xsl:param name="ref"/>
-      <xsl:param name="compType"/>
-      <xsl:param name="schemaLoc">this</xsl:param>
-
-      <!-- Get correct terminology for statements -->
-      <xsl:variable name="noun">
-         <xsl:choose>
-            <xsl:when test="$compType='element' or $compType='attribute'">
-               <xsl:text>declaration</xsl:text>
-            </xsl:when>
-            <xsl:otherwise>
-               <xsl:text>definition</xsl:text>
-            </xsl:otherwise>
-         </xsl:choose>
-      </xsl:variable>
-
-      <!-- Get local name -->
-      <xsl:variable name="refName">
-         <xsl:call-template name="GetRefName">
-            <xsl:with-param name="ref" select="$ref"/>
-         </xsl:call-template>
-      </xsl:variable>
-
-      <!-- Get prefix -->
-      <xsl:variable name="refPrefix">
-         <xsl:call-template name="GetRefPrefix">
-            <xsl:with-param name="ref" select="$ref"/>
-         </xsl:call-template>
-      </xsl:variable>
-
-      <!-- Get prefix of this schema's target namespace -->
-      <xsl:variable name="tnPrefix">
-         <xsl:call-template name="GetThisPrefix"/>
-      </xsl:variable>
-
-      <!-- Get file location of the schema component that is
-           being referenced. -->
-      <xsl:variable name="compLoc">
-         <xsl:call-template name="FindComponent">
-            <xsl:with-param name="ref" select="$ref"/>
-            <xsl:with-param name="compType" select="$compType"/>
-         </xsl:call-template>
-      </xsl:variable>
-
-      <!-- Print prefix -->
-      <xsl:call-template name="PrintNSPrefix">
-         <xsl:with-param name="prefix" select="$refPrefix"/>
-         <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-      </xsl:call-template>
-
-      <!-- Print local name -->
-      <xsl:choose>
-         <!-- Component from XML Schema's or XML's namespace -->
-         <xsl:when test="normalize-space($compLoc)='xsd' or normalize-space($compLoc)='xml'">
-            <xsl:value-of select="$refName"/>
-         </xsl:when>
-         <!-- Component found in this schema. -->
-         <xsl:when test="normalize-space($compLoc)='this'">
-            <xsl:call-template name="PrintCompName">
-               <xsl:with-param name="name" select="$refName"/>
-               <xsl:with-param name="compType" select="$compType"/>
-               <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-            </xsl:call-template>
-         </xsl:when>
-         <!-- Component not found. -->
-         <xsl:when test="normalize-space($compLoc)='' or normalize-space($compLoc)='none'">
-            <xsl:call-template name="PrintCompName">
-               <xsl:with-param name="name" select="$refName"/>
-               <xsl:with-param name="compType" select="$compType"/>
-               <xsl:with-param name="errMsg">could not be found</xsl:with-param>
-            </xsl:call-template>
-         </xsl:when>
-         <!-- Component found in an external schema. -->
-         <xsl:otherwise>
-            <!-- Get documentation file for included schema. -->
-            <xsl:variable name="docFile">
-               <xsl:call-template name="GetSchemaDocLocation">
-                  <xsl:with-param name="uri" select="$compLoc"/>
-               </xsl:call-template>
-            </xsl:variable>
-
-            <xsl:call-template name="PrintCompName">
-               <xsl:with-param name="baseFile" select="$docFile"/>
-               <xsl:with-param name="name" select="$refName"/>
-               <xsl:with-param name="compType" select="$compType"/>
-               <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-            </xsl:call-template>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-
-   <!-- ******** Templates for Finding Components in Different
-             Schema documents ******** -->
-
-   <!-- Special key words: xml, xsd, this, none -->
-   <xsl:template name="FindComponent">
-      <xsl:param name="ref"/>
-      <xsl:param name="compType"/>
-
-      <!-- Get local name -->
-      <xsl:variable name="refName">
-         <xsl:call-template name="GetRefName">
-            <xsl:with-param name="ref" select="$ref"/>
-         </xsl:call-template>
-      </xsl:variable>
-
-      <!-- Get prefix -->
-      <xsl:variable name="refPrefix">
-         <xsl:call-template name="GetRefPrefix">
-            <xsl:with-param name="ref" select="$ref"/>
-         </xsl:call-template>
-      </xsl:variable>
-
-      <!-- Get prefix of this schema's target namespace -->
-      <xsl:variable name="tnPrefix">
-         <xsl:call-template name="GetThisPrefix"/>
-      </xsl:variable>
-
-      <!-- Get prefix of XML Schema -->
-      <xsl:variable name="xsdPrefix">
-         <xsl:call-template name="GetXSDPrefix"/>
-      </xsl:variable>
-
-      <xsl:choose>
-         <!-- Schema component from XML Schema's namespace,
-              unless this schema is for XML Schema -->
-         <xsl:when test="$refPrefix=$xsdPrefix and $xsdPrefix!=$tnPrefix">
-            <xsl:text>xsd</xsl:text>
-         </xsl:when>
-         <!-- Schema component from XML's namespace -->
-         <xsl:when test="$refPrefix='xml'">
-            <xsl:text>xml</xsl:text>
-         </xsl:when>
-         <!-- Schema component from current schema's namespace -->
-         <xsl:when test="$refPrefix=$tnPrefix">
-            <xsl:call-template name="FindComponentInSchema">
-               <xsl:with-param name="name" select="$refName"/>
-               <xsl:with-param name="compType" select="$compType"/>
-               <xsl:with-param name="schema" select="/xsd:schema"/>
-               <xsl:with-param name="schemaFileLoc">this</xsl:with-param>
-            </xsl:call-template>
-         </xsl:when>
-         <!-- Schema component from imported namespace -->
-         <xsl:when test="normalize-space(translate($searchImportedSchemas, 'TRUE', 'true'))='true'">
-            <xsl:variable name="refNS" select="/xsd:schema/namespace::*[local-name(.)=normalize-space($refPrefix)]"/>
-            <xsl:call-template name="FindComponentInImportedSchemas">
-               <xsl:with-param name="name" select="$refName"/>
-               <xsl:with-param name="compType" select="$compType"/>
-               <xsl:with-param name="compNS" select="$refNS"/>
-               <xsl:with-param name="schema" select="/xsd:schema"/>
-               <xsl:with-param name="index">1</xsl:with-param>
-            </xsl:call-template>
-         </xsl:when>
-      </xsl:choose>
-   </xsl:template>
-
-   <xsl:template name="FindComponentInSchema">
-      <xsl:param name="name"/>
-      <xsl:param name="compType"/>
-      <xsl:param name="schema"/>
-      <xsl:param name="schemaFileLoc"/>
-      <xsl:param name="schemasSearched"/>
-
-      <!-- Don't examine this schema if we've already
-           searched it. Prevents infinite recursion.
-           Also check if schema actually exists. -->
-      <xsl:if test="$schema and not(contains($schemasSearched, concat('*', $schemaFileLoc, '+')))">
-         <!-- Find out if the component is in this schema -->
-         <xsl:variable name="thisResult">
-            <xsl:call-template name="IsComponentInSchema">
-               <xsl:with-param name="name" select="$name"/>
-               <xsl:with-param name="compType" select="$compType"/>
-               <xsl:with-param name="schema" select="$schema"/>
-            </xsl:call-template>
-         </xsl:variable>
-
-         <xsl:choose>
-            <!-- Component found -->
-            <xsl:when test="normalize-space($thisResult)='true'">
-               <xsl:value-of select="$schemaFileLoc"/>
-            </xsl:when>
-            <!-- Component not found -->
-            <xsl:when test="normalize-space(translate($searchIncludedSchemas, 'TRUE', 'true'))='true'">
-               <!-- Search included schemas -->
-               <xsl:variable name="includeResult">
-                  <xsl:call-template name="FindComponentInIncludedSchemas">
-                     <xsl:with-param name="schema" select="$schema"/>
-                     <xsl:with-param name="name" select="$name"/>
-                     <xsl:with-param name="compType" select="$compType"/>
-                     <xsl:with-param name="index">1</xsl:with-param>
-                     <xsl:with-param name="schemasSearched" select="concat($schemasSearched, '*', $schemaFileLoc, '+')"/>
-                  </xsl:call-template>
-               </xsl:variable>
-
-               <xsl:choose>
-                  <xsl:when test="normalize-space($includeResult)!='' and normalize-space($includeResult)!='none'">
-                     <xsl:value-of select="$includeResult"/>
-                  </xsl:when>
-                  <xsl:otherwise>
-                     <!-- Search redefined schemas -->
-                     <xsl:call-template name="FindComponentInRedefinedSchemas">
-                        <xsl:with-param name="schema" select="$schema"/>
-                        <xsl:with-param name="name" select="$name"/>
-                        <xsl:with-param name="compType" select="$compType"/>
-                        <xsl:with-param name="index">1</xsl:with-param>
-                        <xsl:with-param name="schemasSearched" select="concat($schemasSearched, '*', $schemaFileLoc, '+')"/>
-                     </xsl:call-template>
-                  </xsl:otherwise>
-               </xsl:choose>
-            </xsl:when>
-         </xsl:choose>
-      </xsl:if>
-   </xsl:template>
-
-   <xsl:template name="IsComponentInSchema">
-      <xsl:param name="name"/>
-      <xsl:param name="compType"/>
-      <xsl:param name="schema"/>
-
-      <xsl:choose>
-         <!-- Schema not found. -->
-         <xsl:when test="not($schema)">
-            <xsl:text>false</xsl:text>
-         </xsl:when>
-         <!-- Search for attribute declaration. -->
-         <xsl:when test="$compType='attribute' and $schema/xsd:attribute[@name=$name]">
-            <xsl:text>true</xsl:text>
-         </xsl:when>
-         <!-- Search for attribute group definition. -->
-         <xsl:when test="$compType='attribute group' and ($schema/xsd:attributeGroup[@name=$name] or $schema/xsd:redefine/xsd:attributeGroup[@name=$name])">
-            <xsl:text>true</xsl:text>
-         </xsl:when>
-         <!-- Search for element declaration. -->
-         <xsl:when test="$compType='element' and $schema/xsd:element[@name=$name]">
-            <xsl:text>true</xsl:text>
-         </xsl:when>
-         <!-- Search for group definition. -->
-         <xsl:when test="$compType='group' and ($schema/xsd:group[@name=$name] or $schema/xsd:redefine/xsd:group[@name=$name])">
-            <xsl:text>true</xsl:text>
-         </xsl:when>
-         <!-- Search for complex type definition. -->
-         <xsl:when test="($compType='type' or $compType='complex type') and ($schema/xsd:complexType[@name=$name] or $schema/xsd:redefine/xsd:complexType[@name=$name])">
-            <xsl:text>true</xsl:text>
-         </xsl:when>
-         <!-- Search for simple type definition. -->
-         <xsl:when test="($compType='type' or $compType='simple type') and ($schema/xsd:simpleType[@name=$name] or $schema/xsd:redefine/xsd:simpleType[@name=$name])">
-            <xsl:text>true</xsl:text>
-         </xsl:when>
-         <!-- Search for uniqueness/key constraint definition. -->
-         <xsl:when test="$compType='uniqueness/key constraint' and ($schema//xsd:element/xsd:key[@name=$name] or $schema//xsd:element/xsd:unique[@name=$name])">
-            <xsl:text>true</xsl:text>
-         </xsl:when>
-         <!-- Component not found. -->
-         <xsl:otherwise>
-            <xsl:text>false</xsl:text>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-   <xsl:template name="FindComponentInIncludedSchemas">
-      <xsl:param name="schema"/>
-      <xsl:param name="name"/>
-      <xsl:param name="compType"/>
-      <xsl:param name="schemasSearched"/>
-      <xsl:param name="index">1</xsl:param>
-
-      <xsl:if test="count($schema/xsd:include) &gt;= number($index)">
-         <!-- Get the 'schemaLocation' attribute of the 'include'
-              element in this schema at position, 'index'. -->
-         <xsl:variable name="schemaLoc" select="$schema/xsd:include[position()=$index]/@schemaLocation"/>
-
-         <xsl:variable name="thisResult">
-            <!-- Search for the component in the current 
-                 included schema. -->
-            <xsl:call-template name="FindComponentInSchema">
-               <xsl:with-param name="name" select="$name"/>
-               <xsl:with-param name="compType" select="$compType"/>
-               <xsl:with-param name="schema" select="document($schemaLoc)/xsd:schema"/>
-               <xsl:with-param name="schemaFileLoc" select="$schemaLoc"/>
-               <xsl:with-param name="schemasSearched" select="$schemasSearched"/>
-            </xsl:call-template>
-         </xsl:variable>
-
-         <xsl:choose>
-            <!-- Component was found, so return result. -->
-            <xsl:when test="normalize-space($thisResult)!='' and normalize-space($thisResult)!='none'">
-               <xsl:value-of select="$thisResult"/>
-            </xsl:when>
-            <!-- Component was not found, so keep on searching. -->
-            <xsl:otherwise>
-               <!-- Examine other included schemas in this schema -->
-               <xsl:call-template name="FindComponentInIncludedSchemas">
-                  <xsl:with-param name="schema" select="$schema"/>
-                  <xsl:with-param name="name" select="$name"/>
-                  <xsl:with-param name="compType" select="$compType"/>
-                  <xsl:with-param name="index" select="number($index)+1"/>
-                  <xsl:with-param name="schemasSearched" select="concat($schemasSearched, '*', $schemaLoc, '+')"/>
-               </xsl:call-template>
-            </xsl:otherwise>
-         </xsl:choose>
-      </xsl:if>
-   </xsl:template>
-
-   <xsl:template name="FindComponentInRedefinedSchemas">
-      <xsl:param name="schema"/>
-      <xsl:param name="name"/>
-      <xsl:param name="compType"/>
-      <xsl:param name="schemasSearched"/>
-      <xsl:param name="index">1</xsl:param>
-
-      <xsl:if test="count($schema/xsd:redefine) &gt;= number($index)">
-         <!-- Get the 'schemaLocation' attribute of the 'redefine'
-              element in this schema at position, 'index'. -->
-         <xsl:variable name="schemaLoc" select="$schema/xsd:redefine[position()=$index]/@schemaLocation"/>
-
-         <xsl:variable name="thisResult">
-            <!-- Search for the component in the current 
-                 redefined schema. -->
-            <xsl:call-template name="FindComponentInSchema">
-               <xsl:with-param name="name" select="$name"/>
-               <xsl:with-param name="compType" select="$compType"/>
-               <xsl:with-param name="schema" select="document($schemaLoc)/xsd:schema"/>
-               <xsl:with-param name="schemaFileLoc" select="$schemaLoc"/>
-               <xsl:with-param name="schemasSearched" select="$schemasSearched"/>
-            </xsl:call-template>
-         </xsl:variable>
-
-         <xsl:choose>
-            <!-- Component was found, so return result. -->
-            <xsl:when test="normalize-space($thisResult)!='' and normalize-space($thisResult)!='none'">
-               <xsl:value-of select="$thisResult"/>
-            </xsl:when>
-            <!-- Component was not found, so keep on searching. -->
-            <xsl:otherwise>
-               <!-- Examine other redefined schemas in this schema -->
-               <xsl:call-template name="FindComponentInRedefinedSchemas">
-                  <xsl:with-param name="schema" select="$schema"/>
-                  <xsl:with-param name="name" select="$name"/>
-                  <xsl:with-param name="compType" select="$compType"/>
-                  <xsl:with-param name="index" select="number($index)+1"/>
-                  <xsl:with-param name="schemasSearched" select="concat($schemasSearched, '*', $schemaLoc, '+')"/>
-               </xsl:call-template>
-            </xsl:otherwise>
-         </xsl:choose>
-      </xsl:if>
-   </xsl:template>
-
-   <xsl:template name="FindComponentInImportedSchemas">
-      <xsl:param name="schema"/>
-      <xsl:param name="name"/>
-      <xsl:param name="compType"/>
-      <xsl:param name="compNS"/>
-      <xsl:param name="schemasSearched"/>
-      <xsl:param name="index">1</xsl:param>
-
-      <xsl:if test="count($schema/xsd:import) &gt;= number($index)">
-         <!-- Get the 'namespace' attribute of the 'import'
-              element in this schema at position, 'index'. -->
-         <xsl:variable name="schemaNS" select="$schema/xsd:import[position()=$index]/@namespace"/>
-         <!-- Get the 'schemaLocation' attribute. -->
-         <xsl:variable name="schemaLoc" select="$schema/xsd:import[position()=$index]/@schemaLocation"/>
-
-         <xsl:variable name="thisResult">
-            <!-- Check that the imported schema has the matching
-                 namespace as the component that we're looking
-                 for. -->
-            <xsl:if test="normalize-space($compNS)=normalize-space($schemaNS)">
-               <!-- Search for the component in the current 
-                    imported schema. -->
-               <xsl:call-template name="FindComponentInSchema">
-                  <xsl:with-param name="name" select="$name"/>
-                  <xsl:with-param name="compType" select="$compType"/>
-                  <xsl:with-param name="schema" select="document($schemaLoc)/xsd:schema"/>
-                  <xsl:with-param name="schemaFileLoc" select="$schemaLoc"/>
-                  <xsl:with-param name="schemasSearched" select="$schemasSearched"/>
-               </xsl:call-template>
-            </xsl:if>
-         </xsl:variable>
-
-         <xsl:choose>
-            <!-- Component was found, so return result. -->
-            <xsl:when test="normalize-space($thisResult)!='' and normalize-space($thisResult)!='none'">
-               <xsl:value-of select="$thisResult"/>
-            </xsl:when>
-            <!-- Component was not found, so keep on searching. -->
-            <xsl:otherwise>
-               <!-- Examine other included schemas in this schema -->
-               <xsl:call-template name="FindComponentInImportedSchemas">
-                  <xsl:with-param name="schema" select="$schema"/>
-                  <xsl:with-param name="name" select="$name"/>
-                  <xsl:with-param name="compType" select="$compType"/>
-                  <xsl:with-param name="compNS" select="$compNS"/>
-                  <xsl:with-param name="index" select="number($index)+1"/>
-                  <xsl:with-param name="schemasSearched" select="concat($schemasSearched, '*', $schemaLoc, '+')"/>
-               </xsl:call-template>
-            </xsl:otherwise>
-         </xsl:choose>
-      </xsl:if>
-   </xsl:template>
-
-
-   <!-- ******** General Utility Templates ******** -->
-
-   <!-- 
-     Creates a box that can be opened and closed, such
-     that the contents can be hidden away until a button
-     is pressed.
-     Param(s):
-            id (String) required
-              Unique ID of the 'div' box
-            caption (String) required
-              Text describing the contents of the box;
-              it will always be shown even when the box
-              is closed
-            contents (String) required
-              Contents of box, which may appear and disappear
-              with the press of a button.
-            anchor (String) optional
-              Anchor, e.g. <a name="...", for this box
-            styleClass (String) optional
-              Additional CSS class for the entire collapseable box
-            isOpened (String) optional
-              Set to true if initially opened, and
-              false if initially closed
-     -->
-   <xsl:template name="CollapseableBox">
-      <xsl:param name="id"/>
-      <xsl:param name="caption"/>
-      <xsl:param name="contents"/>
-      <xsl:param name="anchor"/>
-      <xsl:param name="styleClass"/>
-      <xsl:param name="isOpened">false</xsl:param>
-
-      <xsl:variable name="buttonID" select="concat($id, '_button')"/>
-
-      <div class="{$styleClass} box">
-         <div>
-            <!-- Button to control the opening and closing of the 'div' box -->
-            <xsl:if test="normalize-space(translate($useJavaScript,'TRUE','true'))='true'">
-               <input type="button" id="{$buttonID}" class="control" onclick="switchState('{$id}'); return false;" style="display: none"/>
-               <!--
-                 Button's 'display' property is set to 'none', 
-                 so that button will only be displayed if
-                 box can be successfully opened and closed.
-                 -->
-            </xsl:if>
-            <!-- Box Title -->
-            <xsl:text> </xsl:text>
-            <span class="caption">
-               <xsl:choose>
-                  <xsl:when test="$anchor != ''">
-                     <a name="{$anchor}">
-                        <xsl:value-of select="$caption"/>
-                     </a>
-                  </xsl:when>
-                  <xsl:otherwise>
-                     <xsl:value-of select="$caption"/>
-                  </xsl:otherwise>
-               </xsl:choose>
-            </span>
-         </div>
-
-         <!-- Box Contents -->
-         <div id="{$id}" class="contents">
-            <xsl:copy-of select="$contents"/>
-         </div>
-         <xsl:if test="normalize-space(translate($useJavaScript,'TRUE','true'))='true'">
-            <xsl:call-template name="PrintJSCode">
-               <xsl:with-param name="code">setState('<xsl:value-of select="$id"/>', <xsl:value-of select="$isOpened"/>);</xsl:with-param>
-            </xsl:call-template>
-         </xsl:if>
-      </div>
-   </xsl:template>
-
-   <!--
-     Returns the namespace of an attribute
-     declaration or reference.
-     Param(s):
-            attribute (Node) required
-                Attribute declaration or reference
-     -->
-   <xsl:template name="GetAttributeNS">
-      <xsl:param name="attribute"/>
-
-      <xsl:choose>
-         <!-- Qualified local attribute declaration -->
-         <xsl:when test="$attribute[@name] and (normalize-space(translate($attribute/@form, 'QUALIFED', 'qualifed'))='qualified' or normalize-space(translate(/xsd:schema/@attributeFormDefault, 'QUALIFED', 'qualifed'))='qualified')">
-            <xsl:value-of select="/xsd:schema/@targetNamespace"/>
-         </xsl:when>
-         <!-- Reference to global attribute declaration -->
-         <xsl:when test="$attribute[@ref]">
-            <xsl:call-template name="GetRefNS">
-               <xsl:with-param name="ref" select="$attribute/@ref"/>
-            </xsl:call-template>
-         </xsl:when>
-         <!-- Otherwise, attribute has no namespace -->
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Returns the description that can be used in 
-     headers for a schema component.
-     Param(s):
-            component (Node) required
-                Schema component
-     -->
-   <xsl:template name="GetComponentDescription">
-      <xsl:param name="component"/>
-
-      <xsl:choose>
-         <xsl:when test="local-name($component)='all'">
-            <xsl:text>All Model Group</xsl:text>
-         </xsl:when>
-         <xsl:when test="local-name($component)='attribute'">
-            <xsl:text>Attribute</xsl:text>
-         </xsl:when>
-         <xsl:when test="local-name($component)='attributeGroup'">
-            <xsl:text>Attribute Group</xsl:text>
-         </xsl:when>
-         <xsl:when test="local-name($component)='choice'">
-            <xsl:text>Choice Model Group</xsl:text>
-         </xsl:when>
-         <xsl:when test="local-name($component)='complexType'">
-            <xsl:text>Complex Type</xsl:text>
-         </xsl:when>
-         <xsl:when test="local-name($component)='element'">
-            <xsl:text>Element</xsl:text>
-         </xsl:when>
-         <xsl:when test="local-name($component)='group'">
-            <xsl:text>Model Group</xsl:text>
-         </xsl:when>
-         <xsl:when test="local-name($component)='notation'">
-            <xsl:text>Notation</xsl:text>
-         </xsl:when>
-         <xsl:when test="local-name($component)='sequence'">
-            <xsl:text>Sequence Model Group</xsl:text>
-         </xsl:when>
-         <xsl:when test="local-name($component)='simpleType'">
-            <xsl:text>Simple Type</xsl:text>
-         </xsl:when>
-         <xsl:otherwise>
-            <xsl:call-template name="HandleError">
-               <xsl:with-param name="isTerminating">true</xsl:with-param>
-               <xsl:with-param name="errorMsg">
-Unknown schema component, <xsl:value-of select="local-name($component)"/>.
-               </xsl:with-param>
-            </xsl:call-template>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Returns the unique identifier for a top-level schema
-     component. Returns the string "schema" if the 'component' 
-     is the root schema element.
-     Param(s):
-            component (Node) required
-                Schema component
-     -->
-   <xsl:template name="GetComponentID">
-      <xsl:param name="component"/>
-
-      <xsl:choose>
-         <xsl:when test="local-name($component)='schema'">
-            <xsl:text>schema</xsl:text>
-         </xsl:when>
-         <xsl:otherwise>
-            <xsl:variable name="componentPrefix">
-               <xsl:call-template name="GetComponentPrefix">
-                  <xsl:with-param name="component" select="$component"/>
-               </xsl:call-template>
-            </xsl:variable>
-            <xsl:value-of select="concat($componentPrefix, $component/@name)"/>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Returns the prefix to add in front of a schema component
-     name when generating anchor names.
-     Param(s):
-            component (Node) required
-                Schema component
-     -->
-   <xsl:template name="GetComponentPrefix">
-      <xsl:param name="component"/>
-
-      <xsl:choose>
-         <xsl:when test="local-name($component)='attribute'">
-            <xsl:value-of select="$ATTR_PREFIX"/>
-         </xsl:when>
-         <xsl:when test="local-name($component)='attributeGroup'">
-            <xsl:value-of select="$ATTR_GRP_PREFIX"/>
-         </xsl:when>
-         <xsl:when test="local-name($component)='complexType'">
-            <xsl:value-of select="$CTYPE_PREFIX"/>
-         </xsl:when>
-         <xsl:when test="local-name($component)='element'">
-            <xsl:value-of select="$ELEM_PREFIX"/>
-         </xsl:when>
-         <xsl:when test="local-name($component)='group'">
-            <xsl:value-of select="$GRP_PREFIX"/>
-         </xsl:when>
-         <xsl:when test="local-name($component)='notation'">
-            <xsl:value-of select="$NOTA_PREFIX"/>
-         </xsl:when>
-         <xsl:when test="local-name($component)='simpleType'">
-            <xsl:value-of select="$STYPE_PREFIX"/>
-         </xsl:when>
-         <xsl:when test="local-name($component)='key' or local-name($component)='unique'">
-            <xsl:value-of select="$KEY_PREFIX"/>
-         </xsl:when>
-         <xsl:otherwise>
-            <xsl:call-template name="HandleError">
-               <xsl:with-param name="isTerminating">true</xsl:with-param>
-               <xsl:with-param name="errorMsg">
-Unknown schema component, <xsl:value-of select="local-name($component)"/>.
-               </xsl:with-param>
-            </xsl:call-template>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Returns a glossary term reference for the 
-     schema component type, if applicable.
-     Param(s):
-            component (Node) required
-                Schema component
-     -->
-   <xsl:template name="GetComponentTermRef">
-      <xsl:param name="component"/>
-
-      <xsl:choose>
-         <xsl:when test="local-name($component)='notation'">
-            <xsl:text>Notation</xsl:text>
-         </xsl:when>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Returns the namespace prefix of an attribute.
-     Param(s):
-            attribute (Node) required
-                Attribute declaration or reference
-     -->
-   <xsl:template name="GetAttributePrefix">
-      <xsl:param name="attribute"/>
-
-      <xsl:choose>
-         <!-- Element reference -->
-         <xsl:when test="$attribute/@ref">
-            <xsl:call-template name="GetRefPrefix">
-               <xsl:with-param name="ref" select="$attribute/@ref"/>
-            </xsl:call-template>
-         </xsl:when>
-         <!-- Global element declaration -->
-         <xsl:when test="local-name($attribute/..)='schema'">
-            <xsl:call-template name="GetThisPrefix"/>
-         </xsl:when>
-         <!-- Local element declaration -->
-         <xsl:otherwise>
-            <xsl:if test="($attribute/@form and normalize-space($attribute/@form)='qualified') or (/xsd:schema/@attributeFormDefault and normalize-space(/xsd:schema/@attributeFormDefault)='qualified')">
-               <xsl:call-template name="GetThisPrefix"/>
-            </xsl:if>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Returns the namespace prefix of an element.
-     Param(s):
-            element (Node) required
-                Element declaration or reference
-     -->
-   <xsl:template name="GetElementPrefix">
-      <xsl:param name="element"/>
-
-      <xsl:choose>
-         <!-- Element reference -->
-         <xsl:when test="$element/@ref">
-            <xsl:call-template name="GetRefPrefix">
-               <xsl:with-param name="ref" select="$element/@ref"/>
-            </xsl:call-template>
-         </xsl:when>
-         <!-- Global element declaration -->
-         <xsl:when test="local-name($element/..)='schema'">
-            <xsl:call-template name="GetThisPrefix"/>
-         </xsl:when>
-         <!-- Local element declaration -->
-         <xsl:otherwise>
-            <xsl:if test="($element/@form and normalize-space($element/@form)='qualified') or (/xsd:schema/@elementFormDefault and normalize-space(/xsd:schema/@elementFormDefault)='qualified')">
-               <xsl:call-template name="GetThisPrefix"/>
-            </xsl:if>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Returns the local name of a reference.
-     Param(s):
-            ref (String) required
-                Reference
-     -->
-   <xsl:template name="GetRefName">
-      <xsl:param name="ref"/>
-
-      <xsl:choose>
-         <xsl:when test="contains($ref, ':')">
-            <!-- Ref has namespace prefix -->
-            <xsl:value-of select="substring-after($ref, ':')"/>
-         </xsl:when>
-         <xsl:otherwise>
-            <!-- Ref has no namespace prefix -->
-            <xsl:value-of select="$ref"/>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Returns the namespace prefix of a reference.
-     Param(s):
-            ref (String) required
-                Reference
-     -->
-   <xsl:template name="GetRefPrefix">
-      <xsl:param name="ref"/>
-      <!-- Get namespace prefix -->
-      <xsl:value-of select="substring-before($ref, ':')"/>
-   </xsl:template>
-
-   <!--
-     Returns the namespace of a reference.
-     Param(s):
-            ref (String) required
-                Reference
-     -->
-   <xsl:template name="GetRefNS">
-      <xsl:param name="ref"/>
-      <!-- Get namespace prefix -->
-      <xsl:variable name="refPrefix" select="substring-before($ref, ':')"/>
-      <!-- Get namespace -->
-      <xsl:value-of select="/xsd:schema/namespace::*[local-name(.)=normalize-space($refPrefix)]"/>
-   </xsl:template>
-
-   <!--
-     Returns the declared prefix of this schema's target namespace.
-     -->
-   <xsl:template name="GetThisPrefix">
-      <xsl:if test="/xsd:schema/@targetNamespace">
-         <xsl:value-of select="local-name(/xsd:schema/namespace::*[normalize-space(.)=normalize-space(/xsd:schema/@targetNamespace)])"/>
-      </xsl:if>
-   </xsl:template>
-
-   <!--
-     Returns the declared prefix of XML Schema namespace.
-     -->
-   <xsl:template name="GetXSDPrefix">
-      <xsl:value-of select="local-name(/xsd:schema/namespace::*[normalize-space(.)=$XSD_NS])"/>
-   </xsl:template>
-
-   <!--
-     Returns the schema documentation file location for a
-     given URI for a schema, done by looking up the file
-     specified in 'linksFile' variable.
-     It'll throw a fatal error if a value for 'linksFile' was 
-     provided and the documentation file for 'uri' could not be
-     found.
-     Param(s):
-            uri (String) required
-              Location of schema file
-     -->
-   <xsl:template name="GetSchemaDocLocation">
-      <xsl:param name="uri"/>
-
-      <xsl:if test="$linksFile!=''">
-         <xsl:variable name="schemaDocFile" select="document($linksFile)/ppp:links/ppp:schema[@file-location=$uri]/@docfile-location"/>
-         <xsl:if test="$schemaDocFile=''">
-            <xsl:call-template name="HandleError">
-               <xsl:with-param name="isTerminating">true</xsl:with-param>
-               <xsl:with-param name="errorMsg">
-Documentation file for the schema at, <xsl:value-of select="$uri"/>,
-was not specified in the links file, <xsl:value-of select="$linksFile"/>.
-               </xsl:with-param>
-            </xsl:call-template>
-         </xsl:if>
-         <xsl:value-of select="$schemaDocFile"/>
-      </xsl:if>
-   </xsl:template>
-
-   <!--
-     Prints out a boolean value.
-     Param(s):
-            boolean (String) required
-                Boolean value
-     -->
-   <xsl:template name="PrintBoolean">
-      <xsl:param name="boolean"/>
-
-      <xsl:choose>
-         <xsl:when test="normalize-space(translate($boolean,'TRUE', 'true'))='true' or normalize-space($boolean)='1'">
-            <xsl:text>yes</xsl:text>
-         </xsl:when>
-         <xsl:otherwise>
-            <xsl:text>no</xsl:text>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Prints out a link to the namespace of a prefix,
-     and tacks on a colon in the end.
-     Param(s):
-            prefix (String) required
-                Namespace prefix
-            nolink (boolean) optional
-                If true, doesn't provide a link to the
-                namespace in the namespaces table.
-            schemaLoc (String) optional
-                Schema file containing this namespace prefix;
-                if in current schema, 'schemaLoc' is set to 'this'
-     -->
-   <xsl:template name="PrintNSPrefix">
-      <xsl:param name="prefix"/>
-      <xsl:param name="nolink">false</xsl:param>
-      <xsl:param name="schemaLoc">this</xsl:param>
-
-      <xsl:if test="$prefix!='' and normalize-space(translate($printNSPrefixes,'TRUE','true'))='true'">
-         <xsl:choose>
-            <xsl:when test="$nolink='false'">
-               <xsl:call-template name="PrintNamespaceRef">
-                  <xsl:with-param name="prefix" select="$prefix"/>
-                  <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-               </xsl:call-template>
-            </xsl:when>
-            <xsl:otherwise>
-               <xsl:value-of select="$prefix"/>
-            </xsl:otherwise>
-         </xsl:choose>
-         <xsl:text>:</xsl:text>
-      </xsl:if>
-   </xsl:template>
-
-   <!--
-     Prints out the min/max occurrences of a schema component.
-     Param(s):
-            component (Node) optional
-                Schema component
-            minOccurs (String) optional
-                Minimum occurrences
-            maxOccurs (String) optional
-                Maximum occurrences
-     -->
-   <xsl:template name="PrintOccurs">
-      <xsl:param name="component"/>
-      <xsl:param name="minOccurs"/>
-      <xsl:param name="maxOccurs"/>
-
-      <!-- Get min occurs -->
-      <xsl:variable name="min">
-         <xsl:choose>
-            <xsl:when test="$component and local-name($component)='attribute'">
-               <xsl:choose>
-                  <xsl:when test="normalize-space($component/@use)='required'">
-                     <xsl:text>1</xsl:text>
-                  </xsl:when>
-                  <xsl:otherwise>
-                     <xsl:text>0</xsl:text>
-                  </xsl:otherwise>
-               </xsl:choose>
-            </xsl:when>
-            <xsl:otherwise>
-               <xsl:choose>
-                  <xsl:when test="$component and $component/@minOccurs">
-                     <xsl:value-of select="$component/@minOccurs"/>
-                  </xsl:when>
-                  <xsl:when test="$minOccurs != ''">
-                     <xsl:value-of select="$minOccurs"/>
-                  </xsl:when>
-                  <xsl:otherwise>
-                     <xsl:text>1</xsl:text>
-                  </xsl:otherwise>
-               </xsl:choose>
-            </xsl:otherwise>
-         </xsl:choose>
-      </xsl:variable>
-      <!-- Get max occurs -->
-      <xsl:variable name="max">
-         <xsl:choose>
-            <xsl:when test="$component and local-name($component)='attribute'">
-               <xsl:choose>
-                  <xsl:when test="normalize-space($component/@use)='prohibited'">
-                     <xsl:text>0</xsl:text>
-                  </xsl:when>
-                  <xsl:otherwise>
-                     <xsl:text>1</xsl:text>
-                  </xsl:otherwise>
-               </xsl:choose>
-            </xsl:when>
-            <xsl:otherwise>
-               <xsl:choose>
-                  <xsl:when test="($component and normalize-space($component/@maxOccurs)='unbounded') or $maxOccurs='unbounded'">
-                     <xsl:text>*</xsl:text>
-                  </xsl:when>
-                  <xsl:when test="$component and $component/@maxOccurs">
-                     <xsl:value-of select="$component/@maxOccurs"/>
-                  </xsl:when>
-                  <xsl:when test="$maxOccurs != ''">
-                     <xsl:value-of select="$maxOccurs"/>
-                  </xsl:when>
-                  <xsl:otherwise>
-                     <xsl:text>1</xsl:text>
-                  </xsl:otherwise>
-               </xsl:choose>
-            </xsl:otherwise>
-         </xsl:choose>
-      </xsl:variable>
-
-      <span class="occurs">
-         <xsl:choose>
-            <xsl:when test="number($min)=1 and number($max)=1">
-               <xsl:text>[1]</xsl:text>
-            </xsl:when>
-            <xsl:otherwise>
-               <xsl:text>[</xsl:text>
-               <xsl:value-of select="$min"/>
-               <xsl:text>..</xsl:text>
-               <xsl:value-of select="$max"/>
-               <xsl:text>]</xsl:text>
-            </xsl:otherwise>
-         </xsl:choose>
-      </span>
-   </xsl:template>
-
-   <!--
-     Translates occurrence of '#all' in 'block' value
-     of element declarations.
-     Param(s):
-            EBV (String) required
-                Value
-     -->
-   <xsl:template name="PrintBlockSet">
-      <xsl:param name="EBV"/>
-
-      <xsl:choose>
-         <xsl:when test="normalize-space($EBV)='#all'">
-            <xsl:text>restriction, extension, substitution</xsl:text>
-         </xsl:when>
-         <xsl:otherwise>
-            <xsl:value-of select="$EBV"/>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Translates occurrence of '#all' in 'final' value
-     of element declarations, and 'block' and 'final' values 
-     in complex type definitions.
-     Param(s):
-            EBV (String) required
-                Value
-     -->
-   <xsl:template name="PrintDerivationSet">
-      <xsl:param name="EBV"/>
-
-      <xsl:choose>
-         <xsl:when test="normalize-space($EBV)='#all'">
-            <xsl:text>restriction, extension</xsl:text>
-         </xsl:when>
-         <xsl:otherwise>
-            <xsl:value-of select="$EBV"/>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Translates occurrence of '#all' in 'final' value
-     of simple type definitions.
-     Param(s):
-            EBV (String) required
-                Value
-     -->
-   <xsl:template name="PrintSimpleDerivationSet">
-      <xsl:param name="EBV"/>
-
-      <xsl:choose>
-         <xsl:when test="normalize-space($EBV)='#all'">
-            <xsl:text>restriction, list, union</xsl:text>
-         </xsl:when>
-         <xsl:when test="normalize-space($EBV)!=''">
-            <xsl:value-of select="$EBV"/>
-         </xsl:when>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Print out a URI. If it starts with 'http', a link is provided.
-     Param(s):
-            uri (String) required
-              URI to be printed
-     -->
-   <xsl:template name="PrintURI">
-      <xsl:param name="uri"/>
-
-      <xsl:choose>
-         <xsl:when test="starts-with($uri, 'http')">
-            <a title="{$uri}" href="{$uri}">
-               <xsl:value-of select="$uri"/>
-            </a>
-         </xsl:when>
-         <xsl:otherwise>
-            <xsl:value-of select="$uri"/>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Print out a link to the documentation of schema document.
-     For this happen, the 'linksFile' variable must be provided,
-     it must point to an actual file, and in that file, there
-     must be a mapping from the schema file location to the
-     schema documentation file location.
-     Param(s):
-            uri (String) required
-              Location of schema file
-     -->
-   <xsl:template name="PrintSchemaLink">
-      <xsl:param name="uri"/>
-
-      <xsl:variable name="docFileLoc">
-         <xsl:call-template name="GetSchemaDocLocation">
-            <xsl:with-param name="uri" select="$uri"/>
-         </xsl:call-template>
-      </xsl:variable>
-
-      <xsl:choose>
-         <xsl:when test="$docFileLoc!=''">
-            <a title="Jump to schema documentation for '{$uri}'." href="{$docFileLoc}">
-               <xsl:value-of select="$uri"/>
-            </a>
-         </xsl:when>
-         <xsl:otherwise>
-            <xsl:value-of select="$uri"/>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Tokenises a whitespace-separated list of values, and
-     displays them appropriately.
-     Param(s):
-            value (String) required
-              Whitespace-separated list
-            compType (String) optional
-              Specify schema component type if values in list are
-              schema components, so appropriate links can be provided.
-            isInList (boolean) optional
-              If true, place each value within 'li' tags.
-              Assumes that this template is called within an HTML
-              list element.
-            separator (String) optional
-              Character(s) to use to separate resulting values in list.
-              Only used if 'isInList' is false.
-              If none is provided, uses a space character, ' '.
-            isFirst (boolean) optional
-              If false, it's a recursive call from 'PrintWhitespaceList'.
-            schemaLoc (String) optional
-                Schema file containing this all model group;
-                if in current schema, 'schemaLoc' is set to 'this'
-     -->
-   <xsl:template name="PrintWhitespaceList">
-      <xsl:param name="value"/>
-      <xsl:param name="compType"/>
-      <xsl:param name="isInList">false</xsl:param>
-      <xsl:param name="separator"/>
-      <xsl:param name="isFirst">true</xsl:param>
-      <xsl:param name="schemaLoc">this</xsl:param>
-
-      <xsl:variable name="token" select="normalize-space(substring-before($value, ' '))"/>
-      <xsl:choose>
-         <xsl:when test="$token!=''">
-            <!-- Whitespace found in value -->
-            <!-- Print out token -->
-            <xsl:call-template name="PrintWhitespaceListToken">
-               <xsl:with-param name="token" select="$token"/>
-               <xsl:with-param name="compType" select="$compType"/>
-               <xsl:with-param name="isInList" select="$isInList"/>
-               <xsl:with-param name="separator" select="$separator"/>
-               <xsl:with-param name="isFirst" select="$isFirst"/>
-               <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-            </xsl:call-template>
-            <!-- Continue parsing -->
-            <xsl:variable name="rest" select="normalize-space(substring-after($value, $token))"/>
-            <xsl:if test="$rest!=''">
-               <xsl:call-template name="PrintWhitespaceList">
-                  <xsl:with-param name="value" select="$rest"/>
-                  <xsl:with-param name="compType" select="$compType"/>
-                  <xsl:with-param name="isInList" select="$isInList"/>
-                  <xsl:with-param name="separator" select="$separator"/>
-                  <xsl:with-param name="isFirst">false</xsl:with-param>
-                  <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-               </xsl:call-template>
-            </xsl:if>
-         </xsl:when>
-         <xsl:otherwise>
-            <!-- No more whitespaces  -->
-            <!-- Print out one last token -->
-            <xsl:if test="normalize-space($value)!=''">
-               <xsl:call-template name="PrintWhitespaceListToken">
-                  <xsl:with-param name="token" select="$value"/>
-                  <xsl:with-param name="compType" select="$compType"/>
-                  <xsl:with-param name="isInList" select="$isInList"/>
-                  <xsl:with-param name="separator" select="$separator"/>
-                  <xsl:with-param name="isFirst" select="$isFirst"/>
-                  <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-               </xsl:call-template>
-            </xsl:if>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Helper template for 'PrintWhitespaceList' template,
-     which prints out one token in the list.
-     Param(s):
-            token (String) required
-              Token to be printed
-            compType (String) optional
-              Schema component type of token, if applicable.
-            isInList (boolean) optional
-              If true, place token within 'li' tags.
-            separator (String) optional
-              Character(s) use to separate one token from another.
-              Only used if 'isInList' is false.
-              If none is provided, uses a space character, ' '.
-            isFirst (boolean) optional
-              If true, token is the first value in the list.
-            schemaLoc (String) optional
-                Schema file containing this all model group;
-                if in current schema, 'schemaLoc' is set to 'this'
-     -->
-   <xsl:template name="PrintWhitespaceListToken">
-      <xsl:param name="token"/>
-      <xsl:param name="compType"/>
-      <xsl:param name="isInList">false</xsl:param>
-      <xsl:param name="separator"/>
-      <xsl:param name="isFirst">true</xsl:param>
-      <xsl:param name="schemaLoc">this</xsl:param>
-
-      <xsl:variable name="displayValue">
-         <xsl:choose>
-            <xsl:when test="$compType!=''">
-               <xsl:call-template name="PrintCompRef">
-                  <xsl:with-param name="ref" select="normalize-space($token)"/>
-                  <xsl:with-param name="compType" select="$compType"/>
-                  <xsl:with-param name="schemaLoc" select="$schemaLoc"/>
-               </xsl:call-template>
-            </xsl:when>
-            <xsl:otherwise>
-               <xsl:value-of select="normalize-space($token)"/>
-            </xsl:otherwise>
-         </xsl:choose>
-      </xsl:variable>
-
-      <xsl:choose>
-         <xsl:when test="$isInList!='false'">
-            <li>
-               <xsl:copy-of select="$displayValue"/>
-            </li>
-         </xsl:when>
-         <xsl:when test="$isFirst!='true'">
-            <xsl:choose>
-               <xsl:when test="$separator!=''">
-                  <xsl:value-of select="$separator"/>
-               </xsl:when>
-               <xsl:otherwise>
-                  <xsl:text> </xsl:text>
-               </xsl:otherwise>
-            </xsl:choose>
-            <xsl:copy-of select="$displayValue"/>
-         </xsl:when>
-         <xsl:otherwise>
-            <xsl:copy-of select="$displayValue"/>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Print out a wildcard.
-     Param(s):
-            componentType (attribute|element) required
-              XML Schema component type
-            namespaces (String) required
-              Namespace attribute of wildcard
-            processContents (String) required
-              Process contents attribute of wildcard
-            namespaces (String) required
-              Namespace attribute of wildcard
-     -->
-   <xsl:template name="PrintWildcard">
-      <xsl:param name="componentType">element</xsl:param>
-      <xsl:param name="namespace"/>
-      <xsl:param name="processContents"/>
-      <xsl:param name="minOccurs"/>
-      <xsl:param name="maxOccurs"/>
-
-      <xsl:text>Allow any </xsl:text>
-      <xsl:value-of select="$componentType"/>
-      <xsl:text>s from </xsl:text>
-
-      <xsl:choose>
-         <!-- ##any -->
-         <xsl:when test="not($namespace) or normalize-space($namespace)='##any'">
-            <xsl:text>any namespace</xsl:text>
-         </xsl:when>
-         <!-- ##other -->
-         <xsl:when test="normalize-space($namespace)='##other'">
-            <xsl:text>a namespace other than this schema's namespace</xsl:text>
-         </xsl:when>
-         <!-- ##targetNamespace, ##local, specific namespaces -->
-         <xsl:otherwise>
-            <!-- ##targetNamespace -->
-            <xsl:variable name="hasTargetNS">
-               <xsl:if test="contains($namespace, '##targetNamespace')">
-                  <xsl:text>true</xsl:text>
-               </xsl:if>
-            </xsl:variable>
-            <!-- ##local -->
-            <xsl:variable name="hasLocalNS">
-               <xsl:if test="contains($namespace, '##local')">
-                  <xsl:text>true</xsl:text>
-               </xsl:if>
-            </xsl:variable>
-            <!-- Specific namespaces -->
-            <!-- Remove '##targetNamespace' string if any-->
-            <xsl:variable name="temp">
-               <xsl:choose>
-                  <xsl:when test="$hasTargetNS='true'">
-                     <xsl:value-of select="concat(substring-before($namespace, '##targetNamespace'), substring-after($namespace, '##targetNamespace'))"/>
-                  </xsl:when>
-                  <xsl:otherwise>
-                     <xsl:value-of select="$namespace"/>
-                  </xsl:otherwise>
-               </xsl:choose>
-            </xsl:variable>
-            <!-- Remove '##local' string if any -->
-            <xsl:variable name="specificNS">
-               <xsl:choose>
-                  <xsl:when test="$hasLocalNS='true'">
-                     <xsl:value-of select="concat(substring-before($temp, '##local'), substring-after($temp, '##local'))"/>
-                  </xsl:when>
-                  <xsl:otherwise>
-                     <xsl:value-of select="$temp"/>
-                  </xsl:otherwise>
-               </xsl:choose>
-            </xsl:variable>
-            <xsl:variable name="hasSpecificNS">
-               <xsl:if test="normalize-space($specificNS)!=''">
-                  <xsl:text>true</xsl:text>
-               </xsl:if>
-            </xsl:variable>
-
-            <xsl:if test="$hasLocalNS='true'">
-               <xsl:text>no namespace</xsl:text>
-            </xsl:if>
-
-            <xsl:if test="$hasTargetNS='true'">
-               <xsl:choose>
-                  <xsl:when test="$hasLocalNS='true' and $hasSpecificNS!='true'">
-                     <xsl:text> and </xsl:text>
-                  </xsl:when>
-                  <xsl:when test="$hasLocalNS='true'">
-                     <xsl:text>, </xsl:text>
-                  </xsl:when>
-               </xsl:choose>
-               <xsl:text>this schema's namespace</xsl:text>
-            </xsl:if>
-
-            <xsl:if test="$hasSpecificNS='true'">
-               <xsl:choose>
-                  <xsl:when test="$hasTargetNS='true' and $hasLocalNS='true'">
-                     <xsl:text>, and </xsl:text>
-                  </xsl:when>
-                  <xsl:when test="$hasTargetNS='true' or $hasLocalNS='true'">
-                     <xsl:text> and </xsl:text>
-                  </xsl:when>
-               </xsl:choose>
-               <xsl:text>the following namespace(s): </xsl:text>
-               <xsl:call-template name="PrintWhitespaceList">
-                  <xsl:with-param name="value" select="normalize-space($specificNS)"/>
-                  <xsl:with-param name="separator">,</xsl:with-param>
-               </xsl:call-template>
-            </xsl:if>
-         </xsl:otherwise>
-      </xsl:choose>
-      <!-- Process contents -->
-      <xsl:text> (</xsl:text>
-      <xsl:choose>
-         <xsl:when test="$processContents">
-            <xsl:value-of select="normalize-space($processContents)"/>
-         </xsl:when>
-         <xsl:otherwise>
-            <xsl:text>strict</xsl:text>
-         </xsl:otherwise>
-      </xsl:choose>
-      <xsl:text> validation)</xsl:text>
-      <xsl:text>.</xsl:text>
-
-      <!-- Print min/max occurs -->
-      <xsl:if test="$componentType='element'">
-         <xsl:text> </xsl:text>
-         <xsl:call-template name="PrintOccurs">
-            <xsl:with-param name="minOccurs" select="$minOccurs"/>
-            <xsl:with-param name="maxOccurs" select="$maxOccurs"/>
-         </xsl:call-template>
-      </xsl:if>
-   </xsl:template>
-
-   <!--
-     Print out the pattern property for derivations by
-     restriction on simple content.
-     Param(s):
-            simpleRestrict (Node) required
-              'restriction' element
-     -->
-   <xsl:template name="PrintPatternFacet">
-      <xsl:param name="simpleRestrict"/>
-
-      <xsl:if test="$simpleRestrict/xsd:pattern">
-         <em>pattern</em>
-         <xsl:text> = </xsl:text>
-         <xsl:value-of select="$simpleRestrict/xsd:pattern/@value"/>
-      </xsl:if>
-   </xsl:template>
-
-   <!--
-     Print out the total digits property for derivations by
-     restriction on simple content.
-     Param(s):
-            simpleRestrict (Node) required
-              'restriction' element
-     -->
-   <xsl:template name="PrintTotalDigitsFacet">
-      <xsl:param name="simpleRestrict"/>
-
-      <xsl:if test="$simpleRestrict/xsd:totalDigits">
-         <em>total no. of digits</em>
-         <xsl:text> = </xsl:text>
-         <xsl:value-of select="$simpleRestrict/xsd:totalDigits/@value"/>
-      </xsl:if>
-   </xsl:template>
-
-   <!--
-     Print out the fraction digits property for derivations by
-     restriction on simple content.
-     Param(s):
-            simpleRestrict (Node) required
-              'restriction' element
-     -->
-   <xsl:template name="PrintFractionDigitsFacet">
-      <xsl:param name="simpleRestrict"/>
-
-      <xsl:if test="$simpleRestrict/xsd:fractionDigits">
-         <em>
-            <xsl:text>no. of fraction digits</xsl:text>
-         </em>
-         <xsl:text> = </xsl:text>
-         <xsl:value-of select="$simpleRestrict/xsd:fractionDigits/@value"/>
-      </xsl:if>
-   </xsl:template>
-
-   <!--
-     Print out the enumeration list for derivations by
-     restriction on simple content.
-     Param(s):
-            simpleRestrict (Node) required
-              'restriction' element
-     -->
-   <xsl:template name="PrintEnumFacets">
-      <xsl:param name="simpleRestrict"/>
-
-      <xsl:if test="$simpleRestrict/xsd:enumeration">
-         <em>value</em>
-         <xsl:text> comes from list: {</xsl:text>
-
-         <xsl:for-each select="$simpleRestrict/xsd:enumeration">
-            <xsl:if test="position()!=1">
-               <xsl:text>|</xsl:text>
-            </xsl:if>
-            <xsl:text>'</xsl:text>
-            <xsl:value-of select="@value"/>
-            <xsl:text>'</xsl:text>
-         </xsl:for-each>
-
-         <xsl:text>}</xsl:text>
-      </xsl:if>
-   </xsl:template>
-
-   <!--
-     Print out the length property for derivations by
-     restriction on simple content.
-     Param(s):
-            simpleRestrict (Node) required
-              'restriction' element
-     -->
-   <xsl:template name="PrintLengthFacets">
-      <xsl:param name="simpleRestrict"/>
-
-      <xsl:choose>
-         <xsl:when test="$simpleRestrict/xsd:length">
-            <em>
-               <xsl:text>length</xsl:text>
-            </em>
-            <xsl:text> = </xsl:text>
-            <xsl:value-of select="$simpleRestrict/xsd:length/@value"/>
-         </xsl:when>
-         <xsl:when test="$simpleRestrict/xsd:minLength">
-            <em>
-               <xsl:text>length</xsl:text>
-            </em>
-            <xsl:text> >= </xsl:text>
-            <xsl:value-of select="$simpleRestrict/xsd:minLength/@value"/>
-         </xsl:when>
-         <xsl:when test="$simpleRestrict/xsd:maxLength">
-            <em>
-               <xsl:text>length</xsl:text>
-            </em>
-            <xsl:text> &lt;= </xsl:text>
-            <xsl:value-of select="$simpleRestrict/xsd:maxLength/@value"/>
-         </xsl:when>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Print out the whitespace property for derivations by
-     restriction on simple content.
-     Param(s):
-            simpleRestrict (Node) required
-              'restriction' element
-     -->
-   <xsl:template name="PrintWhitespaceFacet">
-      <xsl:param name="simpleRestrict"/>
-
-      <xsl:variable name="facetValue" select="normalize-space(translate($simpleRestrict/xsd:whiteSpace/@value, 'ACELOPRSV', 'aceloprsv'))"/>
-
-      <xsl:choose>
-         <xsl:when test="$facetValue='preserve'">
-            <em>Whitespace policy: </em>
-            <xsl:call-template name="PrintGlossaryTermRef">
-               <xsl:with-param name="code">PreserveWS</xsl:with-param>
-               <xsl:with-param name="term">preserve</xsl:with-param>
-            </xsl:call-template>
-         </xsl:when>
-         <xsl:when test="$facetValue='replace'">
-            <em>Whitespace policy: </em>
-            <xsl:call-template name="PrintGlossaryTermRef">
-               <xsl:with-param name="code">ReplaceWS</xsl:with-param>
-               <xsl:with-param name="term">replace</xsl:with-param>
-            </xsl:call-template>
-         </xsl:when>
-         <xsl:when test="$facetValue='collapse'">
-            <em>Whitespace policy: </em>
-            <xsl:call-template name="PrintGlossaryTermRef">
-               <xsl:with-param name="code">CollapseWS</xsl:with-param>
-               <xsl:with-param name="term">collapse</xsl:with-param>
-            </xsl:call-template>
-         </xsl:when>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Print out the value ranges for derivations by
-     restriction on simple content.
-     Param(s):
-            simpleRestrict (Node) required
-              'restriction' element
-     -->
-   <xsl:template name="PrintRangeFacets">
-      <xsl:param name="simpleRestrict"/>
-
-      <xsl:choose>
-         <xsl:when test="($simpleRestrict/xsd:minInclusive or $simpleRestrict/xsd:minExclusive) and ($simpleRestrict/xsd:maxInclusive or $simpleRestrict/xsd:maxExclusive)">
-            <xsl:choose>
-               <xsl:when test="$simpleRestrict/xsd:minInclusive">
-                  <xsl:value-of select="$simpleRestrict/xsd:minInclusive/@value"/>
-                  <xsl:text> &lt;= </xsl:text>
-               </xsl:when>
-               <xsl:otherwise>
-                  <xsl:value-of select="$simpleRestrict/xsd:minExclusive/@value"/>
-                  <xsl:text> &lt; </xsl:text>
-               </xsl:otherwise>
-            </xsl:choose>
-            <em>
-               <xsl:text>value</xsl:text>
-            </em>
-            <xsl:choose>
-               <xsl:when test="$simpleRestrict/xsd:maxInclusive">
-                  <xsl:text> &lt;= </xsl:text>
-                  <xsl:value-of select="$simpleRestrict/xsd:maxInclusive/@value"/>
-               </xsl:when>
-               <xsl:otherwise>
-                  <xsl:text> &lt; </xsl:text>
-                  <xsl:value-of select="$simpleRestrict/xsd:maxExclusive/@value"/>
-               </xsl:otherwise>
-            </xsl:choose>
-         </xsl:when>
-         <xsl:when test="$simpleRestrict/xsd:minInclusive">
-            <em>
-               <xsl:text>value</xsl:text>
-            </em>
-            <xsl:text> >= </xsl:text>
-            <xsl:value-of select="$simpleRestrict/xsd:minInclusive/@value"/>
-         </xsl:when>
-         <xsl:when test="$simpleRestrict/xsd:minExclusive">
-            <em>
-               <xsl:text>value</xsl:text>
-            </em>
-            <xsl:text> > </xsl:text>
-            <xsl:value-of select="$simpleRestrict/xsd:minExclusive/@value"/>
-         </xsl:when>
-         <xsl:when test="$simpleRestrict/xsd:maxInclusive">
-            <em>
-               <xsl:text>value</xsl:text>
-            </em>
-            <xsl:text> &lt;= </xsl:text>
-            <xsl:value-of select="$simpleRestrict/xsd:maxInclusive/@value"/>
-         </xsl:when>
-         <xsl:when test="$simpleRestrict/xsd:maxExclusive">
-            <em>
-               <xsl:text>value</xsl:text>
-            </em>
-            <xsl:text> &lt; </xsl:text>
-            <xsl:value-of select="$simpleRestrict/xsd:maxExclusive/@value"/>
-         </xsl:when>
-      </xsl:choose>
-   </xsl:template>
-
-   <!--
-     Prints out JavaScript code.
-     NOTE: Javascript code is placed within comments to make it
-     work with current browsers. In strict XHTML, JavaScript code 
-     should be placed within CDATA sections. However, most
-     browsers generate a syntax error if the page contains 
-     CDATA sections. Placing Javascript code within comments
-     means that the code cannot contain two dashes.
-     Param(s):
-            code (Result Tree Fragment) required
-                Javascript code
-  -->
-   <xsl:template name="PrintJSCode">
-      <xsl:param name="code"/>
-
-      <script type="text/javascript">
-         <!-- If browsers start supporting CDATA sections, 
-              uncomment the following piece of code. -->
-         <!-- <xsl:text disable-output-escaping="yes">
-&lt;![CDATA[
-</xsl:text> -->
-         <!-- If browsers start supporting CDATA sections, 
-              remove the following piece of code. -->
-         <xsl:text disable-output-escaping="yes">
-&lt;!--
-</xsl:text>
-
-         <xsl:value-of select="$code" disable-output-escaping="yes"/>
-         <!-- If browsers start supporting CDATA sections, 
-              remove the following piece of code. -->
-         <xsl:text disable-output-escaping="yes">
-// --&gt;
-</xsl:text>
-         <!-- If browsers start supporting CDATA sections, 
-              uncomment the following piece of code. -->
-         <!-- <xsl:text disable-output-escaping="yes">
-]]&gt;
-</xsl:text> -->
-      </script>
-   </xsl:template>
-
-   <!--
-     Translates occurrences of a string
-     in a piece of text with another string.
-     Param(s):
-            value (String) required
-                Text to translate
-            strToReplace (String) required
-                String to be replaced
-            replacementStr (String) required
-                Replacement text
-     -->
-   <xsl:template name="TranslateStr">
-      <xsl:param name="value"/>
-      <xsl:param name="strToReplace"/>
-      <xsl:param name="replacementStr"/>
-
-      <xsl:if test="$value != ''">
-         <xsl:variable name="beforeText" select="substring-before($value, $strToReplace)"/>
-         <xsl:choose>
-            <xsl:when test="$beforeText != ''">
-               <xsl:value-of select="$beforeText"/>
-               <xsl:value-of select="$replacementStr"/>
-               <xsl:call-template name="TranslateStr">
-                  <xsl:with-param name="value" select="substring-after($value, $strToReplace)"/>
-                  <xsl:with-param name="strToReplace" select="$strToReplace"/>
-                  <xsl:with-param name="replacementStr" select="$replacementStr"/>
-               </xsl:call-template>
-            </xsl:when>
-            <xsl:otherwise>
-               <xsl:value-of select="$value"/>
-            </xsl:otherwise>
-         </xsl:choose>
-      </xsl:if>
-   </xsl:template>
-
-   <xsl:template name="HandleError">
-      <xsl:param name="errorMsg"/>
-      <xsl:param name="isTerminating">false</xsl:param>
-
-      <xsl:choose>
-         <xsl:when test="$isTerminating='true'">
-            <xsl:message terminate="yes">
-               <xsl:text>XS3P ERROR: </xsl:text>
-               <xsl:value-of select="$errorMsg"/>
-            </xsl:message>
-         </xsl:when>
-         <xsl:otherwise>
-            <span style="font-weight: bold; color: red">
-               <xsl:text>ERROR: </xsl:text>
-               <xsl:value-of select="$errorMsg"/>
-            </span>
-         </xsl:otherwise>
-      </xsl:choose>
-   </xsl:template>
-</xsl:stylesheet>
diff --git a/python/libmumbl/xmml/external/xs3p-1/xs3p_links.xsl b/python/libmumbl/xmml/external/xs3p-1/xs3p_links.xsl
deleted file mode 100644
index 90454a08cb2032ca4425ab7cabc632f2085d2655..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/external/xs3p-1/xs3p_links.xsl
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version='1.0' ?>
-<xsl:stylesheet 
-	version="1.0" 
-	xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
-	xmlns:xs="http://www.w3.org/2001/XMLSchema" 
-	exclude-result-prefixes="xs">
-
-	<xsl:output
-		method="xml"
-		indent="yes"/>
-        <xsl:param name="recursive">true</xsl:param>
-
-	<xsl:template match="/">
-		<links xmlns="http://titanium.dstc.edu.au/xml/xs3p">
-			<xsl:apply-templates select="//xs:include | //xs:import" />
-		</links>
-	</xsl:template>
-
-	<xsl:template match="xs:include | xs:import">
-		<schema>
-			<xsl:attribute name="file-location">
-				<xsl:value-of select="@schemaLocation"/>
-			</xsl:attribute>
-			<xsl:attribute name="docfile-location">
-				<xsl:value-of select="@schemaLocation"/>.html</xsl:attribute>
-		</schema>
-                <xsl:if test="normalize-space(translate($recursive, 'TRUE', 'true'))='true'">
-		       <xsl:apply-templates select="document(@schemaLocation)/xs:schema/xs:include | document(@schemaLocation)/xs:schema/xs:import" />
-		</xsl:if>
-	</xsl:template>
-
-</xsl:stylesheet>
diff --git a/python/libmumbl/xmml/release/.gitignore b/python/libmumbl/xmml/release/.gitignore
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/python/libmumbl/xmml/xmml.xsd b/python/libmumbl/xmml/xmml.xsd
deleted file mode 100644
index 13ddce699b648a91a54f766fa72330977636f548..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/xmml.xsd
+++ /dev/null
@@ -1,736 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet type="text/xsl" href="external/xs3p-1/xs3p.xsl"?>
-<schema
-  xmlns="http://www.w3.org/2001/XMLSchema"
-  targetNamespace="http://www.mapper-project.eu/xmml"
-  xmlns:xmml="http://www.mapper-project.eu/xmml"
-  elementFormDefault="qualified">
-
-	<annotation><documentation>
-		Specification of the XML representation of the Multiscale Modeling Language
-	  (xMML). For more information, visit http://www.mapper-project.eu/.
-	  
-	  Every element may be appended with any attributes, and the extra and description
-	  elements also take any element as their children.
-	</documentation></annotation>
-
-  <!-- Element definitions -->
-  
-	<element name="model">
-	  <annotation><documentation>
-	    Root element of a multiscale model.
-	  </documentation></annotation>
-		<complexType>
-			<sequence>
-				<element ref="xmml:description" minOccurs="0" maxOccurs="1"/>
-				<element ref="xmml:definitions"/>
-				<element ref="xmml:topology"/>
-			</sequence>
-			<attribute name="id" type="NCName" use="required"/>
-			<attribute name="name" type="string"/>
-			<attribute name="version" type="string"/>
-			<attribute name="xmml_version" fixed="0.4" type="xmml:version"/>
-			<anyAttribute processContents="lax"/>
-		</complexType>
-  
-		<unique name="datatypeId">
-			<selector xpath="xmml:definitions/xmml:datatype"/>
-			<field xpath="@id"/>
-		</unique>
-		<unique name="mapperId">
-			<selector xpath="xmml:definitions/xmml:mapper"/>
-			<field xpath="@id"/>
-		</unique>
-		<unique name="terminalId">
-			<selector xpath="xmml:definitions/xmml:terminal"/>
-			<field xpath="@id"/>
-		</unique>
-		<unique name="submodelId">
-			<selector xpath="xmml:definitions/xmml:submodel"/>
-			<field xpath="@id"/>
-		</unique>
-		<unique name="filterId">
-			<selector xpath="xmml:definitions/xmml:filter"/>
-			<field xpath="@id"/>
-		</unique>
-		<unique name="instanceId">
-			<selector xpath="xmml:topology/xmml:instance"/>
-			<field xpath="@id"/>
-		</unique>
-		
-		<keyref name="datatypeInIdRef" refer="xmml:datatypeId">
-		  <selector xpath="xmml:definitions/xmml:filter"/>
-		  <field xpath="@datatype_in"/>
-	  </keyref>
-		<keyref name="datatypeOutIdRef" refer="xmml:datatypeId">
-		  <selector xpath="xmml:definitions/xmml:filter"/>
-		  <field xpath="@datatype_out"/>
-	  </keyref>
-		<keyref name="datatypePortIdRef" refer="xmml:datatypeId">
-		  <selector xpath="xmml:definitions/xmml:*/xmml:ports/xmml:*"/>
-		  <field xpath="@datatype"/>
-	  </keyref>
-		<keyref name="mapperIdRef" refer="xmml:mapperId">
-		  <selector xpath="xmml:topology/xmml:instance"/>
-		  <field xpath="@mapper"/>
-	  </keyref>
-		<keyref name="terminalIdRef" refer="xmml:terminalId">
-		  <selector xpath="xmml:topology/xmml:instance"/>
-		  <field xpath="@terminal"/>
-	  </keyref>
-		<keyref name="submodelIdRef" refer="xmml:submodelId">
-		  <selector xpath="xmml:topology/xmml:instance"/>
-		  <field xpath="@submodel"/>
-	  </keyref>
-		<keyref name="filterIdRef" refer="xmml:filterId">
-		  <selector xpath="xmml:topology/xmml:coupling/xmml:apply"/>
-		  <field xpath="@filter"/>
-	  </keyref>
-	</element>
-
-	<element name="description" type="xmml:anyContent">
-	  <annotation><documentation>
-	    A short textual description of the parent element.
-	  </documentation></annotation>
-	</element>
-
-	<element name="definitions">
-	  <annotation><documentation>
-	    Type definitions within the model.
-	  </documentation></annotation>
-		<complexType>
-			<sequence>
-				<element ref="xmml:datatype" minOccurs="0" maxOccurs="unbounded"/>
-				<choice minOccurs="0" maxOccurs="unbounded">
-					<element ref="xmml:terminal"/>
-					<element ref="xmml:filter"/>
-					<element ref="xmml:mapper"/>
-					<element ref="xmml:submodel"/>
-				</choice>
-			</sequence>
-  		<anyAttribute processContents="lax"/>
-		</complexType>
-	</element>
-
-	<element name="datatype">
-	  <annotation><documentation>
-	    A datatype definition.
-	  </documentation></annotation>
-		<complexType><complexContent>
-		  <extension base="xmml:definition">
-  			<attribute name="size_estimate" type="xmml:formula">
-  			  <annotation><documentation>
-  			    A function in terms of the scales and params of the
-  			    submodel it originated from.
-  			  </documentation></annotation></attribute>
-  			<attribute name="extends" type="string">
-  			  <annotation><documentation>
-  			    Possibility to extend another datatype, such that
-                all information in the inherited datatype is also
-                available in the current datatype.
-              </documentation></annotation></attribute>
-			</extension>
-		</complexContent></complexType>
-		<keyref name="datatypeExtendsInIdRef" refer="xmml:datatypeId">
-		  <selector xpath="xmml:datatype"/>
-		  <field xpath="@extends"/>
-	  </keyref>
-	</element>
-
-	<element name="filter">
-	  <annotation><documentation>
-	    A conduit filter, filtering a type of data and either converting it to
-      another type of data, or reducing the data over a dimension with a
-      certain factor, or interpolating in that dimension.
-    </documentation></annotation>
-		<complexType><complexContent>
-		  <extension base="xmml:definition">
-  			<sequence>
-  				<element ref="xmml:description" minOccurs="0" maxOccurs="1"/>
-  				<element ref="xmml:param" minOccurs="0" maxOccurs="unbounded"/>
-  				<element ref="xmml:implementation" minOccurs="0" maxOccurs="1"/>
-  				<element ref="xmml:extra" minOccurs="0" maxOccurs="unbounded"/>
-  			</sequence>
-  			<attribute name="datatype_in" type="NCName"><annotation><documentation>
-				  Data type that the filter accepts as input.
-				 </documentation></annotation></attribute>
-  			<attribute name="datatype_out" type="NCName"><annotation><documentation>
- 				  Data type that the filter will give as output.
- 				 </documentation></annotation></attribute>
-  			<attribute name="type" use="required"><annotation><documentation>
-  				  Type of action that the filter will do. Interpolation produces more
-  				  output messages than input messages by some form of interpolation.
-  				  Reduction produces less messages than it receives. And finally, a
-  				  converter only alters the messages that it receives.
-  				 </documentation></annotation>
-  				<simpleType>
-  					<restriction base="NCName">
-  						<enumeration value="interpolation"/>
-  						<enumeration value="reduction"/>
-  						<enumeration value="converter"/>
-  					</restriction>
-  				</simpleType>
-  			</attribute>
-  			<attribute name="dimension" type="string"><annotation><documentation>
-  				  The dimension over which the filter is applied. Use either the id
-  				  or the name of the dimension.
-  				 </documentation></annotation></attribute>
-  			<attribute name="factor" type="xmml:formula"><annotation><documentation>
- 				  The filter may take a single argument, often a factor.
- 				 </documentation></annotation></attribute>
-  		</extension>
-		</complexContent></complexType>
-		<unique name="filterParamId">
-			<selector xpath="xmml:param"/>
-			<field xpath="@id"/>
-		</unique>
-	</element>
-
-	<element name="terminal">
-	  <annotation><documentation>
-            A terminal connection, either a source or a sink. This can pass predefined parameters
-            or file contents, or simply empty data structures. It is allowed to have a single port.
-          </documentation></annotation>
-		<complexType><complexContent>
-		  <extension base="xmml:computationalElement">
-  			<sequence>
-  				<element ref="xmml:description" minOccurs="0" maxOccurs="1"/>
-  				<element ref="xmml:param" minOccurs="0" maxOccurs="unbounded"/>
-  				<element ref="xmml:ports"/>
-  				<element ref="xmml:implementation" minOccurs="0" maxOccurs="1"/>
-  				<element ref="xmml:extra" minOccurs="0" maxOccurs="unbounded"/>
-  			</sequence>
-  			<attribute name="type" use="required">
-  				<simpleType>
-  					<restriction base="NCName">
-  						<enumeration value="source"/>
-  						<enumeration value="sink"/>
-  					</restriction>
-  				</simpleType>
-  			</attribute>
-  		</extension>
-		</complexContent></complexType>
-		<unique name="terminalParamId">
-			<selector xpath="xmml:param"/>
-			<field xpath="@id"/>
-		</unique>
-	</element>
-
-	<element name="mapper">
-	  <annotation><documentation>
-	    A fan-in, or fan-out, or fan-in-out mapper. If the type is fan-in, it may have multiple
-      in ports and one out port, otherwise, one in port and multiple out ports.
-      Implementation details may also be relevant. A fan-in mapper may have
-      the same in port used for a submodel instance with a multiplicity, and
-      conversely for the fan-out mapper. A filter with multiple inputs can be
-      constructed as a fan-in mapper. In and out ports may not have an operator
-      specified. A fan-in-out mapper may have multiple in- and out ports
-      but still has the limitation that it needs all inputs to have a message,
-      and then it sends one message to each output.
-    </documentation></annotation>
-		<complexType><complexContent>
-		  <extension base="xmml:computationalElement">
-  			<sequence>
-  				<element ref="xmml:description" minOccurs="0" maxOccurs="1"/>
-  				<element ref="xmml:param" minOccurs="0" maxOccurs="unbounded"/>
-  				<element ref="xmml:ports"/>
-  				<element ref="xmml:implementation" minOccurs="0" maxOccurs="1"/>
-  				<element ref="xmml:extra" minOccurs="0" maxOccurs="unbounded"/>
-  			</sequence>
-  			<attribute name="type" use="required">
-  				<simpleType>
-  					<restriction base="NCName">
-  						<enumeration value="fan-in"/>
-  						<enumeration value="fan-out"/>
-  						<enumeration value="fan-in-out"/>
-  					</restriction>
-  				</simpleType>
-  			</attribute>
-  		</extension>
-		</complexContent></complexType>
-		<unique name="mapperParamId">
-			<selector xpath="xmml:param"/>
-			<field xpath="@id"/>
-		</unique>
-	</element>
-
-	<element name="submodel">
-	  <annotation><documentation>
-	    Definition of a single code of a single submodel. Attributes state whether
-      the submodel should be started at initialization if this is ambiguous,
-      whether it is stateful or not, or that it is optional but may bring some
-      optimization, and whether user interaction is required while running
-      the submodel.
-    </documentation></annotation>
-		<complexType><complexContent>
-		  <extension base="xmml:computationalElement">
-  			<sequence>
-  				<element ref="xmml:description" minOccurs="0" maxOccurs="1"/>
-  				<element ref="xmml:timescale"/>
-  				<element ref="xmml:spacescale" minOccurs="0" maxOccurs="unbounded"/>
-  				<element ref="xmml:otherscale" minOccurs="0" maxOccurs="unbounded"/>
-  				<element ref="xmml:param" minOccurs="0" maxOccurs="unbounded"/>
-  				<element ref="xmml:ports"/>
-  				<element ref="xmml:implementation" minOccurs="0" maxOccurs="1"/>
-  				<element ref="xmml:extra" minOccurs="0" maxOccurs="unbounded"/>
-  			</sequence>
-  			<attribute name="name" type="string"><annotation><documentation>
-				  A more descriptive name for the submodel, using any characters.
-				 </documentation></annotation></attribute>
-  			<attribute name="type" type="string"><annotation><documentation>
-				  The generic type of submodel. Other submodels with the same type are
-					interchangeable with the current one but may use different algorithms to achieve the same goal.
-				 </documentation></annotation></attribute>
-  			<attribute name="stateful" type="xmml:OptionalChoice" default="no"><annotation><documentation>
-				  Whether the submodel has a state that should be preserved after finalization
-				so that it can be used in initialization. Usually, this can be achieved
-				by keeping the submodel active, but a runtime system may dictate that
-				the submodel is responsible of storing and restoring its state between
-				instantiations.
-				 </documentation></annotation></attribute>
-  		</extension>
-		</complexContent></complexType>
-		<unique name="submodelParamId">
-			<selector xpath="xmml:param"/>
-			<field xpath="@id"/>
-		</unique>
-		<unique name="submodelScaleName">
-			<selector xpath="xmml:timescale | xmml:spacescale | t.otherscale"/>
-			<field xpath="@id"/>
-		</unique>
-	</element>
-
-	<element name="timescale" type="xmml:scale">
-	  <annotation><documentation>
-	    Temporal scale specification of a submodel. Using the attributes, it is a regular
-	    scale, using child elements it is a full scale specification.
-    </documentation></annotation>
-	</element>
-
-	<element name="spacescale" type="xmml:multiDimensionalScale">
-		<annotation><documentation>
-	    Spatial scale specification of a submodel. Using the attributes, it is a regular
-	    scale, using child elements it is a full scale specification.
-	    Either all spatial dimensions can be listed separately, or the number of
-	    dimensions can be given as an attribute, using only one tag.
-    </documentation></annotation>
-	</element>
-
-	<element name="otherscale">
-		<annotation><documentation>
-	    General scale specification of a submodel. Using the attributes, it is a regular
-	    scale, using child elements it is a full scale specification.
-	    Either all spatial dimensions can be listed separately, or the number of
-	    dimensions can be given as an attribute, using only one tag.
-    </documentation></annotation>
-	  <complexType><complexContent>
-	    <extension base="xmml:multiDimensionalScale">
-			  <attribute name="type" type="string"/>
-		  </extension>
-		</complexContent></complexType>
-	</element>
-
-	<element name="param">
-		<annotation><documentation>
-	    Useful for specifying the size of a datatype, or stating a fundamental
-       non-variable fact. It is not meant for completely parameterizing a
-       submodel, since this should be done at time of execution.
-    </documentation></annotation>
-		<complexType>
-			<sequence><element ref="xmml:description" minOccurs="0" maxOccurs="1"/></sequence>
-			<attribute name="id" type="NCName" use="required"/>
-			<attribute name="value" type="string" use="required"/>
-  		<anyAttribute processContents="lax"/>
-		</complexType>
-	</element>
-
-	<element name="extra" type="xmml:anyContent">
-	  <annotation><documentation>
-	    Any information about an element not captured by any of the other tags.
-      If this is used, possibly the information therein can also be included
-      in the official format; if so, please contact me.
-	  </documentation></annotation></element>
-
-	<element name="ports">
-	  <annotation><documentation>
-	    All in and out ports of a computational element.
-	    If the parent element is a submodel, the ports should include an SEL operator.
-    </documentation></annotation>
-		<complexType>
-			<choice minOccurs="0" maxOccurs="unbounded">
-      	<element name="in" type="xmml:port"/>
-      	<element name="out" type="xmml:port"/>
-			</choice>
-		</complexType>
-		<unique name="portId">
-			<selector xpath="*"/>
-			<field xpath="@id"/>
-		</unique>
-	</element>
-
-	<element name="topology">
-	  <annotation><documentation>
-	    The instantiation of computational elements and the couplings between them.
-    </documentation></annotation>
-		<complexType>
-			<sequence>
-				<element ref="xmml:instance" minOccurs="0" maxOccurs="unbounded"/>
-				<element ref="xmml:coupling" minOccurs="0" maxOccurs="unbounded"/>
-			</sequence>
-  		<anyAttribute processContents="lax"/>
-		</complexType>
-	</element>
-
-	<element name="instance">
-	  <annotation><documentation>
-  	  An instance of a submodel or mapper, by default using the same id as the
-      element it instantiates. A submodel instance may override some of the scale
-      information that was supplied in the submodel definition. Mappers may not
-      specify a multiplicity or be stateful.
-    </documentation></annotation>
-		<complexType>
-			<sequence>
-				<element ref="xmml:timescale" minOccurs="0" maxOccurs="1"/>
-				<element ref="xmml:spacescale" minOccurs="0" maxOccurs="unbounded"/>
-				<element ref="xmml:otherscale" minOccurs="0" maxOccurs="unbounded"/>
-				<element ref="xmml:param" minOccurs="0" maxOccurs="unbounded"/>
-				<element ref="xmml:extra" minOccurs="0" maxOccurs="unbounded"/>
-			</sequence>
-			<attribute name="id" type="NCName"/>
-			<attribute name="submodel" type="NCName"/>
-			<attribute name="mapper" type="NCName"/>
-			<attribute name="terminal" type="NCName"/>
-			<attribute name="domain" type="xmml:domain"><annotation><documentation>
-			  A domain name may be supplied, used to identify single domain interaction.
-			  </documentation></annotation></attribute>
-			<attribute name="init" type="xmml:YesNoChoice"/>
-			<attribute name="interactive" type="xmml:OptionalChoice"/>
-			<attribute name="stateful" type="xmml:OptionalChoice"/>
-			<attribute name="multiplicity">
-			  <annotation><documentation>
-			    A multiplicity is a number that specifies how many instances should be
-          created. If this argument is used and not 1, it should be connected
-          using mappers. Alternatively, different instances can be addressed using
-          array notation, for instance: instanceA[0].</documentation></annotation>
-				<simpleType>
-					<restriction base="NCName">
-						<pattern value="[0-9]+|dynamic"/>
-					</restriction>
-				</simpleType>
-			</attribute>
-			<anyAttribute processContents="lax"/>
-		</complexType>
-		<unique name="instanceParamId">
-			<selector xpath="xmml:param"/>
-			<field xpath="@id"/>
-		</unique>
-	</element>
-
-	<element name="coupling">
-	  <annotation><documentation>
-  	  A coupling from one submodel instance, mapper, or terminal to the other.
-      Notation: instance1.outport to instance2.inport. .
-    </documentation></annotation>
-	  <complexType>
-			<sequence>
-				<element ref="xmml:apply" minOccurs="0" maxOccurs="unbounded"/>
-				<element ref="xmml:extra" minOccurs="0" maxOccurs="unbounded"/>
-			</sequence>
-			<attribute name="name" type="string"/>
-			<attribute name="from" type="xmml:instancePort" use="required"/>
-			<attribute name="to" type="xmml:instancePort" use="required"/>
-			<attribute name="size" type="xmml:unit"><annotation><documentation>
-			  Size can be specified if not already done in the datatypes.
-			  </documentation></annotation></attribute>
-			<attribute name="interactive" type="xmml:OptionalChoice" default="no">
-			    <annotation><documentation>
-  			  Whether the data that is sent through the conduit must be evaluated manually
-          before it can be passed to the next.</documentation></annotation></attribute>
-			<anyAttribute processContents="lax"/>
-		</complexType>
-	</element>
-
-	<element name="apply">
-	  <annotation><documentation>
-  	  Specify filters that will be applied to the conduit. The order that they
-      are specified in is preserved.
-    </documentation></annotation>
-		<complexType>
-			<sequence>
-				<element ref="xmml:param" minOccurs="0" maxOccurs="unbounded"/>
-				<element ref="xmml:extra" minOccurs="0" maxOccurs="unbounded"/>
-			</sequence>
-			<attribute name="filter" type="NCName" use="required"/>
-			<attribute name="factor" type="xmml:formula"><annotation><documentation>
-			  Overrides the factor belonging to the filter.
-			  </documentation></annotation></attribute>
-			<anyAttribute processContents="lax"/>
-		</complexType>
-		<unique name="applyParamId">
-			<selector xpath="xmml:param"/>
-			<field xpath="@id"/>
-		</unique>
-	</element>
- 
-  <!-- Implementation details -->
-  
-	<element name="implementation">
-	  <annotation><documentation>
-	    Implementation details of the submodel.
-	  </documentation></annotation>
-		<complexType>
-			<sequence>
-				<element ref="xmml:interpreter" minOccurs="0" maxOccurs="unbounded"/>
-				<element ref="xmml:platform" minOccurs="0" maxOccurs="unbounded"/>
-				<element ref="xmml:library" minOccurs="0" maxOccurs="unbounded"/>
-				<element ref="xmml:code" minOccurs="0" maxOccurs="unbounded"/>
-			</sequence>
-			<attribute name="size" type="xmml:unit"><annotation><documentation>
-			  Size of the compiled code.
-			  </documentation></annotation></attribute>
-			<attribute name="runtime" type="xmml:unit"><annotation><documentation>
-			  Estimated typical runtime on the preferred platform.
-			  </documentation></annotation></attribute>
-			<attribute name="memory" type="xmml:unit"><annotation><documentation>
-				  Amount of memory that is needed for a simulation.</documentation></annotation></attribute>
-			<attribute name="cores" type="positiveInteger"><annotation><documentation>
-			  Number of cores that are typically needed for a simulation.</documentation></annotation></attribute>
-			<attribute name="language" type="string"><annotation><documentation>
-			  The programming language that is used.</documentation></annotation></attribute>
-			<attribute name="path" type="string">	<annotation><documentation>
-				 The path to the code.</documentation></annotation></attribute>
-  		<anyAttribute processContents="lax"/>
-		</complexType>
-	</element>
-
-	<element name="interpreter">
-		<complexType>
-			<attribute name="name" type="string"/>
-			<attribute name="path" type="string"/>
-			<attribute name="version" type="string"/>
-			<attribute name="flags" type="string"/>
-  		<anyAttribute processContents="lax"/>
-		</complexType>
-	</element>
-
-	<element name="platform">
-		<complexType>
-			<attribute name="arch" type="string"/>
-			<attribute name="os" type="string" use="required"/>
-			<attribute name="preferred" type="xmml:YesNoChoice"/>
-  		<anyAttribute processContents="lax"/>
-		</complexType>
-	</element>
-
-	<element name="library">
-		<complexType>
-			<attribute name="name" type="string" use="required"/>
-			<attribute name="path" type="string"/>
-			<anyAttribute processContents="lax"/>
-		</complexType>
-	</element>
-	
-	<element name="code">
-	  <annotation><documentation>
-	    Store the code of an implementation in some specification language.
-			Inside, any XML or text may be used, although for special characters, use
-			the CDATA directive. The language is the input language for the actual
-			code, which should be of the language specified in the 
-	  </documentation></annotation>
-		<complexType>
-			<complexContent>
-				<extension base="xmml:anyContent">
-					<attribute name="language" type="string" use="required"/>
-					<attribute name="version" type="string"/>
-					<attribute name="part" type="string"/>
-					<attribute name="compiler" type="string"/>
-					<attribute name="compilerflags" type="string"/>
-					<anyAttribute processContents="lax"/>
-				</extension>
-			</complexContent>
-		</complexType>
-	</element>
-	
-	<!-- Shared attributes -->
-	
-	<complexType name="scale">
-		<sequence>
-			<element name="delta" type="xmml:range" minOccurs="0" maxOccurs="1"/>
-			<element name="total" type="xmml:range" minOccurs="0" maxOccurs="1"/>
-		</sequence>
-		<attribute name="id" type="NCName"/>
-		<attribute name="delta" type="xmml:unit"/>
-		<attribute name="total" type="xmml:unit"/>
-		<attribute name="characteristic" type="xmml:unit"/>
-		<anyAttribute processContents="lax"/>
-	</complexType>
- 
- 	<complexType name="multiDimensionalScale"><complexContent>
-    <extension base="xmml:scale">
-		  <attribute name="dimensions" type="positiveInteger"/>
-	  </extension></complexContent>
-	</complexType>
- 
-  <complexType name="definition">
-    <annotation><documentation>
-      Represent an implemented entity.
-    </documentation></annotation>
-		<attribute name="id" type="NCName" use="required"/>
-		<attribute name="class" type="string"/>
-		<attribute name="version" type="string"/>
-		<anyAttribute processContents="lax"/>		
-  </complexType>
-
-  <complexType name="computationalElement">
-    <annotation><documentation>
-      Represent a computational element.
-    </documentation></annotation>
-    <complexContent><extension base="xmml:definition">
-      <attribute name="init" type="xmml:YesNoChoice" default="no"/>
-			<attribute name="interactive" type="xmml:OptionalChoice" default="no"/>
-    </extension></complexContent>
-  </complexType>
-
-  <!-- Shared options -->
-  
-	<simpleType name="YesNoChoice">
-		<annotation>
-	    <documentation>A choice between yes and no.</documentation>
-	  </annotation>
-    <restriction base="NCName">
-			<enumeration value="yes"/>
-			<enumeration value="no"/>
-		</restriction>
-	</simpleType>
-	<simpleType name="OptionalChoice">
-	  <annotation>
-	    <documentation>An `optional' option added to yes-no
-	      choice.</documentation>
-	  </annotation>
-		<restriction base="NCName">
-			<enumeration value="yes"/>
-			<enumeration value="no"/>
-			<enumeration value="optional"/>
-		</restriction>
-	</simpleType>
-	<simpleType name="SEL">
-	  <annotation><documentation>
-	    Operators in a submodel execution loop.
-	  </documentation></annotation>
-	  <restriction base="NCName">
-			<enumeration value="finit"/>
-			<enumeration value="Oi"/>
-			<enumeration value="S"/>
-			<enumeration value="B"/>
-			<enumeration value="Of"/>
-		</restriction>
-	</simpleType>
- 
-  <!-- Enforce specific contents of xMML attributes -->
-  
-	<simpleType name="unit">
-		<annotation>
-	    <documentation>
-	      An SI unit, written in scientific notation, but also accepting bits, bytes,
-	      and human-readable time indication. Conformance is evaluated with pattern
-	      `-?[0-9.]+([eE]-?[0-9]+)?\s*\w*'.
-	    </documentation>
-	  </annotation>
-		<restriction base="string">
-			<whiteSpace value="collapse"/>
-			<pattern value="-?[0-9.]+([eE]-?[0-9]+)?\s*\w*"/>
-		</restriction>
-	</simpleType>
-
-	<simpleType name="instancePort">
-	  <annotation><documentation>
-	    The port of an instance, indicated as `instance.port'.
-    </documentation></annotation>		
-		<restriction base="string">
-			<pattern value="(\p{Pc}|\p{Pd}|\p{L}|\p{N})+\.(\p{Pc}|\p{Pd}|\p{L}|\p{N})+"/>
-		</restriction>
-	</simpleType>
-
-	<simpleType name="domain">
-	  <annotation><documentation>
-	      A domain and all its super-domains, separated by periods like
-	      `domain.subdomain.subsubdomain'.
-	    </documentation>
-	  </annotation>
-		<restriction base="string">
-			<pattern value="(\p{Pc}|\p{Pd}|\p{L}|\p{N})+(\.(\p{Pc}|\p{Pd}|\p{L}|\p{N})+)*"/>
-		</restriction>
-	</simpleType>
-	
-	<simpleType name="version">
-	  <annotation><documentation>
-	    Version number of xMML.
-	  </documentation></annotation>
-	  <restriction base="string">
-	    <pattern value="\p{N}+(\.\p{N}+)*(\.\p{N}+-?(\p{L}|\p{N})+)?"/>
-	  </restriction>
-	</simpleType>
-
-	<simpleType name="formula">
-	  <annotation><documentation>
-	    A formula with variables and some standard operators.
-	  </documentation></annotation>
-	  <restriction base="string"/>
-	</simpleType>
-
-	<!-- Shared attributes and elements -->
-	
-	<complexType name="anyContent" mixed="true">
-	  <annotation>
-	    <documentation>Any content is possible within this type</documentation>
-	  </annotation>
-		<sequence>
-			<any minOccurs="0" maxOccurs="unbounded" processContents="lax"/>
-		</sequence>
-		<anyAttribute processContents="lax"/>
-	</complexType>
-
-	<complexType name="port">
-	  <annotation>
-	    <documentation>
-	      The id, submodel execution loop operator and datatype of a port. If it
-         concerns the port of a mapper, an operator should not be specified. The 
-         optional type can be used to specify whether it concerns a port that only
-         transfers a state or a regular one.
-      </documentation>
-    </annotation>
-    
-		<attribute name="id" type="NCName" use="required"/>
-		<attribute name="operator" type="xmml:SEL"/>
-		<attribute name="datatype" type="NCName"/>
-		<attribute name="type" default="normal">
-			<simpleType>
-				<restriction base="NCName">
-					<enumeration value="state"/>
-					<enumeration value="normal"/>
-				</restriction>
-			</simpleType>
-		</attribute>
-		<anyAttribute processContents="lax"/>
-	</complexType>
- 
-	<complexType name="range">
-	  <annotation><documentation>
-	       A scale range, with an optional minimum and maximum value. If the type
-         is fixed, then during runtime this value will not vary and must be
-         specified for each submodel instance that uses it.
-    </documentation></annotation>
-    
-		<attribute name="type" default="variable">
-			<simpleType>
-				<restriction base="NCName">
-					<enumeration value="variable"/>
-					<enumeration value="fixed"/>
-				</restriction>
-			</simpleType>
-		</attribute>
-		<attribute name="min" type="xmml:unit"/>
-		<attribute name="max" type="xmml:unit"/>
-		<anyAttribute processContents="lax"/>
-	</complexType>
-</schema>
diff --git a/python/libmumbl/xmml/xmml_param.xsd b/python/libmumbl/xmml/xmml_param.xsd
deleted file mode 100644
index 341ad7499220aff30e6a9736abffef555d2c332d..0000000000000000000000000000000000000000
--- a/python/libmumbl/xmml/xmml_param.xsd
+++ /dev/null
@@ -1,101 +0,0 @@
-<?xml version="1.0"?>
-<?xml-stylesheet type="text/xsl" href="external/xs3p-1/xs3p.xsl"?>
-<schema
-  xmlns="http://www.w3.org/2001/XMLSchema"
-  targetNamespace="http://www.mapper-project.eu/xmml/param"
-  xmlns:par="http://www.mapper-project.eu/xmml/param"
-  xmlns:xmml="http://www.mapper-project.eu/xmml"
-  elementFormDefault="qualified">
-
-	<import namespace="http://www.mapper-project.eu/xmml" schemaLocation="xmml.xsd"/>
-	<annotation><documentation>
-		Specification of the parameter file associated to the XML representation of the Multiscale
-		Modeling Language  (xMML). For more information, visit http://www.mapper-project.eu/.
-	</documentation></annotation>
-
-  <!-- Element definitions -->
-  
-	<element name="parameters">
-		<annotation><documentation>
-			Root element of parameters. Parameters are normally given to parameterGroup elements, which refer
-			to specific elements in the referred to model. However, it also possible to give global parameters here.
-		</documentation></annotation>
-		<complexType>
-			<sequence>
-				<element ref="xmml:description" minOccurs="0" maxOccurs="1"/>
-				<choice minOccurs="0" maxOccurs="unbounded">
-					<element ref="xmml:param"/>
-					<element ref="par:parameterGroup"/>
-					<element ref="par:include"/>
-					<element ref="xmml:extra"/>
-				</choice>
-			</sequence>
-
-			<attribute name="id" type="NCName" use="required">
-				<annotation><documentation>
-					The id of the model these parameters refer to.
-				</documentation></annotation>
-			</attribute>
-			<attribute name="version" type="string">
-				<annotation><documentation>
-					A version of the model these parameters refer to.
-				</documentation></annotation></attribute>
-			<attribute name="name" type="string">
-				<annotation><documentation>
-					The name of this parameter set.
-				</documentation></annotation></attribute>
-			<attribute name="xmml_version" fixed="0.4" type="xmml:version"/>
-			<anyAttribute processContents="lax"/>
-		</complexType>
-  
-		<unique name="parameterGroupId">
-			<selector xpath="par:parameterGroup"/>
-			<field xpath="@id"/>
-		</unique>
-		
-		<keyref name="parameterGroupRefId" refer="par:parameterGroupId">
-			<selector xpath="par:include"/>
-			<field xpath="@parameterGroup"/>
-		  </keyref>
-	</element>
-
-	<element name="parameterGroup">
-		<annotation><documentation>
-			A group of parameters associated to an element in the model that is referred to. The parameters given
-			here override the parameters given in the model description.
-		</documentation></annotation>
-		<complexType>
-			<sequence>
-				<element ref="xmml:description" minOccurs="0" maxOccurs="1"/>
-				<choice minOccurs="0" maxOccurs="unbounded">
-					<element ref="xmml:param"/>
-					<element ref="par:parameterGroup"/>
-					<element ref="par:include"/>
-					<element ref="xmml:extra"/>
-				</choice>
-			</sequence>
-			<attribute name="id" type="NCName"/>
-			<attribute name="submodel" type="NCName"/>
-			<attribute name="mapper" type="NCName"/>
-			<attribute name="filter" type="NCName"/>
-			<attribute name="instance" type="NCName"/>
-			<attribute name="domain" type="NCName"/>
-			<anyAttribute processContents="lax"/>
-		</complexType>
-		<unique name="instanceParamId">
-			<selector xpath="xmml:param"/>
-			<field xpath="@id"/>
-		</unique>
-	</element>
-	
-	<element name="include">
-		<annotation><documentation>
-		Includes a parametergroup at the current level.
-		</documentation></annotation>
-
-		<complexType>
-			<attribute name="parameterGroup" type="NCName"/>
-			<anyAttribute processContents="lax"/>
-		</complexType>
-	</element>
-</schema>
diff --git a/python/moose/SBML/readSBML.py b/python/moose/SBML/readSBML.py
index 2deda273d5f4599073f141989de2e398520562c0..2765c5e045a4d600aea8a23c0398e422c8bd5c96 100644
--- a/python/moose/SBML/readSBML.py
+++ b/python/moose/SBML/readSBML.py
@@ -5,25 +5,25 @@
  * Author:          HarshaRani
  * E-mail:          hrani@ncbs.res.in
  ********************************************************************/
+
 /**********************************************************************
 ** This program is part of 'MOOSE', the
 ** Messaging Object Oriented Simulation Environment,
 ** also known as GENESIS 3 base code.
 **           copyright (C) 2003-2016 Upinder S. Bhalla. and NCBS
 Created : Thu May 12 10:19:00 2016(+0530)
-Version 
+Version
 Last-Updated: Wed Sep 28
-		  By:
+          By:
 **********************************************************************/
-/****************************
 
 '''
 
 import sys
 import os.path
 import collections
-from moose import *
-#import libsbml
+import moose
+
 
 '''
    TODO in
@@ -31,988 +31,1103 @@ from moose import *
       --Need to add group
       --Need to deal with compartment outside
     -Molecule
-      -- Need to add group 
-      -- mathML only AssisgmentRule is taken partly I have checked addition and multiplication, 
+      -- Need to add group
+      -- mathML only AssisgmentRule is taken partly I have checked addition and multiplication,
        --, need to do for other calculation.
        -- In Assisgment rule one of the variable is a function, in moose since assignment is done using function,
           function can't get input from another function (model 000740 in l3v1)
     -Loading Model from SBML
       --Tested 1-30 testcase example model provided by l3v1 and l2v4 std.
         ---These are the models that worked (sbml testcase)1-6,10,14-15,17-21,23-25,34,35,58
-	---Need to check
-	 	----what to do when boundarycondition is true i.e.,
+    ---Need to check
+         ----what to do when boundarycondition is true i.e.,
              differential equation derived from the reaction definitions
              should not be calculated for the species(7-9,11-13,16)
-        	 ----kineticsLaw, Math fun has fraction,ceiling,reminder,power 28etc.
-         	----Events to be added 26
-	 	----initial Assisgment for compartment 27
-        	 ----when stoichiometry is rational number 22
-	 	---- For Michaelis Menten kinetics km is not defined which is most of the case need to calculate
+             ----kineticsLaw, Math fun has fraction,ceiling,reminder,power 28etc.
+             ----Events to be added 26
+         ----initial Assisgment for compartment 27
+             ----when stoichiometry is rational number 22
+         ---- For Michaelis Menten kinetics km is not defined which is most of the case need to calculate
 '''
-try: 
-    #from libsbml import *
+
+foundLibSBML_ = False
+try:
     import libsbml
-except ImportError: 
-    def mooseReadSBML(filepath,loadpath,solver="ee"):
-    	return (-2,"\n ReadSBML : python-libsbml module not installed",None)
-else:
-	def mooseReadSBML(filepath,loadpath,solver="ee"):
-		try:
-			filep = open(filepath, "r")
-			document = libsbml.readSBML(filepath)
-			num_errors = document.getNumErrors()
-			if ( num_errors > 0 ):
-				print("Encountered the following SBML errors:" );
-				document.printErrors();
-				return moose.element('/');
-			else:
-				level = document.getLevel();
-				version = document.getVersion();
-				print(("\n" + "File: " + filepath + " (Level " + str(level) + ", version " + str(version) + ")" ));
-				model = document.getModel();
-				if (model == None):
-					print("No model present." );
-					return moose.element('/');
-				else:
-					print((" model: " +str(model)));
-					print(("functionDefinitions: " + str(model.getNumFunctionDefinitions()) ));
-					print(("    unitDefinitions: " + str(model.getNumUnitDefinitions()) ));
-					print(("   compartmentTypes: " + str(model.getNumCompartmentTypes()) ));
-					print(("        specieTypes: " + str(model.getNumSpeciesTypes()) ));
-					print(("       compartments: " + str(model.getNumCompartments()) ));
-					print(("            species: " + str(model.getNumSpecies()) ));
-					print(("         parameters: " + str(model.getNumParameters()) ));
-					print((" initialAssignments: " + str(model.getNumInitialAssignments()) ));
-					print(("              rules: " + str(model.getNumRules()) ));
-					print(("        constraints: " + str(model.getNumConstraints()) ));
-					print(("          reactions: " + str(model.getNumReactions()) ));
-					print(("             events: " + str(model.getNumEvents()) ));
-					print("\n");
-
-					if (model.getNumCompartments() == 0):
-						return moose.element('/')
-					else:
-						baseId = moose.Neutral(loadpath)
-						#All the model will be created under model as a thumbrule
-						basePath = moose.Neutral(baseId.path+'/model')
-						#Map Compartment's SBML id as key and value is list of[ Moose ID and SpatialDimensions ]
-						global comptSbmlidMooseIdMap
-						global warning
-						warning = " "
-						comptSbmlidMooseIdMap = {}
-						print(("modelPath:" + basePath.path))
-						globparameterIdValue = {}
-						modelAnnotaInfo = {}
-						mapParameter(model,globparameterIdValue)
-						errorFlag = createCompartment(basePath,model,comptSbmlidMooseIdMap)
-						if errorFlag:
-							specInfoMap = {}
-							errorFlag = createSpecies(basePath,model,comptSbmlidMooseIdMap,specInfoMap,modelAnnotaInfo)
-							if errorFlag:
-								errorFlag = createRules(model,specInfoMap,globparameterIdValue)
-								if errorFlag:
-									errorFlag,msg = createReaction(model,specInfoMap,modelAnnotaInfo,globparameterIdValue)
-							getModelAnnotation(model,baseId,basePath)
-						
-						if not errorFlag:
-							print(msg)
-							#Any time in the middle if SBML does not read then I delete everything from model level
-							#This is important as while reading in GUI the model will show up untill built which is not correct
-							#print "Deleted rest of the model"
-							moose.delete(basePath)
-					return baseId;
-
-
-		except IOError:
-			print("File " ,filepath ," does not exist.")
-			return moose.element('/')
-
-def setupEnzymaticReaction(enz,groupName,enzName,specInfoMap,modelAnnotaInfo):
-	enzPool = (modelAnnotaInfo[groupName]["enzyme"])
-	enzPool = str(idBeginWith(enzPool))
-	enzParent = specInfoMap[enzPool]["Mpath"]
-	cplx = (modelAnnotaInfo[groupName]["complex"])
-	cplx = str(idBeginWith(cplx))
-	complx = moose.element(specInfoMap[cplx]["Mpath"].path)
-	
-	enzyme_ = moose.Enz(enzParent.path+'/'+enzName)
-	moose.move(complx,enzyme_)
-	moose.connect(enzyme_,"cplx",complx,"reac")
-	moose.connect(enzyme_,"enz",enzParent,"reac");
-
-	sublist = (modelAnnotaInfo[groupName]["substrate"])
-	prdlist = (modelAnnotaInfo[groupName]["product"])
-
-	for si in range(0,len(sublist)):
-		sl = sublist[si]
-		sl = str(idBeginWith(sl))
-		mSId =specInfoMap[sl]["Mpath"]
-		moose.connect(enzyme_,"sub",mSId,"reac")
-
-	for pi in range(0,len(prdlist)):
-		pl = prdlist[pi]
-		pl = str(idBeginWith(pl))
-		mPId = specInfoMap[pl]["Mpath"]
-		moose.connect(enzyme_,"prd",mPId,"reac")
-	
-	if (enz.isSetNotes):
-		pullnotes(enz,enzyme_)
-
-	return enzyme_,True
-
-def addSubPrd(reac,reName,type,reactSBMLIdMooseId,specInfoMap):
-	rctMapIter = {}
-	if (type == "sub"):
-		noplusStoichsub = 0
-		addSubinfo = collections.OrderedDict()
-		for rt in range(0,reac.getNumReactants()):
-			rct = reac.getReactant(rt)
-			sp = rct.getSpecies()
-			rctMapIter[sp] = rct.getStoichiometry()
-			if rct.getStoichiometry() > 1:
-				pass
-				#print " stoich ",reac.name,rct.getStoichiometry()
-			noplusStoichsub = noplusStoichsub+rct.getStoichiometry()
-		for key,value in list(rctMapIter.items()):
-			key = str(idBeginWith(key))
-			src = specInfoMap[key]["Mpath"]
-			des = reactSBMLIdMooseId[reName]["MooseId"]
-			for s in range(0,int(value)):
-				moose.connect(des, 'sub', src, 'reac', 'OneToOne')
-		addSubinfo = {"nSub" :noplusStoichsub}
-		reactSBMLIdMooseId[reName].update(addSubinfo)
-
-	else:
-		noplusStoichprd = 0
-		addPrdinfo = collections.OrderedDict()
-		for rt in range(0,reac.getNumProducts()):
-			rct = reac.getProduct(rt)
-			sp = rct.getSpecies()
-			rctMapIter[sp] = rct.getStoichiometry()
-			if rct.getStoichiometry() > 1:
-				pass
-				#print " stoich prd",reac.name,rct.getStoichiometry()
-			noplusStoichprd = noplusStoichprd+rct.getStoichiometry()
-		
-		for key,values in list(rctMapIter.items()):
-			#src ReacBase
-			src = reactSBMLIdMooseId[reName]["MooseId"]
-			key = parentSp = str(idBeginWith(key))
-			des = specInfoMap[key]["Mpath"]
-			for i in range(0,int(values)):
-				moose.connect(src, 'prd', des, 'reac', 'OneToOne')
-		addPrdinfo = {"nPrd": noplusStoichprd}
-		reactSBMLIdMooseId[reName].update(addPrdinfo)
-
-def populatedict(annoDict,label,value):
-	if label in annoDict:
-		annoDict.setdefault(label,[])
-		annoDict[label].update({value})
-	else:
-		annoDict[label]= {value}
-
-def getModelAnnotation(obj,baseId,basepath):
-	annotationNode = obj.getAnnotation()
-	if annotationNode != None:
-		numchild = annotationNode.getNumChildren()
-		for child_no in range(0,numchild):
-			childNode = annotationNode.getChild( child_no )
-			if ( childNode.getPrefix() == "moose" and childNode.getName() == "ModelAnnotation" ):
-				num_gchildren = childNode.getNumChildren()
-				for gchild_no in range(0,num_gchildren):
-					grandChildNode = childNode.getChild(gchild_no)
-					nodeName = grandChildNode.getName()
-					if (grandChildNode.getNumChildren() == 1 ):
-						baseinfo = moose.Annotator(baseId.path+'/info')
-						baseinfo.modeltype = "xml"
-						if nodeName == "runTime":
-							runtime = float((grandChildNode.getChild(0).toXMLString()))
-							baseinfo.runtime = runtime
-						if nodeName == "solver":
-							solver = (grandChildNode.getChild(0).toXMLString())
-							baseinfo.solver = solver
-						if(nodeName == "plots"):
-							plotValue = (grandChildNode.getChild(0).toXMLString())
-							p = moose.element(baseId)
-							datapath = moose.element(baseId).path +"/data"
-							if not moose.exists(datapath):
-								datapath = moose.Neutral(baseId.path+"/data")
-								graph = moose.Neutral(datapath.path+"/graph_0")
-								plotlist= plotValue.split(";")
-								tablelistname = []
-								for plots in plotlist:
-									plots = plots.replace(" ", "")
-									plotorg = plots
-									if moose.exists(basepath.path+plotorg):
-										plotSId = moose.element(basepath.path+plotorg)
-										#plotorg = convertSpecialChar(plotorg)
-										plot2 = plots.replace('/','_')
-										plot3 = plot2.replace('[','_')
-										plotClean = plot3.replace(']','_')
-										plotName =  plotClean + ".conc"
-										fullPath = graph.path+'/'+plotName.replace(" ","")
-										#If table exist with same name then its not created
-										if not fullPath  in tablelistname:
-											tab = moose.Table2(fullPath)
-											tablelistname.append(fullPath)
-											moose.connect(tab,"requestOut",plotSId,"getConc")
-
-def getObjAnnotation(obj,modelAnnotationInfo):
-	name = obj.getId()
-	name = name.replace(" ","_space_")
-	#modelAnnotaInfo= {}
-	annotateMap = {}
-	if (obj.getAnnotation() != None):
-		annoNode = obj.getAnnotation()
-		for ch in range(0,annoNode.getNumChildren()):
-			childNode = annoNode.getChild(ch)
-			if (childNode.getPrefix() == "moose" and (childNode.getName() == "ModelAnnotation" or childNode.getName() == "EnzymaticReaction")):
-				sublist = []
-				for gch in range(0,childNode.getNumChildren()):
-					grandChildNode = childNode.getChild(gch)
-					nodeName = grandChildNode.getName()
-					nodeValue = ""
-					if (grandChildNode.getNumChildren() == 1):
-						nodeValue = grandChildNode.getChild(0).toXMLString()
-					else:
-						print("Error: expected exactly ONE child of ", nodeName)
-					
-					if nodeName == "xCord":
-						annotateMap[nodeName] = nodeValue
-					if nodeName == "yCord":
-						annotateMap[nodeName] = nodeValue
-					if nodeName == "bgColor":
-							annotateMap[nodeName] = nodeValue
-					if nodeName == "textColor":
-						annotateMap[nodeName] = nodeValue
-	return annotateMap
-def getEnzAnnotation(obj,modelAnnotaInfo,rev,globparameterIdValue,specInfoMap):
-	name = obj.getId()
-	name = name.replace(" ","_space_")
-	#modelAnnotaInfo= {}
-	annotateMap = {}
-	if (obj.getAnnotation() != None):
-		annoNode = obj.getAnnotation()
-		for ch in range(0,annoNode.getNumChildren()):
-			childNode = annoNode.getChild(ch)
-			if (childNode.getPrefix() == "moose" and childNode.getName() == "EnzymaticReaction"):
-				sublist = []
-				for gch in range(0,childNode.getNumChildren()):
-					grandChildNode = childNode.getChild(gch)
-					nodeName = grandChildNode.getName()
-					nodeValue = ""
-					if (grandChildNode.getNumChildren() == 1):
-						nodeValue = grandChildNode.getChild(0).toXMLString()
-					else:
-						print("Error: expected exactly ONE child of ", nodeName)
-					
-					if nodeName == "enzyme":
-						populatedict(annotateMap,"enzyme",nodeValue)
-	
-					elif nodeName == "complex":
-						populatedict(annotateMap,"complex" ,nodeValue)
-					elif ( nodeName == "substrates"):
-						populatedict(annotateMap,"substrates" ,nodeValue)
-					elif ( nodeName == "product" ):
-						populatedict(annotateMap,"product" ,nodeValue)
-					elif ( nodeName == "groupName" ):
-						populatedict(annotateMap,"grpName" ,nodeValue)
-					elif ( nodeName == "stage" ):
-						populatedict(annotateMap,"stage" ,nodeValue)
-					elif ( nodeName == "Group" ):
-						populatedict(annotateMap,"group" ,nodeValue)
-					elif ( nodeName == "xCord" ):
-						populatedict(annotateMap,"xCord" ,nodeValue)
-					elif ( nodeName == "yCord" ):
-						populatedict(annotateMap,"yCord" ,nodeValue)
-	groupName = ""
-	if 'grpName' in annotateMap:
-		groupName = list(annotateMap["grpName"])[0]
-		klaw=obj.getKineticLaw();
-		mmsg = ""
-		errorFlag, mmsg,k1,k2 = getKLaw(obj,klaw,rev,globparameterIdValue,specInfoMap)
-
-		if 'substrates' in annotateMap:
-		    sublist = list(annotateMap["substrates"])
-		else:
-			sublist = {}
-		if 'product' in annotateMap:
-		    prdlist = list(annotateMap["product"])
-		else:
-			prdlist = {}
-
-		if list(annotateMap["stage"])[0] == '1':
-			if groupName in modelAnnotaInfo:
-				modelAnnotaInfo[groupName].update	(
-					{"enzyme" : list(annotateMap["enzyme"])[0],
-					"stage" : list(annotateMap["stage"])[0],
-					"substrate" : sublist,
-					"k1": k1,
-					"k2" : k2
-					}
-				)
-			else:
-				modelAnnotaInfo[groupName]= {
-					"enzyme" : list(annotateMap["enzyme"])[0],
-					"stage" : list(annotateMap["stage"])[0],
-					"substrate" :  sublist,
-					"k1" : k1,
-					"k2" : k2
-					#"group" : list(annotateMap["Group"])[0],
-					#"xCord" : list(annotateMap["xCord"])[0],
-					#"yCord" : list(annotateMap["yCord"]) [0]
-					}
-
-		elif list(annotateMap["stage"])[0] == '2':
-			if groupName in modelAnnotaInfo:
-				stage = int(modelAnnotaInfo[groupName]["stage"])+int(list(annotateMap["stage"])[0])
-				modelAnnotaInfo[groupName].update (
-					{"complex" : list(annotateMap["complex"])[0],
-					"product" : prdlist,
-					"stage" : [stage],
-					"k3" : k1
-					}
-				)
-			else:
-				modelAnnotaInfo[groupName]= {
-					"complex" : list(annotateMap["complex"])[0],
-					"product" : prdlist,
-					"stage" : [stage],
-					"k3" : k1
-					}
-	return(groupName)
-
-
-def createReaction(model,specInfoMap,modelAnnotaInfo,globparameterIdValue):
-	# print " reaction "
-	# Things done for reaction
-	# --Reaction is not created, if substrate and product is missing
-	# --Reaction is created under first substrate's compartment if substrate not found then product
-	# --Reaction is created if substrate or product is missing, but while run time in GUI atleast I have stopped
-	#ToDo
-	# -- I need to check here if any substance/product is if ( constant == true && bcondition == false)
+    foundLibSBML_ = True
+except ImportError:
+    pass
+
+
+def mooseReadSBML(filepath, loadpath, solver="ee"):
+    global foundLibSBML_
+    if not foundLibSBML_:
+        print('No python-libsbml found.' 
+            '\nThis module can be installed by following command in terminal:'
+            '\n\t easy_install python-libsbl'
+            )
+        return None
+
+    if not os.path.isfile(filepath):
+        print('%s is not found ' % filepath)
+        return None
+
+    with open(filepath, "r") as filep:
+        filep = open(filepath, "r")
+        document = libsbml.readSBML(filepath)
+        num_errors = document.getNumErrors()
+        if (num_errors > 0):
+            print("Encountered the following SBML errors:")
+            document.printErrors()
+            return moose.element('/')
+        else:
+            level = document.getLevel()
+            version = document.getVersion()
+            print(("\n" + "File: " + filepath + " (Level " +
+                   str(level) + ", version " + str(version) + ")"))
+            model = document.getModel()
+            if (model is None):
+                print("No model present.")
+                return moose.element('/')
+            else:
+                print((" model: " + str(model)))
+                print(("functionDefinitions: " +
+                       str(model.getNumFunctionDefinitions())))
+                print(("    unitDefinitions: " +
+                       str(model.getNumUnitDefinitions())))
+                print(("   compartmentTypes: " +
+                       str(model.getNumCompartmentTypes())))
+                print(("        specieTypes: " +
+                       str(model.getNumSpeciesTypes())))
+                print(("       compartments: " +
+                       str(model.getNumCompartments())))
+                print(("            species: " +
+                       str(model.getNumSpecies())))
+                print(("         parameters: " +
+                       str(model.getNumParameters())))
+                print((" initialAssignments: " +
+                       str(model.getNumInitialAssignments())))
+                print(("              rules: " +
+                       str(model.getNumRules())))
+                print(("        constraints: " +
+                       str(model.getNumConstraints())))
+                print(("          reactions: " +
+                       str(model.getNumReactions())))
+                print(("             events: " +
+                       str(model.getNumEvents())))
+                print("\n")
+
+                if (model.getNumCompartments() == 0):
+                    return moose.element('/')
+                else:
+                    baseId = moose.Neutral(loadpath)
+                    # All the model will be created under model as
+                    # a thumbrule
+                    basePath = moose.Neutral(
+                        baseId.path + '/model')
+                    # Map Compartment's SBML id as key and value is
+                    # list of[ Moose ID and SpatialDimensions ]
+                    global comptSbmlidMooseIdMap
+                    global warning
+                    warning = " "
+                    comptSbmlidMooseIdMap = {}
+                    print(("modelPath:" + basePath.path))
+                    globparameterIdValue = {}
+                    modelAnnotaInfo = {}
+                    mapParameter(model, globparameterIdValue)
+                    errorFlag = createCompartment(
+                        basePath, model, comptSbmlidMooseIdMap)
+                    if errorFlag:
+                        specInfoMap = {}
+                        errorFlag = createSpecies(
+                            basePath, model, comptSbmlidMooseIdMap, specInfoMap, modelAnnotaInfo)
+                        if errorFlag:
+                            errorFlag = createRules(
+                                model, specInfoMap, globparameterIdValue)
+                            if errorFlag:
+                                errorFlag, msg = createReaction(
+                                    model, specInfoMap, modelAnnotaInfo, globparameterIdValue)
+                        getModelAnnotation(
+                            model, baseId, basePath)
+
+                    if not errorFlag:
+                        print(msg)
+                        # Any time in the middle if SBML does not read then I
+                        # delete everything from model level This is important
+                        # as while reading in GUI the model will show up untill
+                        # built which is not correct print "Deleted rest of the
+                        # model"
+                        moose.delete(basePath)
+            return baseId
+
+
+def setupEnzymaticReaction(enz, groupName, enzName,
+                           specInfoMap, modelAnnotaInfo):
+    enzPool = (modelAnnotaInfo[groupName]["enzyme"])
+    enzPool = str(idBeginWith(enzPool))
+    enzParent = specInfoMap[enzPool]["Mpath"]
+    cplx = (modelAnnotaInfo[groupName]["complex"])
+    cplx = str(idBeginWith(cplx))
+    complx = moose.element(specInfoMap[cplx]["Mpath"].path)
+
+    enzyme_ = moose.Enz(enzParent.path + '/' + enzName)
+    moose.move(complx, enzyme_)
+    moose.connect(enzyme_, "cplx", complx, "reac")
+    moose.connect(enzyme_, "enz", enzParent, "reac")
+
+    sublist = (modelAnnotaInfo[groupName]["substrate"])
+    prdlist = (modelAnnotaInfo[groupName]["product"])
+
+    for si in range(0, len(sublist)):
+        sl = sublist[si]
+        sl = str(idBeginWith(sl))
+        mSId = specInfoMap[sl]["Mpath"]
+        moose.connect(enzyme_, "sub", mSId, "reac")
+
+    for pi in range(0, len(prdlist)):
+        pl = prdlist[pi]
+        pl = str(idBeginWith(pl))
+        mPId = specInfoMap[pl]["Mpath"]
+        moose.connect(enzyme_, "prd", mPId, "reac")
+
+    if (enz.isSetNotes):
+        pullnotes(enz, enzyme_)
+
+    return enzyme_, True
+
+
+def addSubPrd(reac, reName, type, reactSBMLIdMooseId, specInfoMap):
+    rctMapIter = {}
+    if (type == "sub"):
+        noplusStoichsub = 0
+        addSubinfo = collections.OrderedDict()
+        for rt in range(0, reac.getNumReactants()):
+            rct = reac.getReactant(rt)
+            sp = rct.getSpecies()
+            rctMapIter[sp] = rct.getStoichiometry()
+            if rct.getStoichiometry() > 1:
+                pass
+                # print " stoich ",reac.name,rct.getStoichiometry()
+            noplusStoichsub = noplusStoichsub + rct.getStoichiometry()
+        for key, value in list(rctMapIter.items()):
+            key = str(idBeginWith(key))
+            src = specInfoMap[key]["Mpath"]
+            des = reactSBMLIdMooseId[reName]["MooseId"]
+            for s in range(0, int(value)):
+                moose.connect(des, 'sub', src, 'reac', 'OneToOne')
+        addSubinfo = {"nSub": noplusStoichsub}
+        reactSBMLIdMooseId[reName].update(addSubinfo)
+
+    else:
+        noplusStoichprd = 0
+        addPrdinfo = collections.OrderedDict()
+        for rt in range(0, reac.getNumProducts()):
+            rct = reac.getProduct(rt)
+            sp = rct.getSpecies()
+            rctMapIter[sp] = rct.getStoichiometry()
+            if rct.getStoichiometry() > 1:
+                pass
+                # print " stoich prd",reac.name,rct.getStoichiometry()
+            noplusStoichprd = noplusStoichprd + rct.getStoichiometry()
+
+        for key, values in list(rctMapIter.items()):
+            # src ReacBase
+            src = reactSBMLIdMooseId[reName]["MooseId"]
+            key = parentSp = str(idBeginWith(key))
+            des = specInfoMap[key]["Mpath"]
+            for i in range(0, int(values)):
+                moose.connect(src, 'prd', des, 'reac', 'OneToOne')
+        addPrdinfo = {"nPrd": noplusStoichprd}
+        reactSBMLIdMooseId[reName].update(addPrdinfo)
+
+
+def populatedict(annoDict, label, value):
+    if label in annoDict:
+        annoDict.setdefault(label, [])
+        annoDict[label].update({value})
+    else:
+        annoDict[label] = {value}
+
+
+def getModelAnnotation(obj, baseId, basepath):
+    annotationNode = obj.getAnnotation()
+    if annotationNode is not None:
+        numchild = annotationNode.getNumChildren()
+        for child_no in range(0, numchild):
+            childNode = annotationNode.getChild(child_no)
+            if (childNode.getPrefix() ==
+                    "moose" and childNode.getName() == "ModelAnnotation"):
+                num_gchildren = childNode.getNumChildren()
+                for gchild_no in range(0, num_gchildren):
+                    grandChildNode = childNode.getChild(gchild_no)
+                    nodeName = grandChildNode.getName()
+                    if (grandChildNode.getNumChildren() == 1):
+                        baseinfo = moose.Annotator(baseId.path + '/info')
+                        baseinfo.modeltype = "xml"
+                        if nodeName == "runTime":
+                            runtime = float(
+                                (grandChildNode.getChild(0).toXMLString()))
+                            baseinfo.runtime = runtime
+                        if nodeName == "solver":
+                            solver = (grandChildNode.getChild(0).toXMLString())
+                            baseinfo.solver = solver
+                        if(nodeName == "plots"):
+                            plotValue = (
+                                grandChildNode.getChild(0).toXMLString())
+                            p = moose.element(baseId)
+                            datapath = moose.element(baseId).path + "/data"
+                            if not moose.exists(datapath):
+                                datapath = moose.Neutral(baseId.path + "/data")
+                                graph = moose.Neutral(
+                                    datapath.path + "/graph_0")
+                                plotlist = plotValue.split(";")
+                                tablelistname = []
+                                for plots in plotlist:
+                                    plots = plots.replace(" ", "")
+                                    plotorg = plots
+                                    if moose.exists(basepath.path + plotorg):
+                                        plotSId = moose.element(
+                                            basepath.path + plotorg)
+                                        # plotorg = convertSpecialChar(plotorg)
+                                        plot2 = plots.replace('/', '_')
+                                        plot3 = plot2.replace('[', '_')
+                                        plotClean = plot3.replace(']', '_')
+                                        plotName = plotClean + ".conc"
+                                        fullPath = graph.path + '/' + \
+                                            plotName.replace(" ", "")
+                                        # If table exist with same name then
+                                        # its not created
+                                        if not fullPath in tablelistname:
+                                            tab = moose.Table2(fullPath)
+                                            tablelistname.append(fullPath)
+                                            moose.connect(
+                                                tab, "requestOut", plotSId, "getConc")
+
+
+def getObjAnnotation(obj, modelAnnotationInfo):
+    name = obj.getId()
+    name = name.replace(" ", "_space_")
+    # modelAnnotaInfo= {}
+    annotateMap = {}
+    if (obj.getAnnotation() is not None):
+        annoNode = obj.getAnnotation()
+        for ch in range(0, annoNode.getNumChildren()):
+            childNode = annoNode.getChild(ch)
+            if (childNode.getPrefix() == "moose" and (childNode.getName() ==
+                                                      "ModelAnnotation" or childNode.getName() == "EnzymaticReaction")):
+                sublist = []
+                for gch in range(0, childNode.getNumChildren()):
+                    grandChildNode = childNode.getChild(gch)
+                    nodeName = grandChildNode.getName()
+                    nodeValue = ""
+                    if (grandChildNode.getNumChildren() == 1):
+                        nodeValue = grandChildNode.getChild(0).toXMLString()
+                    else:
+                        print(
+                            "Error: expected exactly ONE child of ", nodeName)
+
+                    if nodeName == "xCord":
+                        annotateMap[nodeName] = nodeValue
+                    if nodeName == "yCord":
+                        annotateMap[nodeName] = nodeValue
+                    if nodeName == "bgColor":
+                        annotateMap[nodeName] = nodeValue
+                    if nodeName == "textColor":
+                        annotateMap[nodeName] = nodeValue
+    return annotateMap
+
+
+def getEnzAnnotation(obj, modelAnnotaInfo, rev,
+                     globparameterIdValue, specInfoMap):
+    name = obj.getId()
+    name = name.replace(" ", "_space_")
+    # modelAnnotaInfo= {}
+    annotateMap = {}
+    if (obj.getAnnotation() is not None):
+        annoNode = obj.getAnnotation()
+        for ch in range(0, annoNode.getNumChildren()):
+            childNode = annoNode.getChild(ch)
+            if (childNode.getPrefix() ==
+                    "moose" and childNode.getName() == "EnzymaticReaction"):
+                sublist = []
+                for gch in range(0, childNode.getNumChildren()):
+                    grandChildNode = childNode.getChild(gch)
+                    nodeName = grandChildNode.getName()
+                    nodeValue = ""
+                    if (grandChildNode.getNumChildren() == 1):
+                        nodeValue = grandChildNode.getChild(0).toXMLString()
+                    else:
+                        print(
+                            "Error: expected exactly ONE child of ", nodeName)
+
+                    if nodeName == "enzyme":
+                        populatedict(annotateMap, "enzyme", nodeValue)
+
+                    elif nodeName == "complex":
+                        populatedict(annotateMap, "complex", nodeValue)
+                    elif (nodeName == "substrates"):
+                        populatedict(annotateMap, "substrates", nodeValue)
+                    elif (nodeName == "product"):
+                        populatedict(annotateMap, "product", nodeValue)
+                    elif (nodeName == "groupName"):
+                        populatedict(annotateMap, "grpName", nodeValue)
+                    elif (nodeName == "stage"):
+                        populatedict(annotateMap, "stage", nodeValue)
+                    elif (nodeName == "Group"):
+                        populatedict(annotateMap, "group", nodeValue)
+                    elif (nodeName == "xCord"):
+                        populatedict(annotateMap, "xCord", nodeValue)
+                    elif (nodeName == "yCord"):
+                        populatedict(annotateMap, "yCord", nodeValue)
+    groupName = ""
+    if 'grpName' in annotateMap:
+        groupName = list(annotateMap["grpName"])[0]
+        klaw = obj.getKineticLaw()
+        mmsg = ""
+        errorFlag, mmsg, k1, k2 = getKLaw(
+            obj, klaw, rev, globparameterIdValue, specInfoMap)
+
+        if 'substrates' in annotateMap:
+            sublist = list(annotateMap["substrates"])
+        else:
+            sublist = {}
+        if 'product' in annotateMap:
+            prdlist = list(annotateMap["product"])
+        else:
+            prdlist = {}
+
+        if list(annotateMap["stage"])[0] == '1':
+            if groupName in modelAnnotaInfo:
+                modelAnnotaInfo[groupName].update(
+                    {"enzyme": list(annotateMap["enzyme"])[0],
+                     "stage": list(annotateMap["stage"])[0],
+                     "substrate": sublist,
+                     "k1": k1,
+                     "k2": k2
+                     }
+                )
+            else:
+                modelAnnotaInfo[groupName] = {
+                    "enzyme": list(annotateMap["enzyme"])[0],
+                    "stage": list(annotateMap["stage"])[0],
+                    "substrate": sublist,
+                    "k1": k1,
+                    "k2": k2
+                    #"group" : list(annotateMap["Group"])[0],
+                    #"xCord" : list(annotateMap["xCord"])[0],
+                    #"yCord" : list(annotateMap["yCord"]) [0]
+                }
+
+        elif list(annotateMap["stage"])[0] == '2':
+            if groupName in modelAnnotaInfo:
+                stage = int(modelAnnotaInfo[groupName][
+                            "stage"]) + int(list(annotateMap["stage"])[0])
+                modelAnnotaInfo[groupName].update(
+                    {"complex": list(annotateMap["complex"])[0],
+                     "product": prdlist,
+                     "stage": [stage],
+                     "k3": k1
+                     }
+                )
+            else:
+                modelAnnotaInfo[groupName] = {
+                    "complex": list(annotateMap["complex"])[0],
+                    "product": prdlist,
+                    "stage": [stage],
+                    "k3": k1
+                }
+    return(groupName)
+
+
+def createReaction(model, specInfoMap, modelAnnotaInfo, globparameterIdValue):
+    # print " reaction "
+    # Things done for reaction
+    # --Reaction is not created, if substrate and product is missing
+    # --Reaction is created under first substrate's compartment if substrate not found then product
+    # --Reaction is created if substrate or product is missing, but while run time in GUI atleast I have stopped
+    # ToDo
+    # -- I need to check here if any substance/product is if ( constant == true && bcondition == false)
     # cout <<"The species "<< name << " should not appear in reactant or product as per sbml Rules"<< endl;
 
-	errorFlag = True
-	reactSBMLIdMooseId = {}
-	msg = ""
-	rName = ""
-	reaction_ = ""
-	
-	for ritem in range(0,model.getNumReactions()):
-		reactionCreated = False
-		groupName = ""
-		reac = model.getReaction( ritem )
-		if ( reac.isSetId() ):
-			rId = reac.getId()
-		if ( reac.isSetName() ):
-			rName = reac.getName()
-			rName = rName.replace(" ","_space_")
-		if not( rName ):
-			rName = rId
-		rev = reac.getReversible()
-		fast = reac.getFast()
-		if ( fast ):
-			print(" warning: for now fast attribute is not handled \"", rName,"\"")
-		if (reac.getAnnotation() != None):
-			groupName = getEnzAnnotation(reac,modelAnnotaInfo,rev,globparameterIdValue,specInfoMap)
-			
-		if (groupName != "" and list(modelAnnotaInfo[groupName]["stage"])[0] == 3):
-			reaction_,reactionCreated = setupEnzymaticReaction(reac,groupName,rName,specInfoMap,modelAnnotaInfo)
-			reaction_.k3 = modelAnnotaInfo[groupName]['k3']
-			reaction_.k2 = modelAnnotaInfo[groupName]['k2']
-			reaction_.concK1 = modelAnnotaInfo[groupName]['k1']
-			if reactionCreated:
-				if (reac.isSetNotes):
-					pullnotes(reac,reaction_)
-					reacAnnoInfo = {}
-				reacAnnoInfo = getObjAnnotation(reac,modelAnnotaInfo)
-				if reacAnnoInfo:
-					if not moose.exists(reaction_.path+'/info'):
-						reacInfo = moose.Annotator(reaction_.path+'/info')
-					else:
-						reacInfo = moose.element(reaction_.path+'/info')
-					for k,v in list(reacAnnoInfo.items()):
-						if k == 'xCord':
-							reacInfo.x = float(v)
-						elif k == 'yCord':
-							reacInfo.y = float(v)
-						elif k == 'bgColor':
-							reacInfo.color = v
-						else:
-							reacInfo.textColor = v
-
-
-		elif(groupName == ""):
-			numRcts = reac.getNumReactants()
-			numPdts = reac.getNumProducts()
-			nummodifiers = reac.getNumModifiers()
-			
-			if not (numRcts and numPdts):
-				print(rName," : Substrate and Product is missing, we will be skiping creating this reaction in MOOSE")
-				reactionCreated = False
-			elif (reac.getNumModifiers() > 0):
-				reactionCreated,reaction_ = setupMMEnzymeReaction(reac,rName,specInfoMap,reactSBMLIdMooseId,modelAnnotaInfo,model,globparameterIdValue)
-			# elif (reac.getNumModifiers() > 0):
-			# 	reactionCreated = setupMMEnzymeReaction(reac,rName,specInfoMap,reactSBMLIdMooseId,modelAnnotaInfo,model,globparameterIdValue)
-			# 	reaction_ = reactSBMLIdMooseId['classical']['MooseId']
-			# 	reactionType = "MMEnz"
-			elif (numRcts):
-				# In moose, reactions compartment are decided from first Substrate compartment info
-				# substrate is missing then check for product
-				if (reac.getNumReactants()):
-					react = reac.getReactant(reac.getNumReactants()-1)
-					#react = reac.getReactant(0)
-					sp = react.getSpecies()
-					sp = str(idBeginWith(sp))
-					speCompt = specInfoMap[sp]["comptId"].path
-					reaction_ = moose.Reac(speCompt+'/'+rName)
-					reactionCreated = True
-					reactSBMLIdMooseId[rName] = {"MooseId" : reaction_ , "className ": "reaction"}
-			elif (numPdts):
-				# In moose, reactions compartment are decided from first Substrate compartment info
-				# substrate is missing then check for product
-				if (reac.getNumProducts()):
-					react = reac.getProducts(0)
-					sp = react.getSpecies()
-					sp = str(idBeginWith(sp))
-					speCompt = specInfoMap[sp]["comptId"].path
-					reaction_ = moose.Reac(speCompt+'/'+rName)
-					reactionCreated = True
-					reactSBMLIdMooseId[rId] = {"MooseId" : reaction_, "className": "reaction"}
-			if reactionCreated:
-				if (reac.isSetNotes):
-					pullnotes(reac,reaction_)
-					reacAnnoInfo = {}
-				reacAnnoInfo = getObjAnnotation(reac,modelAnnotaInfo)
-				if reacAnnoInfo:
-					if not moose.exists(reaction_.path+'/info'):
-						reacInfo = moose.Annotator(reaction_.path+'/info')
-					else:
-						reacInfo = moose.element(reaction_.path+'/info')
-					for k,v in list(reacAnnoInfo.items()):
-						if k == 'xCord':
-							reacInfo.x = float(v)
-						elif k == 'yCord':
-							reacInfo.y = float(v)
-						elif k == 'bgColor':
-							reacInfo.color = v
-						else:
-							reacInfo.textColor = v
-
-				addSubPrd(reac,rName,"sub",reactSBMLIdMooseId,specInfoMap)
-				addSubPrd(reac,rName,"prd",reactSBMLIdMooseId,specInfoMap)
-				if reac.isSetKineticLaw():
-					klaw=reac.getKineticLaw();
-					mmsg = ""
-					errorFlag, mmsg,kfvalue,kbvalue = getKLaw(model,klaw,rev,globparameterIdValue,specInfoMap)
-					if not errorFlag:
-						msg = "Error while importing reaction \""+rName+"\"\n Error in kinetics law "
-						if mmsg != "":
-							msg = msg+mmsg
-						return(errorFlag,msg)
-					else:
-						#print " reactSBMLIdMooseId ",reactSBMLIdMooseId[rName]["nSub"], " prd ",reactSBMLIdMooseId[rName]["nPrd"]
-						if reaction_.className == "Reac":
-							subn = reactSBMLIdMooseId[rName]["nSub"]
-							prdn = reactSBMLIdMooseId[rName]["nPrd"]
-							reaction_.Kf = kfvalue #* pow(1e-3,subn-1)
-							reaction_.Kb = kbvalue #* pow(1e-3,prdn-1)
-						elif reaction_.className == "MMenz":
-							reaction_.kcat  = kfvalue
-							reaction_.Km = kbvalue
-	return (errorFlag,msg)
-
-def getKLaw( model, klaw, rev,globparameterIdValue,specMapList):
+    errorFlag = True
+    reactSBMLIdMooseId = {}
+    msg = ""
+    rName = ""
+    reaction_ = None
+
+    for ritem in range(0, model.getNumReactions()):
+        reactionCreated = False
+        groupName = ""
+        reac = model.getReaction(ritem)
+        if (reac.isSetId()):
+            rId = reac.getId()
+        if (reac.isSetName()):
+            rName = reac.getName()
+            rName = rName.replace(" ", "_space_")
+        if not(rName):
+            rName = rId
+        rev = reac.getReversible()
+        fast = reac.getFast()
+        if (fast):
+            print(
+                " warning: for now fast attribute is not handled \"",
+                rName,
+                "\"")
+        if (reac.getAnnotation() is not None):
+            groupName = getEnzAnnotation(
+                reac, modelAnnotaInfo, rev, globparameterIdValue, specInfoMap)
+
+        if (groupName != "" and list(
+                modelAnnotaInfo[groupName]["stage"])[0] == 3):
+            reaction_, reactionCreated = setupEnzymaticReaction(
+                reac, groupName, rName, specInfoMap, modelAnnotaInfo)
+            reaction_.k3 = modelAnnotaInfo[groupName]['k3']
+            reaction_.k2 = modelAnnotaInfo[groupName]['k2']
+            reaction_.concK1 = modelAnnotaInfo[groupName]['k1']
+            if reactionCreated:
+                if (reac.isSetNotes):
+                    pullnotes(reac, reaction_)
+                    reacAnnoInfo = {}
+                reacAnnoInfo = getObjAnnotation(reac, modelAnnotaInfo)
+                if reacAnnoInfo:
+                    if not moose.exists(reaction_.path + '/info'):
+                        reacInfo = moose.Annotator(reaction_.path + '/info')
+                    else:
+                        reacInfo = moose.element(reaction_.path + '/info')
+                    for k, v in list(reacAnnoInfo.items()):
+                        if k == 'xCord':
+                            reacInfo.x = float(v)
+                        elif k == 'yCord':
+                            reacInfo.y = float(v)
+                        elif k == 'bgColor':
+                            reacInfo.color = v
+                        else:
+                            reacInfo.textColor = v
+
+        elif(groupName == ""):
+            numRcts = reac.getNumReactants()
+            numPdts = reac.getNumProducts()
+            nummodifiers = reac.getNumModifiers()
+
+            if not (numRcts and numPdts):
+                print(
+                    rName,
+                    " : Substrate and Product is missing, we will be skiping creating this reaction in MOOSE")
+                reactionCreated = False
+            elif (reac.getNumModifiers() > 0):
+                reactionCreated, reaction_ = setupMMEnzymeReaction(
+                    reac, rName, specInfoMap, reactSBMLIdMooseId, modelAnnotaInfo, model, globparameterIdValue)
+            # elif (reac.getNumModifiers() > 0):
+            #     reactionCreated = setupMMEnzymeReaction(reac,rName,specInfoMap,reactSBMLIdMooseId,modelAnnotaInfo,model,globparameterIdValue)
+            #     reaction_ = reactSBMLIdMooseId['classical']['MooseId']
+            #     reactionType = "MMEnz"
+            elif (numRcts):
+                # In moose, reactions compartment are decided from first Substrate compartment info
+                # substrate is missing then check for product
+                if (reac.getNumReactants()):
+                    react = reac.getReactant(reac.getNumReactants() - 1)
+                    # react = reac.getReactant(0)
+                    sp = react.getSpecies()
+                    sp = str(idBeginWith(sp))
+                    speCompt = specInfoMap[sp]["comptId"].path
+                    reaction_ = moose.Reac(speCompt + '/' + rName)
+                    reactionCreated = True
+                    reactSBMLIdMooseId[rName] = {
+                        "MooseId": reaction_, "className ": "reaction"}
+            elif (numPdts):
+                # In moose, reactions compartment are decided from first Substrate compartment info
+                # substrate is missing then check for product
+                if (reac.getNumProducts()):
+                    react = reac.getProducts(0)
+                    sp = react.getSpecies()
+                    sp = str(idBeginWith(sp))
+                    speCompt = specInfoMap[sp]["comptId"].path
+                    reaction_ = moose.Reac(speCompt + '/' + rName)
+                    reactionCreated = True
+                    reactSBMLIdMooseId[rId] = {
+                        "MooseId": reaction_, "className": "reaction"}
+            if reactionCreated:
+                if (reac.isSetNotes):
+                    pullnotes(reac, reaction_)
+                    reacAnnoInfo = {}
+                reacAnnoInfo = getObjAnnotation(reac, modelAnnotaInfo)
+                if reacAnnoInfo:
+                    if not moose.exists(reaction_.path + '/info'):
+                        reacInfo = moose.Annotator(reaction_.path + '/info')
+                    else:
+                        reacInfo = moose.element(reaction_.path + '/info')
+                    for k, v in list(reacAnnoInfo.items()):
+                        if k == 'xCord':
+                            reacInfo.x = float(v)
+                        elif k == 'yCord':
+                            reacInfo.y = float(v)
+                        elif k == 'bgColor':
+                            reacInfo.color = v
+                        else:
+                            reacInfo.textColor = v
+
+                addSubPrd(reac, rName, "sub", reactSBMLIdMooseId, specInfoMap)
+                addSubPrd(reac, rName, "prd", reactSBMLIdMooseId, specInfoMap)
+                if reac.isSetKineticLaw():
+                    klaw = reac.getKineticLaw()
+                    mmsg = ""
+                    errorFlag, mmsg, kfvalue, kbvalue = getKLaw(
+                        model, klaw, rev, globparameterIdValue, specInfoMap)
+                    if not errorFlag:
+                        msg = "Error while importing reaction \"" + \
+                            rName + "\"\n Error in kinetics law "
+                        if mmsg != "":
+                            msg = msg + mmsg
+                        return(errorFlag, msg)
+                    else:
+                        # print " reactSBMLIdMooseId
+                        # ",reactSBMLIdMooseId[rName]["nSub"], " prd
+                        # ",reactSBMLIdMooseId[rName]["nPrd"]
+                        if reaction_.className == "Reac":
+                            subn = reactSBMLIdMooseId[rName]["nSub"]
+                            prdn = reactSBMLIdMooseId[rName]["nPrd"]
+                            reaction_.Kf = kfvalue  # * pow(1e-3,subn-1)
+                            reaction_.Kb = kbvalue  # * pow(1e-3,prdn-1)
+                        elif reaction_.className == "MMenz":
+                            reaction_.kcat = kfvalue
+                            reaction_.Km = kbvalue
+    return (errorFlag, msg)
+
+
+def getKLaw(model, klaw, rev, globparameterIdValue, specMapList):
     parmValueMap = {}
-    amt_Conc = "amount";
+    amt_Conc = "amount"
     value = 0.0
-    np = klaw. getNumParameters();
+    np = klaw. getNumParameters()
     for pi in range(0, np):
         p = klaw.getParameter(pi)
-        if ( p.isSetId() ):
+        if (p.isSetId()):
             ids = p.getId()
-        if ( p.isSetValue() ):
+        if (p.isSetValue()):
             value = p.getValue()
         parmValueMap[ids] = value
     ruleMemlist = []
-    flag = getMembers(klaw.getMath(),ruleMemlist)
-    index = 0 
+    flag = getMembers(klaw.getMath(), ruleMemlist)
+    index = 0
     kfparm = ""
     kbparm = ""
     kfvalue = 0
-    kbvalue = 0 
-    kfp = ""
-    kbp = ""
-    mssgstr =  ""
+    kbvalue = 0
+    kfp = None
+    kbp = None
+    mssgstr = ""
     for i in ruleMemlist:
-    	if i in parmValueMap or i in globparameterIdValue:
-    		if index == 0:
-    			kfparm = i
-    			if i in parmValueMap:
-    				kfvalue = parmValueMap[i]
-    				kfp = klaw.getParameter(kfparm)
-    			else:
-    				kfvalue = globparameterIdValue[i]
-    				kfp = model.getParameter(kfparm)
-    		elif index == 1:
-    			kbparm = i
-    			if i in parmValueMap:
-    				kbvalue = parmValueMap[i]
-    				kbp = klaw.getParameter(kbparm)
-    			else:
-    				kbvalue = globparameterIdValue[i]
-    				kbp = model.getParameter(kbparm)
-    		index += 1
-
-    	elif not (i in specMapList or i in comptSbmlidMooseIdMap):
-    		mssgstr = "\""+i+ "\" is not defined "
-    		return ( False, mssgstr)
+        if i in parmValueMap or i in globparameterIdValue:
+            if index == 0:
+                kfparm = i
+                if i in parmValueMap:
+                    kfvalue = parmValueMap[i]
+                    kfp = klaw.getParameter(kfparm)
+                else:
+                    kfvalue = globparameterIdValue[i]
+                    kfp = model.getParameter(kfparm)
+            elif index == 1:
+                kbparm = i
+                if i in parmValueMap:
+                    kbvalue = parmValueMap[i]
+                    kbp = klaw.getParameter(kbparm)
+                else:
+                    kbvalue = globparameterIdValue[i]
+                    kbp = model.getParameter(kbparm)
+            index += 1
+
+        elif not (i in specMapList or i in comptSbmlidMooseIdMap):
+            mssgstr = "\"" + i + "\" is not defined "
+            return (False, mssgstr)
     if kfp != "":
-    	#print " unit set for rate law kfp ",kfparm, " ",kfp.isSetUnits()
-    	if kfp.isSetUnits():
-    		kfud = kfp.getDerivedUnitDefinition();
-    		#print " kfud ",kfud
+        # print " unit set for rate law kfp ",kfparm, " ",kfp.isSetUnits()
+        if kfp.isSetUnits():
+            kfud = kfp.getDerivedUnitDefinition()
+            # print " kfud ",kfud
     if kbp != "":
-    	pass
-    	#print " unit set for rate law kbp ",kbparm, " ",kbp.isSetUnits()
-
-    return (True,mssgstr,kfvalue,kbvalue)
-
-def getMembers(node,ruleMemlist):
-	if node.getType() == libsbml.AST_PLUS:
-		if node.getNumChildren() == 0:
-			print ("0")
-			return False
-		getMembers(node.getChild(0),ruleMemlist)
-		for i in range(1,node.getNumChildren()):
-			# addition
-			getMembers(node.getChild(i),ruleMemlist)
-	elif node.getType() == libsbml.AST_REAL:
-		#This will be constant
-		pass
-	elif node.getType() == libsbml.AST_NAME:
-		#This will be the ci term"
-		ruleMemlist.append(node.getName())
-	elif node.getType() == libsbml.AST_MINUS:
-		if node.getNumChildren() == 0:
-			print("0")
-			return False
-		else:
-			lchild = node.getLeftChild();
-			getMembers(lchild,ruleMemlist)
-			rchild = node.getRightChild();
-			getMembers(rchild,ruleMemlist)
-	elif node.getType() == libsbml.AST_DIVIDE:
-		
-		if node.getNumChildren() == 0:
-			print("0")
-			return False
-		else:
-			lchild = node.getLeftChild();
-			getMembers(lchild,ruleMemlist)
-			rchild = node.getRightChild();
-			getMembers(rchild,ruleMemlist)
-	
-	elif node.getType() == libsbml.AST_TIMES:
-		if node.getNumChildren() == 0:
-			print ("0")
-			return False
-		getMembers(node.getChild(0),ruleMemlist)
-		for i in range(1,node.getNumChildren()):
-			# Multiplication
-			getMembers(node.getChild(i),ruleMemlist)
-	
-	elif node.getType() == libsbml.AST_FUNCTION_POWER:
-		pass
-	else:
-
-		print(" this case need to be handled",node.getType())
-	# if len(ruleMemlist) > 2:
-	# 	print "Sorry! for now MOOSE cannot handle more than 2 parameters"
+        pass
+        # print " unit set for rate law kbp ",kbparm, " ",kbp.isSetUnits()
+
+    return (True, mssgstr, kfvalue, kbvalue)
+
+
+def getMembers(node, ruleMemlist):
+    if node.getType() == libsbml.AST_PLUS:
+        if node.getNumChildren() == 0:
+            print ("0")
+            return False
+        getMembers(node.getChild(0), ruleMemlist)
+        for i in range(1, node.getNumChildren()):
+            # addition
+            getMembers(node.getChild(i), ruleMemlist)
+    elif node.getType() == libsbml.AST_REAL:
+        # This will be constant
+        pass
+    elif node.getType() == libsbml.AST_NAME:
+        # This will be the ci term"
+        ruleMemlist.append(node.getName())
+    elif node.getType() == libsbml.AST_MINUS:
+        if node.getNumChildren() == 0:
+            print("0")
+            return False
+        else:
+            lchild = node.getLeftChild()
+            getMembers(lchild, ruleMemlist)
+            rchild = node.getRightChild()
+            getMembers(rchild, ruleMemlist)
+    elif node.getType() == libsbml.AST_DIVIDE:
+
+        if node.getNumChildren() == 0:
+            print("0")
+            return False
+        else:
+            lchild = node.getLeftChild()
+            getMembers(lchild, ruleMemlist)
+            rchild = node.getRightChild()
+            getMembers(rchild, ruleMemlist)
+
+    elif node.getType() == libsbml.AST_TIMES:
+        if node.getNumChildren() == 0:
+            print ("0")
+            return False
+        getMembers(node.getChild(0), ruleMemlist)
+        for i in range(1, node.getNumChildren()):
+            # Multiplication
+            getMembers(node.getChild(i), ruleMemlist)
+
+    elif node.getType() == libsbml.AST_FUNCTION_POWER:
+        pass
+    else:
+
+        print(" this case need to be handled", node.getType())
+    # if len(ruleMemlist) > 2:
+    #     print "Sorry! for now MOOSE cannot handle more than 2 parameters"
  #        return True
 
-def createRules(model,specInfoMap,globparameterIdValue):
-	for r in range(0,model.getNumRules()):
-		rule = model.getRule(r)
-		comptvolume = []
-		if (rule.isAssignment()):
-			rule_variable = rule.getVariable();
-			rule_variable = parentSp = str(idBeginWith(rule_variable))
-			poolList = specInfoMap[rule_variable]["Mpath"].path
-			poolsCompt = findCompartment(moose.element(poolList))
-			if not isinstance(moose.element(poolsCompt),moose.ChemCompt):
-				return -2
-			else:
-				if poolsCompt.name not in comptvolume:
-					comptvolume.append(poolsCompt.name)
-
-			funcId = moose.Function(poolList+'/func')
-			
-			objclassname = moose.element(poolList).className
-			if  objclassname == "BufPool" or objclassname == "ZombieBufPool":
-				moose.connect( funcId, 'valueOut', poolList ,'setN' )
-			elif  objclassname == "Pool" or objclassname == "ZombiePool":
-				#moose.connect( funcId, 'valueOut', poolList ,'increament' )
-				moose.connect(funcId, 'valueOut', poolList ,'setN' )
-			elif  objclassname == "Reac" or objclassname == "ZombieReac":
-				moose.connect( funcId, 'valueOut', poolList ,'setNumkf' )	
-			
-			ruleMath = rule.getMath()
-			ruleMemlist = []
-			speFunXterm = {}
-			getMembers(ruleMath,ruleMemlist)
-			
-			for i in ruleMemlist:
-
-				if (i in specInfoMap):
-					i = str(idBeginWith(i))
-					specMapList = specInfoMap[i]["Mpath"]
-					poolsCompt = findCompartment(moose.element(specMapList))
-					if not isinstance(moose.element(poolsCompt),moose.ChemCompt):
-						return -2
-					else:
-						if poolsCompt.name not in comptvolume:
-							comptvolume.append(poolsCompt.name)
-					numVars = funcId.numVars
-					x = funcId.path+'/x['+str(numVars)+']'
-					speFunXterm[i] = 'x'+str(numVars)
-					moose.connect(specMapList , 'nOut', x, 'input' )
-					funcId.numVars = numVars +1
-
-				elif not(i in globparameterIdValue):
-					print("check the variable type ",i)
-			exp = rule.getFormula()
-			for mem in ruleMemlist:
-				if ( mem in specInfoMap):
-					exp1 = exp.replace(mem,str(speFunXterm[mem]))
-					exp = exp1
-				elif( mem in globparameterIdValue):
-					exp1 = exp.replace(mem,str(globparameterIdValue[mem]))
-					exp = exp1
-				else:
-					print("Math expression need to be checked")
-			exp = exp.replace(" ","")
-			funcId.expr = exp.strip(" \t\n\r")
-			#return True
-
-		elif( rule.isRate() ):
-			print("Warning : For now this \"",rule.getVariable(), "\" rate Rule is not handled in moose ")
-			#return False
-
-		elif ( rule.isAlgebraic() ):
-			print("Warning: For now this " ,rule.getVariable()," Algebraic Rule is not handled in moose")
-			#return False
-		if len(comptvolume) >1:
-			warning = "\nFunction ",moose.element(poolList).name," has input from different compartment which is depricated in moose and running this model cause moose to crash"
-	return True
-
-def pullnotes(sbmlId,mooseId):
-	if sbmlId.getNotes() != None:
-		tnodec = ((sbmlId.getNotes()).getChild(0)).getChild(0)
-		notes = tnodec.getCharacters()
-		notes = notes.strip(' \t\n\r')
-		objPath = mooseId.path+"/info"
-		if not moose.exists(objPath):
-			objInfo = moose.Annotator(mooseId.path+'/info')
-		else:
-			objInfo = moose.element(mooseId.path+'/info')
-		objInfo.notes = notes
-
-def createSpecies(basePath,model,comptSbmlidMooseIdMap,specInfoMap,modelAnnotaInfo):
-	# ToDo:
-	# - Need to add group name if exist in pool
-	# - Notes
-	# print "species "
-
-	if not 	(model.getNumSpecies()):
-		return False
-	else:
-		for sindex in range(0,model.getNumSpecies()):
-			spe = model.getSpecies(sindex)
-			sName = None
-			sId = spe.getId()
-			if spe.isSetName():
-				sName = spe.getName()
-				sName = sName.replace(" ","_space_")
-
-			if spe.isSetCompartment():
-				comptId = spe.getCompartment()
-
-			if not( sName ):
-				sName = sId
-
-			constant = spe.getConstant()
-			boundaryCondition = spe.getBoundaryCondition()
-			comptEl = comptSbmlidMooseIdMap[comptId]["MooseId"].path
-			hasonlySubUnit = spe.getHasOnlySubstanceUnits();
-			# "false": is {unit of amount}/{unit of size} (i.e., concentration or density). 
-			# "true": then the value is interpreted as having a unit of amount only.
-			
-			if (boundaryCondition):
-				poolId = moose.BufPool(comptEl+'/'+sName)
-			else:
-				poolId = moose.Pool(comptEl+'/'+sName)
-			
-			if (spe.isSetNotes):
-				pullnotes(spe,poolId)
-			specAnnoInfo = {}
-			specAnnoInfo = getObjAnnotation(spe,modelAnnotaInfo)
-			if specAnnoInfo:
-				if not moose.exists(poolId.path+'/info'):
-					poolInfo = moose.Annotator(poolId.path+'/info')
-				else:
-					poolInfo = moose.element(poolId.path+'/info')
-				for k,v in list(specAnnoInfo.items()):
-					if k == 'xCord':
-						poolInfo.x = float(v)
-					elif k == 'yCord':
-						poolInfo.y = float(v)
-					elif k == 'bgColor':
-						poolInfo.color = v
-					else:
-						poolInfo.textColor = v
-
-			specInfoMap[sId] = {"Mpath" : poolId, "const" : constant, "bcondition" : boundaryCondition, "hassubunit" : hasonlySubUnit, "comptId" : comptSbmlidMooseIdMap[comptId]["MooseId"]}
-			initvalue = 0.0
-			unitfactor,unitset,unittype = transformUnit(spe,hasonlySubUnit)
-			if hasonlySubUnit == True:
-				if spe.isSetInitialAmount():
-					initvalue = spe.getInitialAmount()
-					# populating nInit, will automatically calculate the concInit.
-					if not (unitset):
-						# if unit is not set,
-						# default unit is assumed as Mole in SBML
-						unitfactor = pow(6.0221409e23,1)
-						unittype = "Mole"
-
-					initvalue = initvalue * unitfactor
-				elif spe.isSetInitialConcentration():
-					initvalue = spe.getInitialConcentration()
-					print(" Since hasonlySubUnit is true and concentration is set units are not checked")
-				poolId.nInit = initvalue
-
-			elif hasonlySubUnit == False:
-				#ToDo : check 00976
-				if spe.isSetInitialAmount():
-					initvalue = spe.getInitialAmount()
-					#initAmount is set we need to convert to concentration
-					initvalue = initvalue / comptSbmlidMooseIdMap[comptId]["size"]
-
-				elif spe.isSetInitialConcentration():
-					initvalue = spe.getInitialConcentration()
-				if not unitset:
-					#print " unit is not set"
-					unitfactor  = power(10,-3)
-
-				initvalue = initvalue * unitfactor
-				poolId.concInit = initvalue
-			else:
-				nr = model.getNumRules()
-				found = False
-				for nrItem in range(0,nr):
-					rule = model.getRule(nrItem)
-					assignRule = rule.isAssignment()
-					if ( assignRule ):
-						rule_variable = rule.getVariable()
-						if (rule_variable == sId):
-							found = True
-							break
-				if not (found):
-					print("Invalid SBML: Either initialConcentration or initialAmount must be set or it should be found in assignmentRule but non happening for ",sName)
-					return False
-
-
-	return True
-
-def transformUnit(unitForObject,hasonlySubUnit=False):
-	#print "unit ",UnitDefinition.printUnits(unitForObject.getDerivedUnitDefinition())
-	unitset = False
-	unittype = None
-	if (unitForObject.getDerivedUnitDefinition()):
-		unit = (unitForObject.getDerivedUnitDefinition())
-		unitnumber = int(unit.getNumUnits())
-		if unitnumber > 0:
-			for ui in range(0,unit.getNumUnits()):
-				lvalue = 1.0			
-				unitType =  unit.getUnit(ui)
-				if( unitType.isLitre()):
-					exponent = unitType.getExponent()
-					multiplier = unitType.getMultiplier()
-					scale = unitType.getScale()
-					offset = unitType.getOffset()
-					#units for compartment is Litre but MOOSE compartment is m3
-					scale = scale-3
-					lvalue *= pow( multiplier * pow(10.0,scale), exponent ) + offset;
-					unitset = True
-					unittype = "Litre"
-					return (lvalue,unitset,unittype)
-				elif( unitType.isMole()):
-					exponent = unitType.getExponent()
-					multiplier = unitType.getMultiplier()
-					scale = unitType.getScale()
-					offset = unitType.getOffset()
-					#if hasOnlySubstanceUnit = True, then assuming Amount
-					if hasonlySubUnit == True:
-						lvalue *= pow(multiplier * pow(10.0,scale),exponent) + offset
-						#If SBML units are in mole then convert to number by multiplying with avogadro's number
-						lvalue = lvalue * pow(6.0221409e23,1)
-					elif hasonlySubUnit == False: 
-						#Pool units in moose is mM
-						if scale > 0:
-							lvalue *= pow( multiplier * pow(10.0,scale-3), exponent ) + offset;
-						elif scale <= 0:
-							lvalue *= pow( multiplier * pow(10.0,scale+3), exponent ) + offset;
-					unitset = True
-					unittype = "Mole"
-					return (lvalue,unitset,unittype)
-		
-				elif( unitType.isItem()):
-					exponent = unitType.getExponent()
-					multiplier = unitType.getMultiplier()
-					scale = unitType.getScale()
-					offset = unitType.getOffset()
-					#if hasOnlySubstanceUnit = True, then assuming Amount
-					if hasonlySubUnit == True:
-						#If SBML units are in Item then amount is populate as its
-						lvalue *= pow( multiplier * pow(10.0,scale), exponent ) + offset;
-					if hasonlySubUnit == False:
-						# hasonlySubUnit is False, which is assumed concentration, 
-						# Here Item is converted to mole by dividing by avogadro and at initiavalue divided by volume"
-						lvalue *= pow( multiplier * pow(10.0,scale), exponent ) + offset;
-						lvalue = lvalue/pow(6.0221409e23,1)
-					unitset = True
-					unittype = "Item"
-					return (lvalue,unitset,unittype)
-		else:
-			lvalue = 1.0
-	return (lvalue,unitset,unittype)
-def createCompartment(basePath,model,comptSbmlidMooseIdMap):
-	#ToDoList : Check what should be done for the spaitialdimension is 2 or 1, area or length
-	if not(model.getNumCompartments()):
-		return False
-	else:
-		for c in range(0,model.getNumCompartments()):
-			compt = model.getCompartment(c)
-			# print("Compartment " + str(c) + ": "+ UnitDefinition.printUnits(compt.getDerivedUnitDefinition()))
-			msize = 0.0
-			unitfactor = 1.0
-			sbmlCmptId = None
-			name = None
-
-			if ( compt.isSetId() ):
-				sbmlCmptId = compt.getId()
-				
-			if ( compt.isSetName() ):
-				name = compt.getName()
-				name = name.replace(" ","_space")
-					
-			if ( compt.isSetOutside() ):
-				outside = compt.getOutside()
-					
-			if ( compt.isSetSize() ):
-				msize = compt.getSize()
-				if msize == 1:
-					print("Compartment size is 1")
-
-			dimension = compt.getSpatialDimensions();
-			if dimension == 3:
-				unitfactor,unitset, unittype = transformUnit(compt)
-				
-			else:
-				print(" Currently we don't deal with spatial Dimension less than 3 and unit's area or length")
-				return False
-
-			if not( name ):
-				name = sbmlCmptId
-			
-			mooseCmptId = moose.CubeMesh(basePath.path+'/'+name)
-			mooseCmptId.volume = (msize*unitfactor)
-			comptSbmlidMooseIdMap[sbmlCmptId]={"MooseId": mooseCmptId, "spatialDim":dimension, "size" : msize}
-	return True
-def setupMMEnzymeReaction(reac,rName,specInfoMap,reactSBMLIdMooseId,modelAnnotaInfo,model,globparameterIdValue):
-	msg = ""
-	errorFlag = ""
-	numRcts = reac.getNumReactants()
-	numPdts = reac.getNumProducts()
-	nummodifiers = reac.getNumModifiers()
-	if (nummodifiers):
-		parent = reac.getModifier(0)
-		parentSp = parent.getSpecies()
-		parentSp = str(idBeginWith(parentSp))
-		enzParent = specInfoMap[parentSp]["Mpath"]
-		MMEnz = moose.MMenz(enzParent.path+'/'+rName)
-		moose.connect(enzParent,"nOut",MMEnz,"enzDest");
-		reactionCreated = True
-		reactSBMLIdMooseId[rName] = { "MooseId":MMEnz, "className":"MMEnz"}
-		if reactionCreated:
-			if (reac.isSetNotes):
-				pullnotes(reac,MMEnz)
-				reacAnnoInfo = {}
-				reacAnnoInfo = getObjAnnotation(reac,modelAnnotaInfo)
-				if reacAnnoInfo:
-					if not moose.exists(MMEnz.path+'/info'):
-						reacInfo = moose.Annotator(MMEnz.path+'/info')
-					else:
-						reacInfo = moose.element(MMEnz.path+'/info')
-					for k,v in list(reacAnnoInfo.items()):
-						if k == 'xCord':
-							reacInfo.x = float(v)
-						elif k == 'yCord':
-							reacInfo.y = float(v)
-						elif k == 'bgColor':
-							reacInfo.color = v
-						else:
-							reacInfo.textColor = v
-			return(reactionCreated,MMEnz)
-
-def mapParameter(model,globparameterIdValue):
-	for pm in range(0,model.getNumParameters()):
-		prm = model.getParameter( pm );
-		if ( prm.isSetId() ):
-			parid = prm.getId()
-		value = 0.0;
-		if ( prm.isSetValue() ):
-			value = prm.getValue()
-		globparameterIdValue[parid] = value
-
-def idBeginWith( name ):
-	changedName = name;
-	if name[0].isdigit() :
-		changedName = "_"+name
-	return changedName;
+
+def createRules(model, specInfoMap, globparameterIdValue):
+    for r in range(0, model.getNumRules()):
+        rule = model.getRule(r)
+        comptvolume = []
+        if (rule.isAssignment()):
+            rule_variable = rule.getVariable()
+            rule_variable = parentSp = str(idBeginWith(rule_variable))
+            poolList = specInfoMap[rule_variable]["Mpath"].path
+            poolsCompt = findCompartment(moose.element(poolList))
+            if not isinstance(moose.element(poolsCompt), moose.ChemCompt):
+                return -2
+            else:
+                if poolsCompt.name not in comptvolume:
+                    comptvolume.append(poolsCompt.name)
+
+            funcId = moose.Function(poolList + '/func')
+
+            objclassname = moose.element(poolList).className
+            if objclassname == "BufPool" or objclassname == "ZombieBufPool":
+                moose.connect(funcId, 'valueOut', poolList, 'setN')
+            elif objclassname == "Pool" or objclassname == "ZombiePool":
+                # moose.connect( funcId, 'valueOut', poolList ,'increament' )
+                moose.connect(funcId, 'valueOut', poolList, 'setN')
+            elif objclassname == "Reac" or objclassname == "ZombieReac":
+                moose.connect(funcId, 'valueOut', poolList, 'setNumkf')
+
+            ruleMath = rule.getMath()
+            ruleMemlist = []
+            speFunXterm = {}
+            getMembers(ruleMath, ruleMemlist)
+
+            for i in ruleMemlist:
+
+                if (i in specInfoMap):
+                    i = str(idBeginWith(i))
+                    specMapList = specInfoMap[i]["Mpath"]
+                    poolsCompt = findCompartment(moose.element(specMapList))
+                    if not isinstance(moose.element(
+                            poolsCompt), moose.ChemCompt):
+                        return -2
+                    else:
+                        if poolsCompt.name not in comptvolume:
+                            comptvolume.append(poolsCompt.name)
+                    numVars = funcId.numVars
+                    x = funcId.path + '/x[' + str(numVars) + ']'
+                    speFunXterm[i] = 'x' + str(numVars)
+                    moose.connect(specMapList, 'nOut', x, 'input')
+                    funcId.numVars = numVars + 1
+
+                elif not(i in globparameterIdValue):
+                    print("check the variable type ", i)
+            exp = rule.getFormula()
+            for mem in ruleMemlist:
+                if (mem in specInfoMap):
+                    exp1 = exp.replace(mem, str(speFunXterm[mem]))
+                    exp = exp1
+                elif(mem in globparameterIdValue):
+                    exp1 = exp.replace(mem, str(globparameterIdValue[mem]))
+                    exp = exp1
+                else:
+                    print("Math expression need to be checked")
+            exp = exp.replace(" ", "")
+            funcId.expr = exp.strip(" \t\n\r")
+            # return True
+
+        elif(rule.isRate()):
+            print(
+                "Warning : For now this \"",
+                rule.getVariable(),
+                "\" rate Rule is not handled in moose ")
+            # return False
+
+        elif (rule.isAlgebraic()):
+            print("Warning: For now this ", rule.getVariable(),
+                  " Algebraic Rule is not handled in moose")
+            # return False
+        if len(comptvolume) > 1:
+            warning = "\nFunction ", moose.element(
+                poolList).name, " has input from different compartment which is depricated in moose and running this model cause moose to crash"
+    return True
+
+
+def pullnotes(sbmlId, mooseId):
+    if sbmlId.getNotes() is not None:
+        tnodec = ((sbmlId.getNotes()).getChild(0)).getChild(0)
+        notes = tnodec.getCharacters()
+        notes = notes.strip(' \t\n\r')
+        objPath = mooseId.path + "/info"
+        if not moose.exists(objPath):
+            objInfo = moose.Annotator(mooseId.path + '/info')
+        else:
+            objInfo = moose.element(mooseId.path + '/info')
+        objInfo.notes = notes
+
+
+def createSpecies(basePath, model, comptSbmlidMooseIdMap,
+                  specInfoMap, modelAnnotaInfo):
+    # ToDo:
+    # - Need to add group name if exist in pool
+    # - Notes
+    # print "species "
+
+    if not (model.getNumSpecies()):
+        return False
+    else:
+        for sindex in range(0, model.getNumSpecies()):
+            spe = model.getSpecies(sindex)
+            sName = None
+            sId = spe.getId()
+            if spe.isSetName():
+                sName = spe.getName()
+                sName = sName.replace(" ", "_space_")
+
+            if spe.isSetCompartment():
+                comptId = spe.getCompartment()
+
+            if not(sName):
+                sName = sId
+
+            constant = spe.getConstant()
+            boundaryCondition = spe.getBoundaryCondition()
+            comptEl = comptSbmlidMooseIdMap[comptId]["MooseId"].path
+            hasonlySubUnit = spe.getHasOnlySubstanceUnits()
+            # "false": is {unit of amount}/{unit of size} (i.e., concentration or density).
+            # "true": then the value is interpreted as having a unit of amount only.
+
+            if (boundaryCondition):
+                poolId = moose.BufPool(comptEl + '/' + sName)
+            else:
+                poolId = moose.Pool(comptEl + '/' + sName)
+
+            if (spe.isSetNotes):
+                pullnotes(spe, poolId)
+            specAnnoInfo = {}
+            specAnnoInfo = getObjAnnotation(spe, modelAnnotaInfo)
+            if specAnnoInfo:
+                if not moose.exists(poolId.path + '/info'):
+                    poolInfo = moose.Annotator(poolId.path + '/info')
+                else:
+                    poolInfo = moose.element(poolId.path + '/info')
+                for k, v in list(specAnnoInfo.items()):
+                    if k == 'xCord':
+                        poolInfo.x = float(v)
+                    elif k == 'yCord':
+                        poolInfo.y = float(v)
+                    elif k == 'bgColor':
+                        poolInfo.color = v
+                    else:
+                        poolInfo.textColor = v
+
+            specInfoMap[sId] = {
+                "Mpath": poolId,
+                "const": constant,
+                "bcondition": boundaryCondition,
+                "hassubunit": hasonlySubUnit,
+                "comptId": comptSbmlidMooseIdMap[comptId]["MooseId"]}
+            initvalue = 0.0
+            unitfactor, unitset, unittype = transformUnit(spe, hasonlySubUnit)
+            if hasonlySubUnit == True:
+                if spe.isSetInitialAmount():
+                    initvalue = spe.getInitialAmount()
+                    # populating nInit, will automatically calculate the
+                    # concInit.
+                    if not (unitset):
+                        # if unit is not set,
+                        # default unit is assumed as Mole in SBML
+                        unitfactor = pow(6.0221409e23, 1)
+                        unittype = "Mole"
+
+                    initvalue = initvalue * unitfactor
+                elif spe.isSetInitialConcentration():
+                    initvalue = spe.getInitialConcentration()
+                    print(
+                        " Since hasonlySubUnit is true and concentration is set units are not checked")
+                poolId.nInit = initvalue
+
+            elif hasonlySubUnit == False:
+                # ToDo : check 00976
+                if spe.isSetInitialAmount():
+                    initvalue = spe.getInitialAmount()
+                    # initAmount is set we need to convert to concentration
+                    initvalue = initvalue / \
+                        comptSbmlidMooseIdMap[comptId]["size"]
+
+                elif spe.isSetInitialConcentration():
+                    initvalue = spe.getInitialConcentration()
+                if not unitset:
+                    # print " unit is not set"
+                    unitfactor = pow(10, -3)
+
+                initvalue = initvalue * unitfactor
+                poolId.concInit = initvalue
+            else:
+                nr = model.getNumRules()
+                found = False
+                for nrItem in range(0, nr):
+                    rule = model.getRule(nrItem)
+                    assignRule = rule.isAssignment()
+                    if (assignRule):
+                        rule_variable = rule.getVariable()
+                        if (rule_variable == sId):
+                            found = True
+                            break
+                if not (found):
+                    print(
+                        "Invalid SBML: Either initialConcentration or initialAmount must be set or it should be found in assignmentRule but non happening for ",
+                        sName)
+                    return False
+
+    return True
+
+
+def transformUnit(unitForObject, hasonlySubUnit=False):
+    # print "unit
+    # ",UnitDefinition.printUnits(unitForObject.getDerivedUnitDefinition())
+    unitset = False
+    unittype = None
+    if (unitForObject.getDerivedUnitDefinition()):
+        unit = (unitForObject.getDerivedUnitDefinition())
+        unitnumber = int(unit.getNumUnits())
+        if unitnumber > 0:
+            for ui in range(0, unit.getNumUnits()):
+                lvalue = 1.0
+                unitType = unit.getUnit(ui)
+                if(unitType.isLitre()):
+                    exponent = unitType.getExponent()
+                    multiplier = unitType.getMultiplier()
+                    scale = unitType.getScale()
+                    offset = unitType.getOffset()
+                    # units for compartment is Litre but MOOSE compartment is
+                    # m3
+                    scale = scale - 3
+                    lvalue *= pow(multiplier * pow(10.0, scale),
+                                  exponent) + offset
+                    unitset = True
+                    unittype = "Litre"
+                    return (lvalue, unitset, unittype)
+                elif(unitType.isMole()):
+                    exponent = unitType.getExponent()
+                    multiplier = unitType.getMultiplier()
+                    scale = unitType.getScale()
+                    offset = unitType.getOffset()
+                    # if hasOnlySubstanceUnit = True, then assuming Amount
+                    if hasonlySubUnit == True:
+                        lvalue *= pow(multiplier *
+                                      pow(10.0, scale), exponent) + offset
+                        # If SBML units are in mole then convert to number by
+                        # multiplying with avogadro's number
+                        lvalue = lvalue * pow(6.0221409e23, 1)
+                    elif hasonlySubUnit == False:
+                        # Pool units in moose is mM
+                        if scale > 0:
+                            lvalue *= pow(multiplier * pow(10.0,
+                                                           scale - 3), exponent) + offset
+                        elif scale <= 0:
+                            lvalue *= pow(multiplier * pow(10.0,
+                                                           scale + 3), exponent) + offset
+                    unitset = True
+                    unittype = "Mole"
+                    return (lvalue, unitset, unittype)
+
+                elif(unitType.isItem()):
+                    exponent = unitType.getExponent()
+                    multiplier = unitType.getMultiplier()
+                    scale = unitType.getScale()
+                    offset = unitType.getOffset()
+                    # if hasOnlySubstanceUnit = True, then assuming Amount
+                    if hasonlySubUnit == True:
+                        # If SBML units are in Item then amount is populate as
+                        # its
+                        lvalue *= pow(multiplier *
+                                      pow(10.0, scale), exponent) + offset
+                    if hasonlySubUnit == False:
+                        # hasonlySubUnit is False, which is assumed concentration,
+                        # Here Item is converted to mole by dividing by
+                        # avogadro and at initiavalue divided by volume"
+                        lvalue *= pow(multiplier *
+                                      pow(10.0, scale), exponent) + offset
+                        lvalue = lvalue / pow(6.0221409e23, 1)
+                    unitset = True
+                    unittype = "Item"
+                    return (lvalue, unitset, unittype)
+        else:
+            lvalue = 1.0
+    return (lvalue, unitset, unittype)
+
+
+def createCompartment(basePath, model, comptSbmlidMooseIdMap):
+    # ToDoList : Check what should be done for the spaitialdimension is 2 or
+    # 1, area or length
+    if not(model.getNumCompartments()):
+        return False
+    else:
+        for c in range(0, model.getNumCompartments()):
+            compt = model.getCompartment(c)
+            # print("Compartment " + str(c) + ": "+ UnitDefinition.printUnits(compt.getDerivedUnitDefinition()))
+            msize = 0.0
+            unitfactor = 1.0
+            sbmlCmptId = None
+            name = None
+
+            if (compt.isSetId()):
+                sbmlCmptId = compt.getId()
+
+            if (compt.isSetName()):
+                name = compt.getName()
+                name = name.replace(" ", "_space")
+
+            if (compt.isSetOutside()):
+                outside = compt.getOutside()
+
+            if (compt.isSetSize()):
+                msize = compt.getSize()
+                if msize == 1:
+                    print("Compartment size is 1")
+
+            dimension = compt.getSpatialDimensions()
+            if dimension == 3:
+                unitfactor, unitset, unittype = transformUnit(compt)
+
+            else:
+                print(
+                    " Currently we don't deal with spatial Dimension less than 3 and unit's area or length")
+                return False
+
+            if not(name):
+                name = sbmlCmptId
+
+            mooseCmptId = moose.CubeMesh(basePath.path + '/' + name)
+            mooseCmptId.volume = (msize * unitfactor)
+            comptSbmlidMooseIdMap[sbmlCmptId] = {
+                "MooseId": mooseCmptId, "spatialDim": dimension, "size": msize}
+    return True
+
+
+def setupMMEnzymeReaction(reac, rName, specInfoMap, reactSBMLIdMooseId,
+                          modelAnnotaInfo, model, globparameterIdValue):
+    msg = ""
+    errorFlag = ""
+    numRcts = reac.getNumReactants()
+    numPdts = reac.getNumProducts()
+    nummodifiers = reac.getNumModifiers()
+    if (nummodifiers):
+        parent = reac.getModifier(0)
+        parentSp = parent.getSpecies()
+        parentSp = str(idBeginWith(parentSp))
+        enzParent = specInfoMap[parentSp]["Mpath"]
+        MMEnz = moose.MMenz(enzParent.path + '/' + rName)
+        moose.connect(enzParent, "nOut", MMEnz, "enzDest")
+        reactionCreated = True
+        reactSBMLIdMooseId[rName] = {"MooseId": MMEnz, "className": "MMEnz"}
+        if reactionCreated:
+            if (reac.isSetNotes):
+                pullnotes(reac, MMEnz)
+                reacAnnoInfo = {}
+                reacAnnoInfo = getObjAnnotation(reac, modelAnnotaInfo)
+                if reacAnnoInfo:
+                    if not moose.exists(MMEnz.path + '/info'):
+                        reacInfo = moose.Annotator(MMEnz.path + '/info')
+                    else:
+                        reacInfo = moose.element(MMEnz.path + '/info')
+                    for k, v in list(reacAnnoInfo.items()):
+                        if k == 'xCord':
+                            reacInfo.x = float(v)
+                        elif k == 'yCord':
+                            reacInfo.y = float(v)
+                        elif k == 'bgColor':
+                            reacInfo.color = v
+                        else:
+                            reacInfo.textColor = v
+            return(reactionCreated, MMEnz)
+
+
+def mapParameter(model, globparameterIdValue):
+    for pm in range(0, model.getNumParameters()):
+        prm = model.getParameter(pm)
+        if (prm.isSetId()):
+            parid = prm.getId()
+        value = 0.0
+        if (prm.isSetValue()):
+            value = prm.getValue()
+        globparameterIdValue[parid] = value
+
+
+def idBeginWith(name):
+    changedName = name
+    if name[0].isdigit():
+        changedName = "_" + name
+    return changedName
+
 
 def convertSpecialChar(str1):
-	d = {"&":"_and","<":"_lessthan_",">":"_greaterthan_","BEL":"&#176","-":"_minus_","'":"_prime_",
-		 "+": "_plus_","*":"_star_","/":"_slash_","(":"_bo_",")":"_bc_",
-		 "[":"_sbo_","]":"_sbc_",".":"_dot_"," ":"_"
-		}
-	for i,j in list(d.items()):
-		str1 = str1.replace(i,j)
-	return str1
+    d = {"&": "_and", "<": "_lessthan_", ">": "_greaterthan_", "BEL": "&#176", "-": "_minus_", "'": "_prime_",
+         "+": "_plus_", "*": "_star_", "/": "_slash_", "(": "_bo_", ")": "_bc_",
+         "[": "_sbo_", "]": "_sbc_", ".": "_dot_", " ": "_"
+         }
+    for i, j in list(d.items()):
+        str1 = str1.replace(i, j)
+    return str1
+
 
 def mooseIsInstance(element, classNames):
-	return moose.element(element).__class__.__name__ in classNames
+    return moose.element(element).__class__.__name__ in classNames
+
 
 def findCompartment(element):
-	while not mooseIsInstance(element,["CubeMesh","CyclMesh"]):
-		element = element.parent
-	return element
+    while not mooseIsInstance(element, ["CubeMesh", "CyclMesh"]):
+        element = element.parent
+    return element
 
 if __name__ == "__main__":
-	
-	filepath = sys.argv[1]
-	path = sys.argv[2]
-	
-	f = open(filepath, 'r')
-	
-	if path == '':
-		loadpath = filepath[filepath.rfind('/'):filepath.find('.')]
-	else:
-		loadpath = path
-	
-	read = mooseReadSBML(filepath,loadpath)
-	if read:
-		print(" Read to path",loadpath)
-	else:
-		print(" could not read  SBML to MOOSE")
+
+    filepath = sys.argv[1]
+    path = sys.argv[2]
+
+    f = open(filepath, 'r')
+
+    if path == '':
+        loadpath = filepath[filepath.rfind('/'):filepath.find('.')]
+    else:
+        loadpath = path
+
+    read = mooseReadSBML(filepath, loadpath)
+    if read:
+        print(" Read to path", loadpath)
+    else:
+        print(" could not read  SBML to MOOSE")
diff --git a/python/moose/SBML/writeSBML.py b/python/moose/SBML/writeSBML.py
index 988b8c470a94f1b7d789dd5d24e0c54e869d1dac..3057f1002b3d356114f579a195a97c0804f568b1 100644
--- a/python/moose/SBML/writeSBML.py
+++ b/python/moose/SBML/writeSBML.py
@@ -11,897 +11,1093 @@
 ** also known as GENESIS 3 base code.
 **           copyright (C) 2003-2016 Upinder S. Bhalla. and NCBS
 Created : Friday May 27 12:19:00 2016(+0530)
-Version 
+Version
 Last-Updated: Thursday Oct 27 11:20:00 2016(+0530)
 		  By:
 **********************************************************************/
 /****************************
 
 '''
-from moose import *
+
+import moose
 import re
 from collections import Counter
 import networkx as nx
 import matplotlib.pyplot as plt
 import sys
 
-#ToDo:
+# ToDo:
 #	Table should be written
 #	Group's should be added
-#	boundary condition for buffer pool having assignment statment constant shd be false
+# boundary condition for buffer pool having assignment statment constant
+# shd be false
 
-try: 
+foundLibSBML_ = False
+try:
     from libsbml import *
-except ImportError: 
-    def mooseWriteSBML(modelpath,filename,sceneitems={}):
-    	return (-2,"\n WriteSBML : python-libsbml module not installed",None)
-else:
-	def mooseWriteSBML(modelpath,filename,sceneitems={}):
-			sbmlDoc = SBMLDocument(3, 1)
-			filepath,filenameExt = os.path.split(filename)
-			if filenameExt.find('.') != -1:
-				filename = filenameExt[:filenameExt.find('.')]
-			else:
-				filename = filenameExt
-			
-			#validatemodel
-			sbmlOk = False
-			global spe_constTrue,cmin,cmax
-			spe_constTrue = []
-			global nameList_
-			nameList_ = []
-
-			autoCoordinateslayout = False
-			xmlns = XMLNamespaces()
-			xmlns.add("http://www.sbml.org/sbml/level3/version1")
-			xmlns.add("http://www.moose.ncbs.res.in","moose")
-			xmlns.add("http://www.w3.org/1999/xhtml","xhtml")
-			sbmlDoc.setNamespaces(xmlns)
-			cremodel_ = sbmlDoc.createModel()
-			cremodel_.setId(filename)
-			cremodel_.setTimeUnits("second")
-			cremodel_.setExtentUnits("substance")
-			cremodel_.setSubstanceUnits("substance")
-			neutralNotes = ""
-			specieslist = wildcardFind(modelpath+'/##[ISA=PoolBase]')
-			neutralPath = getGroupinfo(specieslist[0])
-			if moose.exists(neutralPath.path+'/info'):
-				neutralInfo = moose.element(neutralPath.path+'/info')
-				neutralNotes = neutralInfo.notes
-			if neutralNotes != "":
-				cleanNotes= convertNotesSpecialChar(neutralNotes)
-				notesString = "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n \t \t"+ neutralNotes + "\n\t </body>"
-				cremodel_.setNotes(notesString)
-			srcdesConnection = {}
-			cmin,cmax = 0,1
-
-			if not bool(sceneitems):
-				autoCoordinateslayout = True
-				srcdesConnection = setupItem(modelpath)
-				meshEntry = setupMeshObj(modelpath)
-				cmin,cmax,sceneitems = autoCoordinates(meshEntry,srcdesConnection)
-			
-			writeUnits(cremodel_)
-			modelAnno = writeSimulationAnnotation(modelpath)
-			if modelAnno:
-				cremodel_.setAnnotation(modelAnno)
-			compartexist = writeCompt(modelpath,cremodel_)
-			species = writeSpecies(modelpath,cremodel_,sbmlDoc,sceneitems,autoCoordinateslayout)
-			if species:
-				writeFunc(modelpath,cremodel_)
-			writeReac(modelpath,cremodel_,sceneitems,autoCoordinateslayout)
-			writeEnz(modelpath,cremodel_,sceneitems,autoCoordinateslayout)
-
-			consistencyMessages = ""
-			SBMLok = validateModel( sbmlDoc )
-			if ( SBMLok ):
-				writeTofile = filepath+"/"+filename+'.xml'
-				writeSBMLToFile( sbmlDoc, writeTofile)
-				return True,consistencyMessages,writeTofile
-
-			if ( not SBMLok ):
-				cerr << "Errors encountered " << endl;
-				return -1,consistencyMessages
-
-def writeEnz(modelpath,cremodel_,sceneitems,autoCoordinateslayout):
-	for enz in wildcardFind(modelpath+'/##[ISA=EnzBase]'):
-		enzannoexist = False
-		enzGpnCorCol = " "
-		cleanEnzname = convertSpecialChar(enz.name) 
-		enzSubt = ()        
-		compt = ""
-		notesE = ""
-		if moose.exists(enz.path+'/info'):
-			Anno = moose.Annotator(enz.path+'/info')
-			notesE = Anno.notes
-			element = moose.element(enz)
-			ele = getGroupinfo(element)
-			if ele.className == "Neutral" or sceneitems[element] or Anno.color or Anno.textColor:
-				enzannoexist = True
-
-			if enzannoexist :
-				if ele.className == "Neutral":
-					enzGpnCorCol = "<moose:Group> "+ ele.name + " </moose:Group>\n"
-				if sceneitems[element]:
-					v = sceneitems[element]
-					if autoCoordinateslayout == False:
-						enzGpnCorCol = enzGpnCorCol+"<moose:xCord>"+str(v['x'])+"</moose:xCord>\n"+"<moose:yCord>"+str(v['y'])+"</moose:yCord>\n"
-					elif autoCoordinateslayout == True:
-						x = calPrime(v['x'])
-						y = calPrime(v['y'])
-						enzGpnCorCol = enzGpnCorCol+"<moose:xCord>"+str(x)+"</moose:xCord>\n"+"<moose:yCord>"+str(y)+"</moose:yCord>\n"
-				if Anno.color:
-					enzGpnCorCol = enzGpnCorCol+"<moose:bgColor>"+Anno.color+"</moose:bgColor>\n"
-				if Anno.textColor:
-					enzGpnCorCol = enzGpnCorCol+"<moose:textColor>"+Anno.textColor+"</moose:textColor>\n"
-				
-		if (enz.className == "Enz" or enz.className == "ZombieEnz"):
-			enzyme = cremodel_.createReaction()
-			if notesE != "":
-				cleanNotesE= convertNotesSpecialChar(notesE)
-				notesStringE = "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n \t \t"+ cleanNotesE + "\n\t </body>"
-				enzyme.setNotes(notesStringE)
-			comptVec = findCompartment(moose.element(enz))
-			if not isinstance(moose.element(comptVec),moose.ChemCompt):
-				return -2
-			else:
-				compt = comptVec.name+"_"+str(comptVec.getId().value)+"_"+str(comptVec.getDataIndex())+"_"
-			
-			enzyme.setId(str(idBeginWith(cleanEnzname+"_"+str(enz.getId().value)+"_"+str(enz.getDataIndex())+"_"+"Complex_formation_")))
-			enzyme.setName(cleanEnzname)
-			enzyme.setFast ( False )
-			enzyme.setReversible( True)
-			k1 = enz.concK1
-			k2 = enz.k2
-			k3 = enz.k3
-			enzAnno = " "
-			enzAnno ="<moose:EnzymaticReaction>\n"
-			
-			enzOut = enz.neighbors["enzOut"]
-			
-			if not enzOut:
-				print(" Enzyme parent missing for ",enz.name)
-			else:
-				listofname(enzOut,True)
-				enzSubt = enzOut
-				for i in range(0,len(nameList_)):
-					enzAnno=enzAnno+"<moose:enzyme>"+(str(idBeginWith(convertSpecialChar(nameList_[i]))))+"</moose:enzyme>\n"
-			#noofSub,sRateLaw = getSubprd(cremodel_,True,"sub",enzSub)
-			#for i in range(0,len(nameList_)):
-			#    enzAnno=enzAnno+"<moose:enzyme>"+nameList_[i]+"</moose:enzyme>\n"
-			#rec_order  = noofSub
-			#rate_law = "k1"+"*"+sRateLaw
-			
-			enzSub = enz.neighbors["sub"]
-			if not enzSub:
-				print("Enzyme \"",enz.name,"\" substrate missing")
-			else:
-				listofname(enzSub,True)
-				enzSubt += enzSub
-				for i in range(0,len(nameList_)):
-					enzAnno= enzAnno+"<moose:substrates>"+nameList_[i]+"</moose:substrates>\n"
-			if enzSubt:    
-				rate_law = "k1"
-				noofSub,sRateLaw = getSubprd(cremodel_,True,"sub",enzSubt)
-				#rec_order = rec_order + noofSub
-				rec_order = noofSub
-				rate_law = compt+" * "+rate_law +"*"+sRateLaw
-
-			enzPrd = enz.neighbors["cplxDest"]
-			if not enzPrd:
-				print("Enzyme \"",enz.name,"\"product missing")
-			else:
-				noofPrd,sRateLaw = getSubprd(cremodel_,True,"prd",enzPrd)
-				for i in range(0,len(nameList_)):
-					enzAnno= enzAnno+"<moose:product>"+nameList_[i]+"</moose:product>\n"
-				rate_law = rate_law+ " - "+compt+"* k2"+'*'+sRateLaw 
-			
-			prd_order = noofPrd
-			enzAnno = enzAnno + "<moose:groupName>" + cleanEnzname + "_" + str(enz.getId().value) + "_" + str(enz.getDataIndex()) + "_" + "</moose:groupName>\n"
-			enzAnno = enzAnno+"<moose:stage>1</moose:stage>\n"
-			if enzannoexist:
-				enzAnno=enzAnno + enzGpnCorCol
-			enzAnno = enzAnno+ "</moose:EnzymaticReaction>"
-			enzyme.setAnnotation(enzAnno)
-			kl = enzyme.createKineticLaw()
-			kl.setFormula( rate_law )
-			kl.setNotes("<body xmlns=\"http://www.w3.org/1999/xhtml\">\n\t\t" + rate_law + "\n \t </body>")
-			punit = parmUnit( prd_order-1, cremodel_ )
-			printParameters( kl,"k2",k2,punit ) 
-			
-			unit = parmUnit( rec_order-1, cremodel_)
-			printParameters( kl,"k1",k1,unit ) 
-			enzyme = cremodel_.createReaction()
-			enzyme.setId(str(idBeginWith(cleanEnzname+"_"+str(enz.getId().value)+"_"+str(enz.getDataIndex())+"_"+"Product_formation_")))
-			enzyme.setName(cleanEnzname)
-			enzyme.setFast ( False )
-			enzyme.setReversible( False )
-			enzAnno2 = "<moose:EnzymaticReaction>"
-			
-			enzSub = enz.neighbors["cplxDest"]
-			if not enzSub:
-				print(" complex missing from ",enz.name)
-			else:
-				noofSub,sRateLaw = getSubprd(cremodel_,True,"sub",enzSub)
-				for i in range(0,len(nameList_)):
-					enzAnno2 = enzAnno2+"<moose:complex>"+nameList_[i]+"</moose:complex>\n"
-
-			enzEnz = enz.neighbors["enzOut"]
-			if not enzEnz:
-				print("Enzyme parent missing for ",enz.name)
-			else:
-				noofEnz,sRateLaw1 = getSubprd(cremodel_,True,"prd",enzEnz)
-				for i in range(0,len(nameList_)):
-					enzAnno2 = enzAnno2+"<moose:enzyme>"+nameList_[i]+"</moose:enzyme>\n"
-			enzPrd = enz.neighbors["prd"]
-			if enzPrd:
-				noofprd,sRateLaw2 = getSubprd(cremodel_,True,"prd",enzPrd)
-			else:
-				print("Enzyme \"",enz.name, "\" product missing") 
-			for i in range(0,len(nameList_)):
-				enzAnno2 = enzAnno2+"<moose:product>"+nameList_[i]+"</moose:product>\n"
-			enzAnno2 += "<moose:groupName>"+ cleanEnzname + "_" + str(enz.getId().value) + "_" + str(enz.getDataIndex())+"_" +"</moose:groupName>\n";
-			enzAnno2 += "<moose:stage>2</moose:stage> \n";
-			if enzannoexist:
-				enzAnno2 = enzAnno2 + enzGpnCorCol
-			enzAnno2 += "</moose:EnzymaticReaction>";
-			enzyme.setAnnotation( enzAnno2 );
-
-			enzrate_law = compt +" * k3" + '*'+sRateLaw;
-			kl = enzyme.createKineticLaw();
-			kl.setFormula( enzrate_law );
-			kl.setNotes("<body xmlns=\"http://www.w3.org/1999/xhtml\">\n\t\t" + enzrate_law + "\n \t </body>")
-			unit = parmUnit(noofPrd-1 ,cremodel_)
-			printParameters( kl,"k3",k3,unit ); 
-			
-		elif(enz.className == "MMenz" or enz.className == "ZombieMMenz"):
-			enzSub = enz.neighbors["sub"] 
-			enzPrd = enz.neighbors["prd"] 
-			if (len(enzSub) != 0 and len(enzPrd) != 0 ):
-				enzCompt= findCompartment(enz)
-				if not isinstance(moose.element(enzCompt),moose.ChemCompt):
-					return -2
-				else:
-					compt = enzCompt.name+"_"+str(enzCompt.getId().value)+"_"+str(enzCompt.getDataIndex())+"_"
-				enzyme = cremodel_.createReaction()
-				enzAnno = " "
-				if notesE != "":
-					cleanNotesE= convertNotesSpecialChar(notesE)
-					notesStringE = "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n \t \t"+ cleanNotesE + "\n\t </body>"
-					enzyme.setNotes(notesStringE)
-				enzyme.setId(str(idBeginWith(cleanEnzname+"_"+str(enz.getId().value)+"_"+str(enz.getDataIndex())+"_")))
-				enzyme.setName(cleanEnzname)
-				enzyme.setFast ( False )
-				enzyme.setReversible( True)
-				if enzannoexist:
-					enzAnno = enzAnno + enzGpnCorCol
-					enzAnno = "<moose:EnzymaticReaction>\n" + enzGpnCorCol + "</moose:EnzymaticReaction>";
-					enzyme.setAnnotation(enzAnno)
-				Km = enz.Km
-				kcat = enz.kcat
-				enzSub = enz.neighbors["sub"] 
-				noofSub,sRateLawS = getSubprd(cremodel_,False,"sub",enzSub)
-				#sRate_law << rate_law.str();
-				#Modifier
-				enzMod = enz.neighbors["enzDest"]
-				noofMod,sRateLawM = getSubprd(cremodel_,False,"enz",enzMod)
-				enzPrd = enz.neighbors["prd"]
-				noofPrd,sRateLawP = getSubprd(cremodel_,False,"prd",enzPrd)
-				kl = enzyme.createKineticLaw()
-				fRate_law = "kcat *" + sRateLawS + "*" + sRateLawM + "/(" + compt +" * ("+ "Km" + "+" +sRateLawS +"))"
-				kl.setFormula(fRate_law)
-				kl.setNotes("<body xmlns=\"http://www.w3.org/1999/xhtml\">\n\t\t" + fRate_law + "\n \t </body>")
-				printParameters( kl,"Km",Km,"substance" )
-				kcatUnit = parmUnit( 0,cremodel_ )
-				printParameters( kl,"kcat",kcat,kcatUnit )
-
-def printParameters( kl, k, kvalue, unit ):
-	para = kl.createParameter()
-	para.setId(str(idBeginWith( k )))
-	para.setValue( kvalue )
-	para.setUnits( unit )
-
-def parmUnit( rct_order,cremodel_ ):
-	order = rct_order
-	if order == 0:
-		unit_stream = "per_second"
-	elif order == 1:
-		unit_stream = "litre_per_mmole_per_second"
-	elif order == 2:
-		unit_stream ="litre_per_mmole_sq_per_second"
-	else:
-		unit_stream = "litre_per_mmole_"+str(rct_order)+"_per_second";
-
-	lud =cremodel_.getListOfUnitDefinitions();
-	flag = False;
-	for i in range( 0,len(lud)):
-		ud = lud.get(i);
-		if ( ud.getId() == unit_stream ):
-			flag = True;
-			break;
-	if ( not flag ):
-		unitdef = cremodel_.createUnitDefinition()
-		unitdef.setId( unit_stream)
-		#Create individual unit objects that will be put inside the UnitDefinition .
-		if order != 0 :
-			unit = unitdef.createUnit()
-			unit.setKind( UNIT_KIND_LITRE )
-			unit.setExponent( 1 )
-			unit.setMultiplier(1)
-			unit.setScale( 0 )
-			unit = unitdef.createUnit()
-			unit.setKind( UNIT_KIND_MOLE )
-			unit.setExponent( -order )
-			unit.setMultiplier(1)
-			unit.setScale( -3 )
-
-		unit = unitdef.createUnit();
-		unit.setKind( UNIT_KIND_SECOND );
-		unit.setExponent( -1 );
-		unit.setMultiplier( 1 );
-		unit.setScale ( 0 );
-	return unit_stream
-	
-def getSubprd(cremodel_,mobjEnz,type,neighborslist):
-	if type == "sub":
-		reacSub = neighborslist
-		reacSubCou = Counter(reacSub)
-
-		#print " reacSubCou ",reacSubCou,"()",len(reacSubCou)
-		noofSub = len(reacSubCou)
-		rate_law = " "
-		if reacSub:
-			rate_law = processRateLaw(reacSubCou,cremodel_,noofSub,"sub",mobjEnz)
-			return len(reacSub),rate_law
-		else:
-			return 0,rate_law
-	elif type == "prd":
-		reacPrd = neighborslist
-		reacPrdCou = Counter(reacPrd)
-		noofPrd = len(reacPrdCou)
-		rate_law = " "
-		if reacPrd:
-			rate_law = processRateLaw(reacPrdCou,cremodel_,noofPrd,"prd",mobjEnz)
-			return len(reacPrd),rate_law
-	elif type == "enz":
-		enzModifier = neighborslist
-		enzModCou = Counter(enzModifier)
-		noofMod = len(enzModCou)
-		rate_law = " "
-		if enzModifier:
-			rate_law = processRateLaw(enzModCou,cremodel_,noofMod,"Modifier",mobjEnz)
-			return len(enzModifier),rate_law
-	
-
-def processRateLaw(objectCount,cremodel,noofObj,type,mobjEnz):
-	rate_law = ""
-	nameList_[:] = []
-	for value,count in objectCount.items():
-		value = moose.element(value)
-		nameIndex = value.name+"_"+str(value.getId().value)+"_"+str(value.getDataIndex())+"_"
-		clean_name = (str(idBeginWith(convertSpecialChar(nameIndex))))
-		if mobjEnz == True:
-			nameList_.append(clean_name)
-		if type == "sub":
-			sbmlRef = cremodel.createReactant()
-		elif type == "prd":
-			sbmlRef = cremodel.createProduct()
-		elif type == "Modifier":
-			sbmlRef = cremodel.createModifier()
-			sbmlRef.setSpecies(clean_name)
-
-		if type == "sub" or type == "prd":
-			sbmlRef.setSpecies(clean_name)
-
-			sbmlRef.setStoichiometry( count)
-			if clean_name in spe_constTrue:
-				sbmlRef.setConstant(True)
-			else:
-				sbmlRef.setConstant(False)
-		if ( count == 1 ):
-			if rate_law == "":
-				rate_law = clean_name
-			else:
-				rate_law = rate_law+"*"+clean_name
-		else:
-			if rate_law == "":
-				rate_law = clean_name+"^"+str(count)
-			else:
-				rate_law = rate_law+"*"+clean_name + "^" + str(count)
-	return(rate_law)
-
-def listofname(reacSub,mobjEnz):
-	objectCount = Counter(reacSub)
-	nameList_[:] = []
-	for value,count in objectCount.items():
-		value = moose.element(value)
-		nameIndex = value.name+"_"+str(value.getId().value)+"_"+str(value.getDataIndex())+"_"
-		clean_name = convertSpecialChar(nameIndex)
-		if mobjEnz == True:
-			nameList_.append(clean_name)
-
-def writeReac(modelpath,cremodel_,sceneitems,autoCoordinateslayout):
-	for reac in wildcardFind(modelpath+'/##[ISA=ReacBase]'):
-		reacSub = reac.neighbors["sub"]
-		reacPrd = reac.neighbors["prd"]
-		if (len(reacSub) != 0  and len(reacPrd) != 0 ):
-
-			reaction = cremodel_.createReaction()
-			reacannoexist = False
-			reacGpname = " "
-			cleanReacname = convertSpecialChar(reac.name) 
-			reaction.setId(str(idBeginWith(cleanReacname+"_"+str(reac.getId().value)+"_"+str(reac.getDataIndex())+"_")))
-			reaction.setName(cleanReacname)
-			#Kf = reac.numKf
-			#Kb = reac.numKb
-			Kf = reac.Kf
-			Kb = reac.Kb
-			if Kb == 0.0:
-				reaction.setReversible( False )
-			else:
-				reaction.setReversible( True )
-			
-			reaction.setFast( False )
-			if moose.exists(reac.path+'/info'):
-				Anno = moose.Annotator(reac.path+'/info')
-				if Anno.notes != "":
-					cleanNotesR = convertNotesSpecialChar(Anno.notes)
-					notesStringR = "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n \t \t"+ cleanNotesR + "\n\t </body>"
-					reaction.setNotes(notesStringR)
-				element = moose.element(reac)
-				ele = getGroupinfo(element)
-				if ele.className == "Neutral" or sceneitems[element] or Anno.color or Anno.textColor:
-					reacannoexist = True
-				if reacannoexist :
-					reacAnno = "<moose:ModelAnnotation>\n"
-					if ele.className == "Neutral":
-						reacAnno = reacAnno + "<moose:Group>"+ ele.name + "</moose:Group>\n"
-					if sceneitems[element]:
-						v = sceneitems[element]
-						if autoCoordinateslayout == False:
-							reacAnno = reacAnno+"<moose:xCord>"+str(v['x'])+"</moose:xCord>\n"+"<moose:yCord>"+str(v['y'])+"</moose:yCord>\n"
-						elif autoCoordinateslayout == True:
-							x = calPrime(v['x'])
-							y = calPrime(v['y'])
-							reacAnno = reacAnno+"<moose:xCord>"+str(x)+"</moose:xCord>\n"+"<moose:yCord>"+str(y)+"</moose:yCord>\n"
-					if Anno.color:
-						reacAnno = reacAnno+"<moose:bgColor>"+Anno.color+"</moose:bgColor>\n"
-					if Anno.textColor:
-						reacAnno = reacAnno+"<moose:textColor>"+Anno.textColor+"</moose:textColor>\n"
-					reacAnno = reacAnno+ "</moose:ModelAnnotation>"
-					#s1.appendAnnotation(XMLNode.convertStringToXMLNode(speciAnno))
-					reaction.setAnnotation(reacAnno)
-			kl_s , sRL, pRL ,compt= "", "", "",""
-		
-			if not reacSub and not reacPrd:
-				print(" Reaction ",reac.name, "missing substrate and product")
-			else:
-				kfl = reaction.createKineticLaw()
-				if reacSub:
-					noofSub,sRateLaw = getSubprd(cremodel_,False,"sub",reacSub)
-					if noofSub:
-						comptVec = findCompartment(moose.element(reacSub[0]))
-						if not isinstance(moose.element(comptVec),moose.ChemCompt):
-							return -2
-						else:
-							compt = comptVec.name+"_"+str(comptVec.getId().value)+"_"+str(comptVec.getDataIndex())+"_"
-						cleanReacname = cleanReacname+"_"+str(reac.getId().value)+"_"+str(reac.getDataIndex())+"_"
-						kfparm = idBeginWith(cleanReacname)+"_"+"Kf"
-						sRL = compt +" * " +idBeginWith(cleanReacname) + "_Kf * " + sRateLaw
-						unit = parmUnit( noofSub-1 ,cremodel_)
-						printParameters( kfl,kfparm,Kf,unit ); 
-						#kl_s = compt+"(" +sRL
-						kl_s = sRL
-					else:
-						print(reac.name + " has no substrate")
-						return -2
-				else:
-					print(" Substrate missing for reaction ",reac.name)
-					
-				if reacPrd:
-					noofPrd,pRateLaw = getSubprd(cremodel_,False,"prd",reacPrd)
-					if  noofPrd:
-						if Kb:
-							kbparm = idBeginWith(cleanReacname)+"_"+"Kb"
-							pRL = compt +" * " +idBeginWith(cleanReacname) + "_Kb * " + pRateLaw
-							unit = parmUnit( noofPrd-1 , cremodel_)
-							printParameters( kfl,kbparm,Kb,unit );
-							#kl_s = kl_s+ "- "+pRL+")"
-							kl_s = kl_s + "-"+pRL
-					else:
-						print(reac.name + " has no product")
-						return -2
-				else:
-					print(" Product missing for reaction ",reac.name)
-			kfl.setFormula(kl_s)
-			kfl.setNotes("<body xmlns=\"http://www.w3.org/1999/xhtml\">\n\t\t" + kl_s + "\n \t </body>")
-			kfl.setFormula(kl_s)
-		else:
-			print(" Reaction ",reac.name, "missing substrate and product")
-
-def writeFunc(modelpath,cremodel_):
-	funcs = wildcardFind(modelpath+'/##[ISA=Function]')
-	#if func:
-	for func in funcs:
-		if func:
-			if func.parent.className == "CubeMesh" or func.parent.className == "CyclMesh":
-				funcEle = moose.element(moose.element(func).neighbors["valueOut"][0])
-				funcEle1 = moose.element(funcEle)
-				fName = idBeginWith(convertSpecialChar(funcEle.name+"_"+str(funcEle.getId().value)+"_"+str(funcEle.getDataIndex())+"_"))
-				expr = moose.element(func).expr
-
-			else:
-				fName = idBeginWith( convertSpecialChar(func.parent.name+"_"+str(func.parent.getId().value)+"_"+str(func.parent.getDataIndex())+"_"))
-				item = func.path+'/x[0]'
-				sumtot = moose.element(item).neighbors["input"]
-				expr = moose.element(func).expr
-				for i in range(0,len(sumtot)):
-					v ="x"+str(i)
-					if v in expr:
-						z = str(idBeginWith(str(convertSpecialChar(sumtot[i].name+"_"+str(moose.element(sumtot[i]).getId().value)+"_"+str(moose.element(sumtot[i]).getDataIndex()))+"_")))
-						expr = expr.replace(v,z)
-				
-			rule =  cremodel_.createAssignmentRule()
-			rule.setVariable( fName )
-			rule.setFormula( expr )
-			
+    foundLibSBML_ = True
+except Exception as e:
+    pass
+
+def mooseWriteSBML(modelpath, filename, sceneitems={}):
+    global foundLibSBML_ 
+    if not foundLibSBML_:
+        print('No python-libsbml found.' 
+            '\nThis module can be installed by following command in terminal:'
+            '\n\t easy_install python-libsbl'
+            )
+        return -1, msg
+
+    sbmlDoc = SBMLDocument(3, 1)
+    filepath, filenameExt = os.path.split(filename)
+    if filenameExt.find('.') != -1:
+        filename = filenameExt[:filenameExt.find('.')]
+    else:
+        filename = filenameExt
+
+    # validatemodel
+    sbmlOk = False
+    global spe_constTrue, cmin, cmax
+    spe_constTrue = []
+    global nameList_
+    nameList_ = []
+
+    autoCoordinateslayout = False
+    xmlns = XMLNamespaces()
+    xmlns.add("http://www.sbml.org/sbml/level3/version1")
+    xmlns.add("http://www.moose.ncbs.res.in", "moose")
+    xmlns.add("http://www.w3.org/1999/xhtml", "xhtml")
+    sbmlDoc.setNamespaces(xmlns)
+    cremodel_ = sbmlDoc.createModel()
+    cremodel_.setId(filename)
+    cremodel_.setTimeUnits("second")
+    cremodel_.setExtentUnits("substance")
+    cremodel_.setSubstanceUnits("substance")
+    neutralNotes = ""
+    specieslist = moose.wildcardFind(modelpath + '/##[ISA=PoolBase]')
+    neutralPath = getGroupinfo(specieslist[0])
+    if moose.exists(neutralPath.path + '/info'):
+        neutralInfo = moose.element(neutralPath.path + '/info')
+        neutralNotes = neutralInfo.notes
+    if neutralNotes != "":
+        cleanNotes = convertNotesSpecialChar(neutralNotes)
+        notesString = "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n \t \t" + \
+            neutralNotes + "\n\t </body>"
+        cremodel_.setNotes(notesString)
+    srcdesConnection = {}
+    cmin, cmax = 0, 1
+
+    if not bool(sceneitems):
+        autoCoordinateslayout = True
+        srcdesConnection = setupItem(modelpath)
+        meshEntry = setupMeshObj(modelpath)
+        cmin, cmax, sceneitems = autoCoordinates(
+            meshEntry, srcdesConnection)
+
+    writeUnits(cremodel_)
+    modelAnno = writeSimulationAnnotation(modelpath)
+    if modelAnno:
+        cremodel_.setAnnotation(modelAnno)
+    compartexist = writeCompt(modelpath, cremodel_)
+    species = writeSpecies(
+        modelpath,
+        cremodel_,
+        sbmlDoc,
+        sceneitems,
+        autoCoordinateslayout)
+    if species:
+        writeFunc(modelpath, cremodel_)
+    writeReac(modelpath, cremodel_, sceneitems, autoCoordinateslayout)
+    writeEnz(modelpath, cremodel_, sceneitems, autoCoordinateslayout)
+
+    consistencyMessages = ""
+    SBMLok = validateModel(sbmlDoc)
+    if (SBMLok):
+        writeTofile = filepath + "/" + filename + '.xml'
+        writeSBMLToFile(sbmlDoc, writeTofile)
+        return True, consistencyMessages, writeTofile
+
+    if (not SBMLok):
+        cerr << "Errors encountered " << endl
+        return -1, consistencyMessages
+
+
+def writeEnz(modelpath, cremodel_, sceneitems, autoCoordinateslayout):
+    for enz in moose.wildcardFind(modelpath + '/##[ISA=EnzBase]'):
+        enzannoexist = False
+        enzGpnCorCol = " "
+        cleanEnzname = convertSpecialChar(enz.name)
+        enzSubt = ()
+        compt = ""
+        notesE = ""
+        if moose.exists(enz.path + '/info'):
+            Anno = moose.Annotator(enz.path + '/info')
+            notesE = Anno.notes
+            element = moose.element(enz)
+            ele = getGroupinfo(element)
+            if ele.className == "Neutral" or sceneitems[
+                    element] or Anno.color or Anno.textColor:
+                enzannoexist = True
+
+            if enzannoexist:
+                if ele.className == "Neutral":
+                    enzGpnCorCol = "<moose:Group> " + ele.name + " </moose:Group>\n"
+                if sceneitems[element]:
+                    v = sceneitems[element]
+                    if autoCoordinateslayout == False:
+                        enzGpnCorCol = enzGpnCorCol + "<moose:xCord>" + \
+                            str(v['x']) + "</moose:xCord>\n" + \
+                            "<moose:yCord>" + str(v['y']) + "</moose:yCord>\n"
+                    elif autoCoordinateslayout == True:
+                        x = calPrime(v['x'])
+                        y = calPrime(v['y'])
+                        enzGpnCorCol = enzGpnCorCol + "<moose:xCord>" + \
+                            str(x) + "</moose:xCord>\n" + \
+                            "<moose:yCord>" + str(y) + "</moose:yCord>\n"
+                if Anno.color:
+                    enzGpnCorCol = enzGpnCorCol + "<moose:bgColor>" + Anno.color + "</moose:bgColor>\n"
+                if Anno.textColor:
+                    enzGpnCorCol = enzGpnCorCol + "<moose:textColor>" + \
+                        Anno.textColor + "</moose:textColor>\n"
+
+        if (enz.className == "Enz" or enz.className == "ZombieEnz"):
+            enzyme = cremodel_.createReaction()
+            if notesE != "":
+                cleanNotesE = convertNotesSpecialChar(notesE)
+                notesStringE = "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n \t \t" + \
+                    cleanNotesE + "\n\t </body>"
+                enzyme.setNotes(notesStringE)
+            comptVec = findCompartment(moose.element(enz))
+            if not isinstance(moose.element(comptVec), moose.ChemCompt):
+                return -2
+            else:
+                compt = comptVec.name + "_" + \
+                    str(comptVec.getId().value) + "_" + \
+                    str(comptVec.getDataIndex()) + "_"
+
+            enzyme.setId(str(idBeginWith(cleanEnzname +
+                                         "_" +
+                                         str(enz.getId().value) +
+                                         "_" +
+                                         str(enz.getDataIndex()) +
+                                         "_" +
+                                         "Complex_formation_")))
+            enzyme.setName(cleanEnzname)
+            enzyme.setFast(False)
+            enzyme.setReversible(True)
+            k1 = enz.concK1
+            k2 = enz.k2
+            k3 = enz.k3
+            enzAnno = " "
+            enzAnno = "<moose:EnzymaticReaction>\n"
+
+            enzOut = enz.neighbors["enzOut"]
+
+            if not enzOut:
+                print(" Enzyme parent missing for ", enz.name)
+            else:
+                listofname(enzOut, True)
+                enzSubt = enzOut
+                for i in range(0, len(nameList_)):
+                    enzAnno = enzAnno + "<moose:enzyme>" + \
+                        (str(idBeginWith(convertSpecialChar(
+                            nameList_[i])))) + "</moose:enzyme>\n"
+            #noofSub,sRateLaw = getSubprd(cremodel_,True,"sub",enzSub)
+            # for i in range(0,len(nameList_)):
+            #    enzAnno=enzAnno+"<moose:enzyme>"+nameList_[i]+"</moose:enzyme>\n"
+            #rec_order  = noofSub
+            #rate_law = "k1"+"*"+sRateLaw
+
+            enzSub = enz.neighbors["sub"]
+            if not enzSub:
+                print("Enzyme \"", enz.name, "\" substrate missing")
+            else:
+                listofname(enzSub, True)
+                enzSubt += enzSub
+                for i in range(0, len(nameList_)):
+                    enzAnno = enzAnno + "<moose:substrates>" + \
+                        nameList_[i] + "</moose:substrates>\n"
+            if enzSubt:
+                rate_law = "k1"
+                noofSub, sRateLaw = getSubprd(cremodel_, True, "sub", enzSubt)
+                #rec_order = rec_order + noofSub
+                rec_order = noofSub
+                rate_law = compt + " * " + rate_law + "*" + sRateLaw
+
+            enzPrd = enz.neighbors["cplxDest"]
+            if not enzPrd:
+                print("Enzyme \"", enz.name, "\"product missing")
+            else:
+                noofPrd, sRateLaw = getSubprd(cremodel_, True, "prd", enzPrd)
+                for i in range(0, len(nameList_)):
+                    enzAnno = enzAnno + "<moose:product>" + \
+                        nameList_[i] + "</moose:product>\n"
+                rate_law = rate_law + " - " + compt + "* k2" + '*' + sRateLaw
+
+            prd_order = noofPrd
+            enzAnno = enzAnno + "<moose:groupName>" + cleanEnzname + "_" + \
+                str(enz.getId().value) + "_" + \
+                str(enz.getDataIndex()) + "_" + "</moose:groupName>\n"
+            enzAnno = enzAnno + "<moose:stage>1</moose:stage>\n"
+            if enzannoexist:
+                enzAnno = enzAnno + enzGpnCorCol
+            enzAnno = enzAnno + "</moose:EnzymaticReaction>"
+            enzyme.setAnnotation(enzAnno)
+            kl = enzyme.createKineticLaw()
+            kl.setFormula(rate_law)
+            kl.setNotes(
+                "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n\t\t" +
+                rate_law +
+                "\n \t </body>")
+            punit = parmUnit(prd_order - 1, cremodel_)
+            printParameters(kl, "k2", k2, punit)
+
+            unit = parmUnit(rec_order - 1, cremodel_)
+            printParameters(kl, "k1", k1, unit)
+            enzyme = cremodel_.createReaction()
+            enzyme.setId(str(idBeginWith(cleanEnzname +
+                                         "_" +
+                                         str(enz.getId().value) +
+                                         "_" +
+                                         str(enz.getDataIndex()) +
+                                         "_" +
+                                         "Product_formation_")))
+            enzyme.setName(cleanEnzname)
+            enzyme.setFast(False)
+            enzyme.setReversible(False)
+            enzAnno2 = "<moose:EnzymaticReaction>"
+
+            enzSub = enz.neighbors["cplxDest"]
+            if not enzSub:
+                print(" complex missing from ", enz.name)
+            else:
+                noofSub, sRateLaw = getSubprd(cremodel_, True, "sub", enzSub)
+                for i in range(0, len(nameList_)):
+                    enzAnno2 = enzAnno2 + "<moose:complex>" + \
+                        nameList_[i] + "</moose:complex>\n"
+
+            enzEnz = enz.neighbors["enzOut"]
+            if not enzEnz:
+                print("Enzyme parent missing for ", enz.name)
+            else:
+                noofEnz, sRateLaw1 = getSubprd(cremodel_, True, "prd", enzEnz)
+                for i in range(0, len(nameList_)):
+                    enzAnno2 = enzAnno2 + "<moose:enzyme>" + \
+                        nameList_[i] + "</moose:enzyme>\n"
+            enzPrd = enz.neighbors["prd"]
+            if enzPrd:
+                noofprd, sRateLaw2 = getSubprd(cremodel_, True, "prd", enzPrd)
+            else:
+                print("Enzyme \"", enz.name, "\" product missing")
+            for i in range(0, len(nameList_)):
+                enzAnno2 = enzAnno2 + "<moose:product>" + \
+                    nameList_[i] + "</moose:product>\n"
+            enzAnno2 += "<moose:groupName>" + cleanEnzname + "_" + \
+                str(enz.getId().value) + "_" + \
+                str(enz.getDataIndex()) + "_" + "</moose:groupName>\n"
+            enzAnno2 += "<moose:stage>2</moose:stage> \n"
+            if enzannoexist:
+                enzAnno2 = enzAnno2 + enzGpnCorCol
+            enzAnno2 += "</moose:EnzymaticReaction>"
+            enzyme.setAnnotation(enzAnno2)
+
+            enzrate_law = compt + " * k3" + '*' + sRateLaw
+            kl = enzyme.createKineticLaw()
+            kl.setFormula(enzrate_law)
+            kl.setNotes(
+                "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n\t\t" +
+                enzrate_law +
+                "\n \t </body>")
+            unit = parmUnit(noofPrd - 1, cremodel_)
+            printParameters(kl, "k3", k3, unit)
+
+        elif(enz.className == "MMenz" or enz.className == "ZombieMMenz"):
+            enzSub = enz.neighbors["sub"]
+            enzPrd = enz.neighbors["prd"]
+            if (len(enzSub) != 0 and len(enzPrd) != 0):
+                enzCompt = findCompartment(enz)
+                if not isinstance(moose.element(enzCompt), moose.ChemCompt):
+                    return -2
+                else:
+                    compt = enzCompt.name + "_" + \
+                        str(enzCompt.getId().value) + "_" + \
+                        str(enzCompt.getDataIndex()) + "_"
+                enzyme = cremodel_.createReaction()
+                enzAnno = " "
+                if notesE != "":
+                    cleanNotesE = convertNotesSpecialChar(notesE)
+                    notesStringE = "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n \t \t" + \
+                        cleanNotesE + "\n\t </body>"
+                    enzyme.setNotes(notesStringE)
+                enzyme.setId(str(idBeginWith(cleanEnzname +
+                                             "_" +
+                                             str(enz.getId().value) +
+                                             "_" +
+                                             str(enz.getDataIndex()) +
+                                             "_")))
+                enzyme.setName(cleanEnzname)
+                enzyme.setFast(False)
+                enzyme.setReversible(True)
+                if enzannoexist:
+                    enzAnno = enzAnno + enzGpnCorCol
+                    enzAnno = "<moose:EnzymaticReaction>\n" + \
+                        enzGpnCorCol + "</moose:EnzymaticReaction>"
+                    enzyme.setAnnotation(enzAnno)
+                Km = enz.Km
+                kcat = enz.kcat
+                enzSub = enz.neighbors["sub"]
+                noofSub, sRateLawS = getSubprd(cremodel_, False, "sub", enzSub)
+                #sRate_law << rate_law.str();
+                # Modifier
+                enzMod = enz.neighbors["enzDest"]
+                noofMod, sRateLawM = getSubprd(cremodel_, False, "enz", enzMod)
+                enzPrd = enz.neighbors["prd"]
+                noofPrd, sRateLawP = getSubprd(cremodel_, False, "prd", enzPrd)
+                kl = enzyme.createKineticLaw()
+                fRate_law = "kcat *" + sRateLawS + "*" + sRateLawM + \
+                    "/(" + compt + " * (" + "Km" + "+" + sRateLawS + "))"
+                kl.setFormula(fRate_law)
+                kl.setNotes(
+                    "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n\t\t" +
+                    fRate_law +
+                    "\n \t </body>")
+                printParameters(kl, "Km", Km, "substance")
+                kcatUnit = parmUnit(0, cremodel_)
+                printParameters(kl, "kcat", kcat, kcatUnit)
+
+
+def printParameters(kl, k, kvalue, unit):
+    para = kl.createParameter()
+    para.setId(str(idBeginWith(k)))
+    para.setValue(kvalue)
+    para.setUnits(unit)
+
+
+def parmUnit(rct_order, cremodel_):
+    order = rct_order
+    if order == 0:
+        unit_stream = "per_second"
+    elif order == 1:
+        unit_stream = "litre_per_mmole_per_second"
+    elif order == 2:
+        unit_stream = "litre_per_mmole_sq_per_second"
+    else:
+        unit_stream = "litre_per_mmole_" + str(rct_order) + "_per_second"
+
+    lud = cremodel_.getListOfUnitDefinitions()
+    flag = False
+    for i in range(0, len(lud)):
+        ud = lud.get(i)
+        if (ud.getId() == unit_stream):
+            flag = True
+            break
+    if (not flag):
+        unitdef = cremodel_.createUnitDefinition()
+        unitdef.setId(unit_stream)
+        # Create individual unit objects that will be put inside the
+        # UnitDefinition .
+        if order != 0:
+            unit = unitdef.createUnit()
+            unit.setKind(UNIT_KIND_LITRE)
+            unit.setExponent(1)
+            unit.setMultiplier(1)
+            unit.setScale(0)
+            unit = unitdef.createUnit()
+            unit.setKind(UNIT_KIND_MOLE)
+            unit.setExponent(-order)
+            unit.setMultiplier(1)
+            unit.setScale(-3)
+
+        unit = unitdef.createUnit()
+        unit.setKind(UNIT_KIND_SECOND)
+        unit.setExponent(-1)
+        unit.setMultiplier(1)
+        unit.setScale(0)
+    return unit_stream
+
+
+def getSubprd(cremodel_, mobjEnz, type, neighborslist):
+    if type == "sub":
+        reacSub = neighborslist
+        reacSubCou = Counter(reacSub)
+
+        # print " reacSubCou ",reacSubCou,"()",len(reacSubCou)
+        noofSub = len(reacSubCou)
+        rate_law = " "
+        if reacSub:
+            rate_law = processRateLaw(
+                reacSubCou, cremodel_, noofSub, "sub", mobjEnz)
+            return len(reacSub), rate_law
+        else:
+            return 0, rate_law
+    elif type == "prd":
+        reacPrd = neighborslist
+        reacPrdCou = Counter(reacPrd)
+        noofPrd = len(reacPrdCou)
+        rate_law = " "
+        if reacPrd:
+            rate_law = processRateLaw(
+                reacPrdCou, cremodel_, noofPrd, "prd", mobjEnz)
+            return len(reacPrd), rate_law
+    elif type == "enz":
+        enzModifier = neighborslist
+        enzModCou = Counter(enzModifier)
+        noofMod = len(enzModCou)
+        rate_law = " "
+        if enzModifier:
+            rate_law = processRateLaw(
+                enzModCou, cremodel_, noofMod, "Modifier", mobjEnz)
+            return len(enzModifier), rate_law
+
+
+def processRateLaw(objectCount, cremodel, noofObj, type, mobjEnz):
+    rate_law = ""
+    nameList_[:] = []
+    for value, count in objectCount.items():
+        value = moose.element(value)
+        nameIndex = value.name + "_" + \
+            str(value.getId().value) + "_" + str(value.getDataIndex()) + "_"
+        clean_name = (str(idBeginWith(convertSpecialChar(nameIndex))))
+        if mobjEnz == True:
+            nameList_.append(clean_name)
+        if type == "sub":
+            sbmlRef = cremodel.createReactant()
+        elif type == "prd":
+            sbmlRef = cremodel.createProduct()
+        elif type == "Modifier":
+            sbmlRef = cremodel.createModifier()
+            sbmlRef.setSpecies(clean_name)
+
+        if type == "sub" or type == "prd":
+            sbmlRef.setSpecies(clean_name)
+
+            sbmlRef.setStoichiometry(count)
+            if clean_name in spe_constTrue:
+                sbmlRef.setConstant(True)
+            else:
+                sbmlRef.setConstant(False)
+        if (count == 1):
+            if rate_law == "":
+                rate_law = clean_name
+            else:
+                rate_law = rate_law + "*" + clean_name
+        else:
+            if rate_law == "":
+                rate_law = clean_name + "^" + str(count)
+            else:
+                rate_law = rate_law + "*" + clean_name + "^" + str(count)
+    return(rate_law)
+
+
+def listofname(reacSub, mobjEnz):
+    objectCount = Counter(reacSub)
+    nameList_[:] = []
+    for value, count in objectCount.items():
+        value = moose.element(value)
+        nameIndex = value.name + "_" + \
+            str(value.getId().value) + "_" + str(value.getDataIndex()) + "_"
+        clean_name = convertSpecialChar(nameIndex)
+        if mobjEnz == True:
+            nameList_.append(clean_name)
+
+
+def writeReac(modelpath, cremodel_, sceneitems, autoCoordinateslayout):
+    for reac in moose.wildcardFind(modelpath + '/##[ISA=ReacBase]'):
+        reacSub = reac.neighbors["sub"]
+        reacPrd = reac.neighbors["prd"]
+        if (len(reacSub) != 0 and len(reacPrd) != 0):
+
+            reaction = cremodel_.createReaction()
+            reacannoexist = False
+            reacGpname = " "
+            cleanReacname = convertSpecialChar(reac.name)
+            reaction.setId(str(idBeginWith(cleanReacname +
+                                           "_" +
+                                           str(reac.getId().value) +
+                                           "_" +
+                                           str(reac.getDataIndex()) +
+                                           "_")))
+            reaction.setName(cleanReacname)
+            #Kf = reac.numKf
+            #Kb = reac.numKb
+            Kf = reac.Kf
+            Kb = reac.Kb
+            if Kb == 0.0:
+                reaction.setReversible(False)
+            else:
+                reaction.setReversible(True)
+
+            reaction.setFast(False)
+            if moose.exists(reac.path + '/info'):
+                Anno = moose.Annotator(reac.path + '/info')
+                if Anno.notes != "":
+                    cleanNotesR = convertNotesSpecialChar(Anno.notes)
+                    notesStringR = "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n \t \t" + \
+                        cleanNotesR + "\n\t </body>"
+                    reaction.setNotes(notesStringR)
+                element = moose.element(reac)
+                ele = getGroupinfo(element)
+                if ele.className == "Neutral" or sceneitems[
+                        element] or Anno.color or Anno.textColor:
+                    reacannoexist = True
+                if reacannoexist:
+                    reacAnno = "<moose:ModelAnnotation>\n"
+                    if ele.className == "Neutral":
+                        reacAnno = reacAnno + "<moose:Group>" + ele.name + "</moose:Group>\n"
+                    if sceneitems[element]:
+                        v = sceneitems[element]
+                        if autoCoordinateslayout == False:
+                            reacAnno = reacAnno + "<moose:xCord>" + \
+                                str(v['x']) + "</moose:xCord>\n" + \
+                                "<moose:yCord>" + \
+                                str(v['y']) + "</moose:yCord>\n"
+                        elif autoCoordinateslayout == True:
+                            x = calPrime(v['x'])
+                            y = calPrime(v['y'])
+                            reacAnno = reacAnno + "<moose:xCord>" + \
+                                str(x) + "</moose:xCord>\n" + \
+                                "<moose:yCord>" + str(y) + "</moose:yCord>\n"
+                    if Anno.color:
+                        reacAnno = reacAnno + "<moose:bgColor>" + Anno.color + "</moose:bgColor>\n"
+                    if Anno.textColor:
+                        reacAnno = reacAnno + "<moose:textColor>" + \
+                            Anno.textColor + "</moose:textColor>\n"
+                    reacAnno = reacAnno + "</moose:ModelAnnotation>"
+                    # s1.appendAnnotation(XMLNode.convertStringToXMLNode(speciAnno))
+                    reaction.setAnnotation(reacAnno)
+            kl_s, sRL, pRL, compt = "", "", "", ""
+
+            if not reacSub and not reacPrd:
+                print(" Reaction ", reac.name, "missing substrate and product")
+            else:
+                kfl = reaction.createKineticLaw()
+                if reacSub:
+                    noofSub, sRateLaw = getSubprd(
+                        cremodel_, False, "sub", reacSub)
+                    if noofSub:
+                        comptVec = findCompartment(moose.element(reacSub[0]))
+                        if not isinstance(moose.element(
+                                comptVec), moose.ChemCompt):
+                            return -2
+                        else:
+                            compt = comptVec.name + "_" + \
+                                str(comptVec.getId().value) + "_" + \
+                                str(comptVec.getDataIndex()) + "_"
+                        cleanReacname = cleanReacname + "_" + \
+                            str(reac.getId().value) + "_" + \
+                            str(reac.getDataIndex()) + "_"
+                        kfparm = idBeginWith(cleanReacname) + "_" + "Kf"
+                        sRL = compt + " * " + \
+                            idBeginWith(cleanReacname) + "_Kf * " + sRateLaw
+                        unit = parmUnit(noofSub - 1, cremodel_)
+                        printParameters(kfl, kfparm, Kf, unit)
+                        #kl_s = compt+"(" +sRL
+                        kl_s = sRL
+                    else:
+                        print(reac.name + " has no substrate")
+                        return -2
+                else:
+                    print(" Substrate missing for reaction ", reac.name)
+
+                if reacPrd:
+                    noofPrd, pRateLaw = getSubprd(
+                        cremodel_, False, "prd", reacPrd)
+                    if noofPrd:
+                        if Kb:
+                            kbparm = idBeginWith(cleanReacname) + "_" + "Kb"
+                            pRL = compt + " * " + \
+                                idBeginWith(cleanReacname) + \
+                                "_Kb * " + pRateLaw
+                            unit = parmUnit(noofPrd - 1, cremodel_)
+                            printParameters(kfl, kbparm, Kb, unit)
+                            #kl_s = kl_s+ "- "+pRL+")"
+                            kl_s = kl_s + "-" + pRL
+                    else:
+                        print(reac.name + " has no product")
+                        return -2
+                else:
+                    print(" Product missing for reaction ", reac.name)
+            kfl.setFormula(kl_s)
+            kfl.setNotes(
+                "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n\t\t" +
+                kl_s +
+                "\n \t </body>")
+            kfl.setFormula(kl_s)
+        else:
+            print(" Reaction ", reac.name, "missing substrate and product")
+
+
+def writeFunc(modelpath, cremodel_):
+    funcs = moose.wildcardFind(modelpath + '/##[ISA=Function]')
+    # if func:
+    for func in funcs:
+        if func:
+            if func.parent.className == "CubeMesh" or func.parent.className == "CyclMesh":
+                funcEle = moose.element(
+                    moose.element(func).neighbors["valueOut"][0])
+                funcEle1 = moose.element(funcEle)
+                fName = idBeginWith(convertSpecialChar(
+                    funcEle.name + "_" + str(funcEle.getId().value) + "_" + str(funcEle.getDataIndex()) + "_"))
+                expr = moose.element(func).expr
+
+            else:
+                fName = idBeginWith(convertSpecialChar(func.parent.name +
+                                                       "_" +
+                                                       str(func.parent.getId().value) +
+                                                       "_" +
+                                                       str(func.parent.getDataIndex()) +
+                                                       "_"))
+                item = func.path + '/x[0]'
+                sumtot = moose.element(item).neighbors["input"]
+                expr = moose.element(func).expr
+                for i in range(0, len(sumtot)):
+                    v = "x" + str(i)
+                    if v in expr:
+                        z = str(idBeginWith(str(convertSpecialChar(sumtot[i].name + "_" + str(moose.element(
+                            sumtot[i]).getId().value) + "_" + str(moose.element(sumtot[i]).getDataIndex())) + "_")))
+                        expr = expr.replace(v, z)
+
+            rule = cremodel_.createAssignmentRule()
+            rule.setVariable(fName)
+            rule.setFormula(expr)
+
+
 def convertNotesSpecialChar(str1):
-	d = {"&":"_and","<":"_lessthan_",">":"_greaterthan_","BEL":"&#176"}
-	for i,j in d.items():
-		str1 = str1.replace(i,j)
-	#stripping \t \n \r and space from begining and end of string
-	str1 = str1.strip(' \t\n\r')
-	return str1
+    d = {"&": "_and", "<": "_lessthan_", ">": "_greaterthan_", "BEL": "&#176"}
+    for i, j in d.items():
+        str1 = str1.replace(i, j)
+    # stripping \t \n \r and space from begining and end of string
+    str1 = str1.strip(' \t\n\r')
+    return str1
+
+
 def getGroupinfo(element):
-	#   Note: At this time I am assuming that if group exist (incase of Genesis)
-	#   1. for 'pool' its between compartment and pool, /modelpath/Compartment/Group/pool 
-	#   2. for 'enzComplx' in case of ExpilcityEnz its would be, /modelpath/Compartment/Group/Pool/Enz/Pool_cplx 
-	#   For these cases I have checked, but subgroup may exist then this bit of code need to cleanup further down
-	#   if /modelpath/Compartment/Group/Group1/Pool, then I check and get Group1
-	#   And /modelpath is also a NeutralObject,I stop till I find Compartment
-
-	while not mooseIsInstance(element, ["Neutral"]) and not mooseIsInstance(element,["CubeMesh","CyclMesh"]):
-		element = element.parent
-	return element
-	
+    #   Note: At this time I am assuming that if group exist (incase of Genesis)
+    #   1. for 'pool' its between compartment and pool, /modelpath/Compartment/Group/pool
+    #   2. for 'enzComplx' in case of ExpilcityEnz its would be, /modelpath/Compartment/Group/Pool/Enz/Pool_cplx
+    #   For these cases I have checked, but subgroup may exist then this bit of code need to cleanup further down
+    #   if /modelpath/Compartment/Group/Group1/Pool, then I check and get Group1
+    #   And /modelpath is also a NeutralObject,I stop till I find Compartment
+
+    while not mooseIsInstance(element, ["Neutral"]) and not mooseIsInstance(
+            element, ["CubeMesh", "CyclMesh"]):
+        element = element.parent
+    return element
+
+
 def mooseIsInstance(element, classNames):
-	return moose.element(element).__class__.__name__ in classNames
+    return moose.element(element).__class__.__name__ in classNames
+
 
 def findCompartment(element):
-	while not mooseIsInstance(element,["CubeMesh","CyclMesh"]):
-		element = element.parent
-	return element
-
-def idBeginWith( name ):
-	changedName = name;
-	if name[0].isdigit() :
-		changedName = "_"+name
-	return changedName;
-	
+    while not mooseIsInstance(element, ["CubeMesh", "CyclMesh"]):
+        element = element.parent
+    return element
+
+
+def idBeginWith(name):
+    changedName = name
+    if name[0].isdigit():
+        changedName = "_" + name
+    return changedName
+
+
 def convertSpecialChar(str1):
-	d = {"&":"_and","<":"_lessthan_",">":"_greaterthan_","BEL":"&#176","-":"_minus_","'":"_prime_",
-		 "+": "_plus_","*":"_star_","/":"_slash_","(":"_bo_",")":"_bc_",
-		 "[":"_sbo_","]":"_sbc_",".":"_dot_"," ":"_"
-		}
-	for i,j in d.items():
-		str1 = str1.replace(i,j)
-	return str1
-	
-def writeSpecies(modelpath,cremodel_,sbmlDoc,sceneitems,autoCoordinateslayout):
-	#getting all the species
-	for spe in wildcardFind(modelpath+'/##[ISA=PoolBase]'):
-		sName = convertSpecialChar(spe.name)
-		comptVec = findCompartment(spe)
-		speciannoexist = False;
-		speciGpname = ""
-
-		if not isinstance(moose.element(comptVec),moose.ChemCompt):
-			return -2
-		else:
-			compt = comptVec.name+"_"+str(comptVec.getId().value)+"_"+str(comptVec.getDataIndex())+"_"
-			s1 = cremodel_.createSpecies()
-			spename = sName+"_"+str(spe.getId().value)+"_"+str(spe.getDataIndex())+"_"
-			spename = str(idBeginWith(spename))
-			s1.setId(spename)
-			
-			if spename.find("cplx") != -1 and isinstance(moose.element(spe.parent),moose.EnzBase):
-				enz = spe.parent
-				if (moose.element(enz.parent),moose.PoolBase):
-					#print " found a cplx name ",spe.parent, moose.element(spe.parent).parent
-					enzname = enz.name
-					enzPool = (enz.parent).name
-					sName = convertSpecialChar(enzPool+"_"+enzname+"_"+sName)
-
-			
-			s1.setName(sName)
-			#s1.setInitialAmount(spe.nInit)
-			s1.setInitialConcentration(spe.concInit)
-			s1.setCompartment(compt)
-			#  Setting BoundaryCondition and constant as per this rule for BufPool
-			#  -constanst  -boundaryCondition  -has assignment/rate Rule  -can be part of sub/prd
-			#   false           true              yes                       yes   
-			#   true            true               no                       yes
-			if spe.className == "BufPool" or spe.className == "ZombieBufPool" :
-				#BoundaryCondition is made for buff pool
-				s1.setBoundaryCondition(True);
-
-				if moose.exists(spe.path+'/func'):
-					bpf = moose.element(spe.path)
-					for fp in bpf.children:
-						if fp.className =="Function" or fp.className == "ZombieFunction":
-							if len(moose.element(fp.path+'/x').neighbors["input"]) > 0:
-								s1.setConstant(False)
-							else:
-								#if function exist but sumtotal object doesn't exist
-								spe_constTrue.append(spename)
-								s1.setConstant(True)
-				else:
-					spe_constTrue.append(spename)
-					s1.setConstant(True)
-			else:
-				#if not bufpool then Pool, then 
-				s1.setBoundaryCondition(False)
-				s1.setConstant(False)
-			s1.setUnits("substance")
-			s1.setHasOnlySubstanceUnits( False )
-			if moose.exists(spe.path+'/info'):
-				Anno = moose.Annotator(spe.path+'/info')
-				if Anno.notes != "":
-					cleanNotesS= convertNotesSpecialChar(Anno.notes)
-					notesStringS = "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n \t \t"+ cleanNotesS + "\n\t </body>"
-					s1.setNotes(notesStringS)
-				
-				element = moose.element(spe)
-				ele = getGroupinfo(element)
-				if ele.className == "Neutral" or sceneitems[element] or Anno.color or Anno.textColor:
-					speciannoexist = True
-				if speciannoexist :
-					speciAnno = "<moose:ModelAnnotation>\n"
-					if ele.className == "Neutral":
-						speciAnno = speciAnno + "<moose:Group>"+ ele.name + "</moose:Group>\n"
-					if sceneitems[element]:
-						v = sceneitems[element]
-						if autoCoordinateslayout == False:
-							speciAnno = speciAnno+"<moose:xCord>"+str(v['x'])+"</moose:xCord>\n"+"<moose:yCord>"+str(v['y'])+"</moose:yCord>\n"
-						elif autoCoordinateslayout == True:
-							x = calPrime(v['x'])
-							y = calPrime(v['y'])
-							speciAnno = speciAnno+"<moose:xCord>"+str(x)+"</moose:xCord>\n"+"<moose:yCord>"+str(y)+"</moose:yCord>\n"
-					if Anno.color:
-						speciAnno = speciAnno+"<moose:bgColor>"+Anno.color+"</moose:bgColor>\n"
-					if Anno.textColor:
-						speciAnno = speciAnno+"<moose:textColor>"+Anno.textColor+"</moose:textColor>\n"
-					speciAnno = speciAnno+ "</moose:ModelAnnotation>"
-					s1.setAnnotation(speciAnno)
-	return True
-
-def writeCompt(modelpath,cremodel_):
-	#getting all the compartments
-	for compt in wildcardFind(modelpath+'/##[ISA=ChemCompt]'):
-		comptName = convertSpecialChar(compt.name)
-		#converting m3 to litre
-		size =compt.volume*pow(10,3)
-		ndim = compt.numDimensions
-		c1 = cremodel_.createCompartment()
-		c1.setId(str(idBeginWith(comptName+"_"+str(compt.getId().value)+"_"+str(compt.getDataIndex())+"_")))
-		c1.setName(comptName)                     
-		c1.setConstant(True)               
-		c1.setSize(size)          
-		c1.setSpatialDimensions(ndim)
-		c1.setUnits('volume')
-
-#write Simulation runtime,simdt,plotdt 
+    d = {"&": "_and", "<": "_lessthan_", ">": "_greaterthan_", "BEL": "&#176", "-": "_minus_", "'": "_prime_",
+         "+": "_plus_", "*": "_star_", "/": "_slash_", "(": "_bo_", ")": "_bc_",
+         "[": "_sbo_", "]": "_sbc_", ".": "_dot_", " ": "_"
+         }
+    for i, j in d.items():
+        str1 = str1.replace(i, j)
+    return str1
+
+
+def writeSpecies(modelpath, cremodel_, sbmlDoc,
+                 sceneitems, autoCoordinateslayout):
+    # getting all the species
+    for spe in moose.wildcardFind(modelpath + '/##[ISA=PoolBase]'):
+        sName = convertSpecialChar(spe.name)
+        comptVec = findCompartment(spe)
+        speciannoexist = False
+        speciGpname = ""
+
+        if not isinstance(moose.element(comptVec), moose.ChemCompt):
+            return -2
+        else:
+            compt = comptVec.name + "_" + \
+                str(comptVec.getId().value) + "_" + \
+                str(comptVec.getDataIndex()) + "_"
+            s1 = cremodel_.createSpecies()
+            spename = sName + "_" + \
+                str(spe.getId().value) + "_" + str(spe.getDataIndex()) + "_"
+            spename = str(idBeginWith(spename))
+            s1.setId(spename)
+
+            if spename.find(
+                    "cplx") != -1 and isinstance(moose.element(spe.parent), moose.EnzBase):
+                enz = spe.parent
+                if (moose.element(enz.parent), moose.PoolBase):
+                    # print " found a cplx name ",spe.parent,
+                    # moose.element(spe.parent).parent
+                    enzname = enz.name
+                    enzPool = (enz.parent).name
+                    sName = convertSpecialChar(
+                        enzPool + "_" + enzname + "_" + sName)
+
+            s1.setName(sName)
+            # s1.setInitialAmount(spe.nInit)
+            s1.setInitialConcentration(spe.concInit)
+            s1.setCompartment(compt)
+            #  Setting BoundaryCondition and constant as per this rule for BufPool
+            #  -constanst  -boundaryCondition  -has assignment/rate Rule  -can be part of sub/prd
+            #   false           true              yes                       yes
+            #   true            true               no                       yes
+            if spe.className == "BufPool" or spe.className == "ZombieBufPool":
+                # BoundaryCondition is made for buff pool
+                s1.setBoundaryCondition(True)
+
+                if moose.exists(spe.path + '/func'):
+                    bpf = moose.element(spe.path)
+                    for fp in bpf.children:
+                        if fp.className == "Function" or fp.className == "ZombieFunction":
+                            if len(moose.element(
+                                    fp.path + '/x').neighbors["input"]) > 0:
+                                s1.setConstant(False)
+                            else:
+                                # if function exist but sumtotal object doesn't
+                                # exist
+                                spe_constTrue.append(spename)
+                                s1.setConstant(True)
+                else:
+                    spe_constTrue.append(spename)
+                    s1.setConstant(True)
+            else:
+                # if not bufpool then Pool, then
+                s1.setBoundaryCondition(False)
+                s1.setConstant(False)
+            s1.setUnits("substance")
+            s1.setHasOnlySubstanceUnits(False)
+            if moose.exists(spe.path + '/info'):
+                Anno = moose.Annotator(spe.path + '/info')
+                if Anno.notes != "":
+                    cleanNotesS = convertNotesSpecialChar(Anno.notes)
+                    notesStringS = "<body xmlns=\"http://www.w3.org/1999/xhtml\">\n \t \t" + \
+                        cleanNotesS + "\n\t </body>"
+                    s1.setNotes(notesStringS)
+
+                element = moose.element(spe)
+                ele = getGroupinfo(element)
+                if ele.className == "Neutral" or sceneitems[
+                        element] or Anno.color or Anno.textColor:
+                    speciannoexist = True
+                if speciannoexist:
+                    speciAnno = "<moose:ModelAnnotation>\n"
+                    if ele.className == "Neutral":
+                        speciAnno = speciAnno + "<moose:Group>" + ele.name + "</moose:Group>\n"
+                    if sceneitems[element]:
+                        v = sceneitems[element]
+                        if autoCoordinateslayout == False:
+                            speciAnno = speciAnno + "<moose:xCord>" + \
+                                str(v['x']) + "</moose:xCord>\n" + \
+                                "<moose:yCord>" + \
+                                str(v['y']) + "</moose:yCord>\n"
+                        elif autoCoordinateslayout == True:
+                            x = calPrime(v['x'])
+                            y = calPrime(v['y'])
+                            speciAnno = speciAnno + "<moose:xCord>" + \
+                                str(x) + "</moose:xCord>\n" + \
+                                "<moose:yCord>" + str(y) + "</moose:yCord>\n"
+                    if Anno.color:
+                        speciAnno = speciAnno + "<moose:bgColor>" + Anno.color + "</moose:bgColor>\n"
+                    if Anno.textColor:
+                        speciAnno = speciAnno + "<moose:textColor>" + \
+                            Anno.textColor + "</moose:textColor>\n"
+                    speciAnno = speciAnno + "</moose:ModelAnnotation>"
+                    s1.setAnnotation(speciAnno)
+    return True
+
+
+def writeCompt(modelpath, cremodel_):
+    # getting all the compartments
+    for compt in moose.wildcardFind(modelpath + '/##[ISA=ChemCompt]'):
+        comptName = convertSpecialChar(compt.name)
+        # converting m3 to litre
+        size = compt.volume * pow(10, 3)
+        ndim = compt.numDimensions
+        c1 = cremodel_.createCompartment()
+        c1.setId(str(idBeginWith(comptName +
+                                 "_" +
+                                 str(compt.getId().value) +
+                                 "_" +
+                                 str(compt.getDataIndex()) +
+                                 "_")))
+        c1.setName(comptName)
+        c1.setConstant(True)
+        c1.setSize(size)
+        c1.setSpatialDimensions(ndim)
+        c1.setUnits('volume')
+
+# write Simulation runtime,simdt,plotdt
 def writeSimulationAnnotation(modelpath):
-	modelAnno = ""
-	plots = ""
-	if moose.exists(modelpath+'/info'):
-		mooseclock = moose.Clock('/clock')
-		modelAnno ="<moose:ModelAnnotation>\n"
-		modelAnnotation = moose.element(modelpath+'/info')
-		modelAnno = modelAnno+"<moose:runTime> "+str(modelAnnotation.runtime)+" </moose:runTime>\n"
-		modelAnno = modelAnno+"<moose:solver> "+modelAnnotation.solver+" </moose:solver>\n"
-		modelAnno = modelAnno+"<moose:simdt>"+ str(mooseclock.dts[12]) + " </moose:simdt>\n";
-		modelAnno = modelAnno+"<moose:plotdt> " + str(mooseclock.dts[18]) +" </moose:plotdt>\n";
-		plots = "";
-		graphs = moose.wildcardFind(modelpath+"/##[TYPE=Table2]")
-		for gphs in range(0,len(graphs)):
-			gpath = graphs[gphs].neighbors['requestOut']
-			if len(gpath) != 0:
-				q = moose.element(gpath[0])
-				ori = q.path
-				name = convertSpecialChar(q.name)
-				graphSpefound = False
-				while not(isinstance(moose.element(q),moose.CubeMesh)):
-					q = q.parent
-					graphSpefound = True
-				if graphSpefound:
-					if not plots:
-						#plots = ori[ori.find(q.name)-1:len(ori)]
-						plots = '/'+q.name+'/'+name
-
-					else:
-						#plots = plots + "; "+ori[ori.find(q.name)-1:len(ori)]
-						plots = plots + "; /"+q.name+'/'+name
-		if plots != " ":
-			modelAnno = modelAnno+ "<moose:plots> "+ plots+ "</moose:plots>\n";
-		modelAnno = modelAnno+"</moose:ModelAnnotation>"
-	return modelAnno
+    modelAnno = ""
+    plots = ""
+    if moose.exists(modelpath + '/info'):
+        mooseclock = moose.Clock('/clock')
+        modelAnno = "<moose:ModelAnnotation>\n"
+        modelAnnotation = moose.element(modelpath + '/info')
+        modelAnno = modelAnno + "<moose:runTime> " + \
+            str(modelAnnotation.runtime) + " </moose:runTime>\n"
+        modelAnno = modelAnno + "<moose:solver> " + \
+            modelAnnotation.solver + " </moose:solver>\n"
+        modelAnno = modelAnno + "<moose:simdt>" + \
+            str(mooseclock.dts[12]) + " </moose:simdt>\n"
+        modelAnno = modelAnno + "<moose:plotdt> " + \
+            str(mooseclock.dts[18]) + " </moose:plotdt>\n"
+        plots = ""
+        graphs = moose.wildcardFind(modelpath + "/##[TYPE=Table2]")
+        for gphs in range(0, len(graphs)):
+            gpath = graphs[gphs].neighbors['requestOut']
+            if len(gpath) != 0:
+                q = moose.element(gpath[0])
+                ori = q.path
+                name = convertSpecialChar(q.name)
+                graphSpefound = False
+                while not(isinstance(moose.element(q), moose.CubeMesh)):
+                    q = q.parent
+                    graphSpefound = True
+                if graphSpefound:
+                    if not plots:
+                        #plots = ori[ori.find(q.name)-1:len(ori)]
+                        plots = '/' + q.name + '/' + name
+
+                    else:
+                        #plots = plots + "; "+ori[ori.find(q.name)-1:len(ori)]
+                        plots = plots + "; /" + q.name + '/' + name
+        if plots != " ":
+            modelAnno = modelAnno + "<moose:plots> " + plots + "</moose:plots>\n"
+        modelAnno = modelAnno + "</moose:ModelAnnotation>"
+    return modelAnno
+
 
 def writeUnits(cremodel_):
-	unitVol = cremodel_.createUnitDefinition()
-	unitVol.setId( "volume")
-	unit = unitVol.createUnit()
-	unit.setKind(UNIT_KIND_LITRE)
-	unit.setMultiplier(1.0)
-	unit.setExponent(1.0)
-	unit.setScale(0)
-
-	unitSub = cremodel_.createUnitDefinition()
-	unitSub.setId("substance")
-	unit = unitSub.createUnit()
-	unit.setKind( UNIT_KIND_MOLE )
-	unit.setMultiplier(1)
-	unit.setExponent(1.0)
-	unit.setScale(-3)
-	
-
-def validateModel( sbmlDoc ):
-	#print " sbmlDoc ",sbmlDoc.toSBML()
-	if ( not sbmlDoc ):
-		print("validateModel: given a null SBML Document")
-		return False
-	consistencyMessages    = ""
-	validationMessages     = ""
-	noProblems             = True
-	numCheckFailures       = 0
-	numConsistencyErrors   = 0
-	numConsistencyWarnings = 0
-	numValidationErrors    = 0
-	numValidationWarnings  = 0
-	#Once the whole model is done and before it gets written out, 
-	#it's important to check that the whole model is in fact complete, consistent and valid.
-	numCheckFailures = sbmlDoc.checkInternalConsistency()
-	if ( numCheckFailures > 0 ):
-		noProblems = False
-		for i in range(0,numCheckFailures ):
-			sbmlErr = sbmlDoc.getError(i);
-			if ( sbmlErr.isFatal() or sbmlErr.isError() ):
-				++numConsistencyErrors;
-			else:
-				++numConsistencyWarnings
-		constStr = sbmlDoc.printErrors()
-		consistencyMessages = constStr
-	  
-	#If the internal checks fail, it makes little sense to attempt
-	#further validation, because the model may be too compromised to
-	#be properly interpreted.
-	if ( numConsistencyErrors > 0 ):
-		consistencyMessages += "Further validation aborted.";
-	else:
-		numCheckFailures = sbmlDoc.checkConsistency()
-		#numCheckFailures = sbmlDoc.checkL3v1Compatibility() 
-		if ( numCheckFailures > 0 ):
-			noProblems = False;
-			for i in range(0, (numCheckFailures ) ):
-				consistencyMessages = sbmlDoc.getErrorLog().toString()
-				sbmlErr = sbmlDoc.getError(i);
-				if ( sbmlErr.isFatal() or sbmlErr.isError() ):
-					++numValidationErrors;
-				else:
-					++numValidationWarnings;
-		warning = sbmlDoc.getErrorLog().toString()
-		oss = sbmlDoc.printErrors()
-		validationMessages = oss
-	if ( noProblems ):
-		return True
-	else:
-		if consistencyMessages == None:
-			consistencyMessages = ""
-		if consistencyMessages != "":
-			print(" consistency Warning: "+consistencyMessages)
-		
-		if ( numConsistencyErrors > 0 ):
-			if numConsistencyErrors == 1: t = "" 
-			else: t="s"
-			print("ERROR: encountered " + numConsistencyErrors + " consistency error" +t+ " in model '" + sbmlDoc.getModel().getId() + "'.")
-	if ( numConsistencyWarnings > 0 ):
-		if numConsistencyWarnings == 1:
-			t1 = "" 
-		else: t1 ="s"
-		print("Notice: encountered " + numConsistencyWarnings +" consistency warning" + t + " in model '" + sbmlDoc.getModel().getId() + "'.")
-	  	
-	if ( numValidationErrors > 0 ):
-		if numValidationErrors == 1:
-			t2 = "" 
-		else: t2 ="s" 
-		print("ERROR: encountered " + numValidationErrors  + " validation error" + t2 + " in model '" + sbmlDoc.getModel().getId() + "'.")
-		if ( numValidationWarnings > 0 ):
-			if numValidationWarnings == 1:
-				t3 = "" 
-			else: t3 = "s"
-
-			print("Notice: encountered " + numValidationWarnings + " validation warning" + t3 + " in model '" + sbmlDoc.getModel().getId() + "'.") 
-		
-		print(validationMessages);
-	return ( numConsistencyErrors == 0 and numValidationErrors == 0)
-	#return ( numConsistencyErrors == 0 and numValidationErrors == 0, consistencyMessages)
+    unitVol = cremodel_.createUnitDefinition()
+    unitVol.setId("volume")
+    unit = unitVol.createUnit()
+    unit.setKind(UNIT_KIND_LITRE)
+    unit.setMultiplier(1.0)
+    unit.setExponent(1.0)
+    unit.setScale(0)
+
+    unitSub = cremodel_.createUnitDefinition()
+    unitSub.setId("substance")
+    unit = unitSub.createUnit()
+    unit.setKind(UNIT_KIND_MOLE)
+    unit.setMultiplier(1)
+    unit.setExponent(1.0)
+    unit.setScale(-3)
+
+
+def validateModel(sbmlDoc):
+    # print " sbmlDoc ",sbmlDoc.toSBML()
+    if (not sbmlDoc):
+        print("validateModel: given a null SBML Document")
+        return False
+    consistencyMessages = ""
+    validationMessages = ""
+    noProblems = True
+    numCheckFailures = 0
+    numConsistencyErrors = 0
+    numConsistencyWarnings = 0
+    numValidationErrors = 0
+    numValidationWarnings = 0
+    # Once the whole model is done and before it gets written out,
+    # it's important to check that the whole model is in fact complete,
+    # consistent and valid.
+    numCheckFailures = sbmlDoc.checkInternalConsistency()
+    if (numCheckFailures > 0):
+        noProblems = False
+        for i in range(0, numCheckFailures):
+            sbmlErr = sbmlDoc.getError(i)
+            if (sbmlErr.isFatal() or sbmlErr.isError()):
+                numConsistencyErrors += 1
+            else:
+                numConsistencyWarnings += 1
+        constStr = sbmlDoc.printErrors()
+        consistencyMessages = constStr
+
+    # If the internal checks fail, it makes little sense to attempt
+    # further validation, because the model may be too compromised to
+    # be properly interpreted.
+    if (numConsistencyErrors > 0):
+        consistencyMessages += "Further validation aborted."
+    else:
+        numCheckFailures = sbmlDoc.checkConsistency()
+        #numCheckFailures = sbmlDoc.checkL3v1Compatibility()
+        if (numCheckFailures > 0):
+            noProblems = False
+            for i in range(0, (numCheckFailures)):
+                consistencyMessages = sbmlDoc.getErrorLog().toString()
+                sbmlErr = sbmlDoc.getError(i)
+                if (sbmlErr.isFatal() or sbmlErr.isError()):
+                    numValidationErrors += 1
+                else:
+                    numValidationWarnings += 1
+        warning = sbmlDoc.getErrorLog().toString()
+        oss = sbmlDoc.printErrors()
+        validationMessages = oss
+    if (noProblems):
+        return True
+    else:
+        if consistencyMessages is None:
+            consistencyMessages = ""
+        if consistencyMessages != "":
+            print(" consistency Warning: " + consistencyMessages)
+
+        if (numConsistencyErrors > 0):
+            if numConsistencyErrors == 1:
+                t = ""
+            else:
+                t = "s"
+            print(
+                "ERROR: encountered " +
+                numConsistencyErrors +
+                " consistency error" +
+                t +
+                " in model '" +
+                sbmlDoc.getModel().getId() +
+                "'.")
+    if (numConsistencyWarnings > 0):
+        if numConsistencyWarnings == 1:
+            t1 = ""
+        else:
+            t1 = "s"
+        print(
+            "Notice: encountered " +
+            numConsistencyWarnings +
+            " consistency warning" +
+            t +
+            " in model '" +
+            sbmlDoc.getModel().getId() +
+            "'.")
+
+    if (numValidationErrors > 0):
+        if numValidationErrors == 1:
+            t2 = ""
+        else:
+            t2 = "s"
+        print(
+            "ERROR: encountered " +
+            numValidationErrors +
+            " validation error" +
+            t2 +
+            " in model '" +
+            sbmlDoc.getModel().getId() +
+            "'.")
+        if (numValidationWarnings > 0):
+            if numValidationWarnings == 1:
+                t3 = ""
+            else:
+                t3 = "s"
+
+            print(
+                "Notice: encountered " +
+                numValidationWarnings +
+                " validation warning" +
+                t3 +
+                " in model '" +
+                sbmlDoc.getModel().getId() +
+                "'.")
+
+        print(validationMessages)
+    return (numConsistencyErrors == 0 and numValidationErrors == 0)
+    # return ( numConsistencyErrors == 0 and numValidationErrors == 0,
+    # consistencyMessages)
+
 
 def setupItem(modelPath):
     '''This function collects information of what is connected to what. \
     eg. substrate and product connectivity to reaction's and enzyme's \
     sumtotal connectivity to its pool are collected '''
-    #print " setupItem"
+    # print " setupItem"
     sublist = []
     prdlist = []
     cntDict = {}
-    zombieType = ['ReacBase','EnzBase','Function','StimulusTable']
+    zombieType = ['ReacBase', 'EnzBase', 'Function', 'StimulusTable']
     for baseObj in zombieType:
-        path = '/##[ISA='+baseObj+']'
+        path = '/##[ISA=' + baseObj + ']'
         if modelPath != '/':
-            path = modelPath+path
-        if ( (baseObj == 'ReacBase') or (baseObj == 'EnzBase')):
-            for items in wildcardFind(path):
+            path = modelPath + path
+        if ((baseObj == 'ReacBase') or (baseObj == 'EnzBase')):
+            for items in moose.wildcardFind(path):
                 sublist = []
                 prdlist = []
-                uniqItem,countuniqItem = countitems(items,'subOut')
+                uniqItem, countuniqItem = countitems(items, 'subOut')
                 subNo = uniqItem
-                for sub in uniqItem: 
-                    sublist.append((element(sub),'s',countuniqItem[sub]))
+                for sub in uniqItem:
+                    sublist.append((moose.element(sub), 's', countuniqItem[sub]))
 
-                uniqItem,countuniqItem = countitems(items,'prd')
+                uniqItem, countuniqItem = countitems(items, 'prd')
                 prdNo = uniqItem
                 if (len(subNo) == 0 or len(prdNo) == 0):
-                    print("Substrate Product is empty "," ",items)
+                    print("Substrate Product is empty ", " ", items)
                 for prd in uniqItem:
-                	prdlist.append((element(prd),'p',countuniqItem[prd]))
-                
-                if (baseObj == 'CplxEnzBase') :
-                    uniqItem,countuniqItem = countitems(items,'toEnz')
+                    prdlist.append((moose.element(prd), 'p', countuniqItem[prd]))
+
+                if (baseObj == 'CplxEnzBase'):
+                    uniqItem, countuniqItem = countitems(items, 'toEnz')
                     for enzpar in uniqItem:
-                        sublist.append((element(enzpar),'t',countuniqItem[enzpar]))
-                    
-                    uniqItem,countuniqItem = countitems(items,'cplxDest')
+                        sublist.append(
+                            (moose.element(enzpar), 't', countuniqItem[enzpar]))
+
+                    uniqItem, countuniqItem = countitems(items, 'cplxDest')
                     for cplx in uniqItem:
-                        prdlist.append((element(cplx),'cplx',countuniqItem[cplx]))
+                        prdlist.append(
+                            (moose.element(cplx), 'cplx', countuniqItem[cplx]))
 
                 if (baseObj == 'EnzBase'):
-                    uniqItem,countuniqItem = countitems(items,'enzDest')
+                    uniqItem, countuniqItem = countitems(items, 'enzDest')
                     for enzpar in uniqItem:
-                        sublist.append((element(enzpar),'t',countuniqItem[enzpar]))
-                cntDict[items] = sublist,prdlist
+                        sublist.append(
+                            (moose.element(enzpar), 't', countuniqItem[enzpar]))
+                cntDict[items] = sublist, prdlist
         elif baseObj == 'Function':
-            for items in wildcardFind(path):
+            for items in moose.wildcardFind(path):
                 sublist = []
                 prdlist = []
-                item = items.path+'/x[0]'
-                uniqItem,countuniqItem = countitems(item,'input')
+                item = items.path + '/x[0]'
+                uniqItem, countuniqItem = countitems(item, 'input')
                 for funcpar in uniqItem:
-                    sublist.append((element(funcpar),'sts',countuniqItem[funcpar]))
-                
-                uniqItem,countuniqItem = countitems(items,'valueOut')
+                    sublist.append(
+                        (moose.element(funcpar), 'sts', countuniqItem[funcpar]))
+
+                uniqItem, countuniqItem = countitems(items, 'valueOut')
                 for funcpar in uniqItem:
-                    prdlist.append((element(funcpar),'stp',countuniqItem[funcpar]))
-                cntDict[items] = sublist,prdlist
+                    prdlist.append(
+                        (moose.element(funcpar), 'stp', countuniqItem[funcpar]))
+                cntDict[items] = sublist, prdlist
         else:
-            for tab in wildcardFind(path):
+            for tab in moose.wildcardFind(path):
                 tablist = []
-                uniqItem,countuniqItem = countitems(tab,'output')
+                uniqItem, countuniqItem = countitems(tab, 'output')
                 for tabconnect in uniqItem:
-                    tablist.append((element(tabconnect),'tab',countuniqItem[tabconnect]))
+                    tablist.append(
+                        (moose.element(tabconnect), 'tab', countuniqItem[tabconnect]))
                 cntDict[tab] = tablist
     return cntDict
 
-def countitems(mitems,objtype):
+
+def countitems(mitems, objtype):
     items = []
-    #print "mitems in countitems ",mitems,objtype
-    items = element(mitems).neighbors[objtype]
+    # print "mitems in countitems ",mitems,objtype
+    items = moose.element(mitems).neighbors[objtype]
     uniqItems = set(items)
     countuniqItems = Counter(items)
-    return(uniqItems,countuniqItems)
+    return(uniqItems, countuniqItems)
+
 
 def setupMeshObj(modelRoot):
-    ''' Setup compartment and its members pool,reaction,enz cplx under self.meshEntry dictionaries \ 
-    self.meshEntry with "key" as compartment, 
+    ''' Setup compartment and its members pool,reaction,enz cplx under self.meshEntry dictionaries \
+    self.meshEntry with "key" as compartment,
     value is key2:list where key2 represents moose object type,list of objects of a perticular type
     e.g self.meshEntry[meshEnt] = { 'reaction': reaction_list,'enzyme':enzyme_list,'pool':poollist,'cplx': cplxlist }
     '''
@@ -912,72 +1108,100 @@ def setupMeshObj(modelRoot):
         meshEntry = {}
     meshEntryWildcard = '/##[ISA=ChemCompt]'
     if modelRoot != '/':
-        meshEntryWildcard = modelRoot+meshEntryWildcard
-    for meshEnt in wildcardFind(meshEntryWildcard):
+        meshEntryWildcard = modelRoot + meshEntryWildcard
+    for meshEnt in moose.wildcardFind(meshEntryWildcard):
         mollist = []
         cplxlist = []
-        mol_cpl  = wildcardFind(meshEnt.path+'/##[ISA=PoolBase]')
-        funclist = wildcardFind(meshEnt.path+'/##[ISA=Function]')
-        enzlist  = wildcardFind(meshEnt.path+'/##[ISA=EnzBase]')
-        realist  = wildcardFind(meshEnt.path+'/##[ISA=ReacBase]')
-        tablist  = wildcardFind(meshEnt.path+'/##[ISA=StimulusTable]')
+        mol_cpl = moose.wildcardFind(meshEnt.path + '/##[ISA=PoolBase]')
+        funclist = moose.wildcardFind(meshEnt.path + '/##[ISA=Function]')
+        enzlist = moose.wildcardFind(meshEnt.path + '/##[ISA=EnzBase]')
+        realist = moose.wildcardFind(meshEnt.path + '/##[ISA=ReacBase]')
+        tablist = moose.wildcardFind(meshEnt.path + '/##[ISA=StimulusTable]')
         if mol_cpl or funclist or enzlist or realist or tablist:
             for m in mol_cpl:
-                if isinstance(element(m.parent),CplxEnzBase):
+                if isinstance(moose.element(m.parent), moose.CplxEnzBase):
                     cplxlist.append(m)
-                elif isinstance(element(m),PoolBase):
+                elif isinstance(moose.element(m), moose.PoolBase):
                     mollist.append(m)
-                    
-            meshEntry[meshEnt] = {'enzyme':enzlist,
-                                  'reaction':realist,
-                                  'pool':mollist,
-                                  'cplx':cplxlist,
-                                  'table':tablist,
-                                  'function':funclist
+
+            meshEntry[meshEnt] = {'enzyme': enzlist,
+                                  'reaction': realist,
+                                  'pool': mollist,
+                                  'cplx': cplxlist,
+                                  'table': tablist,
+                                  'function': funclist
                                   }
     return(meshEntry)
 
-def autoCoordinates(meshEntry,srcdesConnection):
+
+def autoCoordinates(meshEntry, srcdesConnection):
     G = nx.Graph()
-    for cmpt,memb in list(meshEntry.items()):
-        for enzObj in find_index(memb,'enzyme'):
-            G.add_node(enzObj.path,label='',shape='ellipse',color='',style='filled',fontname='Helvetica',fontsize=12,fontcolor='blue')
-    for cmpt,memb in list(meshEntry.items()):
-        for poolObj in find_index(memb,'pool'):
+    for cmpt, memb in list(meshEntry.items()):
+        for enzObj in find_index(memb, 'enzyme'):
+            G.add_node(
+                enzObj.path,
+                label='',
+                shape='ellipse',
+                color='',
+                style='filled',
+                fontname='Helvetica',
+                fontsize=12,
+                fontcolor='blue')
+    for cmpt, memb in list(meshEntry.items()):
+        for poolObj in find_index(memb, 'pool'):
             #poolinfo = moose.element(poolObj.path+'/info')
-            G.add_node(poolObj.path,label = poolObj.name,shape = 'box',color = '',style = 'filled',fontname = 'Helvetica',fontsize = 12,fontcolor = 'blue')
-        for cplxObj in find_index(memb,'cplx'):
+            G.add_node(
+                poolObj.path,
+                label=poolObj.name,
+                shape='box',
+                color='',
+                style='filled',
+                fontname='Helvetica',
+                fontsize=12,
+                fontcolor='blue')
+        for cplxObj in find_index(memb, 'cplx'):
             pass
-        for reaObj in find_index(memb,'reaction'):
-            G.add_node(reaObj.path,label='',shape='record',color='')
-        
-    for inn,out in list(srcdesConnection.items()):
-        if (inn.className =='ZombieReac'): arrowcolor = 'green'
-        elif(inn.className =='ZombieEnz'): arrowcolor = 'red'
-        else: arrowcolor = 'blue'
-        if isinstance(out,tuple):
-            if len(out[0])== 0:
-                print(inn.className + ':' +inn.name + "  doesn't have input message")
+        for reaObj in find_index(memb, 'reaction'):
+            G.add_node(reaObj.path, label='', shape='record', color='')
+
+    for inn, out in list(srcdesConnection.items()):
+        if (inn.className == 'ZombieReac'):
+            arrowcolor = 'green'
+        elif(inn.className == 'ZombieEnz'):
+            arrowcolor = 'red'
+        else:
+            arrowcolor = 'blue'
+        if isinstance(out, tuple):
+            if len(out[0]) == 0:
+                print(
+                    inn.className +
+                    ':' +
+                    inn.name +
+                    "  doesn't have input message")
             else:
-                for items in (items for items in out[0] ):
-                	G.add_edge(element(items[0]).path,inn.path)
-                	
+                for items in (items for items in out[0]):
+                    G.add_edge(moose.element(items[0]).path, inn.path)
+
             if len(out[1]) == 0:
-                print(inn.className + ':' + inn.name + "doesn't have output mssg")
+                print(
+                    inn.className +
+                    ':' +
+                    inn.name +
+                    "doesn't have output mssg")
             else:
-                for items in (items for items in out[1] ):
-                	G.add_edge(inn.path,element(items[0]).path)
-                	
-        elif isinstance(out,list):
+                for items in (items for items in out[1]):
+                    G.add_edge(inn.path, moose.element(items[0]).path)
+
+        elif isinstance(out, list):
             if len(out) == 0:
                 print("Func pool doesn't have sumtotal")
             else:
-                for items in (items for items in out ):
-                	G.add_edge(element(items[0]).path,inn.path)
+                for items in (items for items in out):
+                    G.add_edge(moose.element(items[0]).path, inn.path)
     #from networkx.drawing.nx_agraph import graphviz_layout
     #position = graphviz_layout(G,prog='dot')
 
-    position = nx.pygraphviz_layout(G, prog = 'dot')
+    position = nx.pygraphviz_layout(G, prog='dot')
     position = nx.spring_layout(G)
     #agraph = nx.to_agraph(G)
     #agraph.draw("~/out.png", format = 'png', prog = 'dot')
@@ -986,42 +1210,43 @@ def autoCoordinates(meshEntry,srcdesConnection):
     xycord = []
     cmin = 0
     cmax = 0
-    for key,value in list(position.items()):
+    for key, value in list(position.items()):
         xycord.append(value[0])
         xycord.append(value[1])
-        sceneitems[element(key)] = {'x':value[0],'y':value[1]}
+        sceneitems[moose.element(key)] = {'x': value[0], 'y': value[1]}
     if len(xycord) > 0:
-    	cmin = min(xycord)
-    	cmax = max(xycord)
-    return cmin,cmax,sceneitems
+        cmin = min(xycord)
+        cmax = max(xycord)
+    return cmin, cmax, sceneitems
+
 
 def calPrime(x):
-    prime = int((20*(float(x-cmin)/float(cmax-cmin)))-10)
+    prime = int((20 * (float(x - cmin) / float(cmax - cmin))) - 10)
     return prime
 
+
 def find_index(value, key):
     """ Value.get(key) to avoid expection which would raise if empty value in dictionary for a given key """
-    if value.get(key) != None:
+    if value.get(key) is not None:
         return value.get(key)
     else:
         raise ValueError('no dict with the key found')
 if __name__ == "__main__":
 
-	filepath = sys.argv[1]
-	path = sys.argv[2]
-
-	f = open(filepath, 'r')
-	
-	if path == '':
-		loadpath = filepath[filepath.rfind('/'):filepath.find('.')]
-	else:
-		loadpath = path
-	
-	moose.loadModel(filepath,loadpath,"gsl")
-	
-	written,c,writtentofile = mooseWriteSBML(loadpath,filepath)
-	if written:
-		print(" File written to ",writtentofile)
-	else:
-		print(" could not write model to SBML file")
-	
\ No newline at end of file
+    filepath = sys.argv[1]
+    path = sys.argv[2]
+
+    f = open(filepath, 'r')
+
+    if path == '':
+        loadpath = filepath[filepath.rfind('/'):filepath.find('.')]
+    else:
+        loadpath = path
+
+    moose.loadModel(filepath, loadpath, "gsl")
+
+    written, c, writtentofile = mooseWriteSBML(loadpath, filepath)
+    if written:
+        print(" File written to ", writtentofile)
+    else:
+        print(" could not write model to SBML file")
diff --git a/python/moose/add_Delete_ChemicalSolver.py b/python/moose/add_Delete_ChemicalSolver.py
new file mode 100644
index 0000000000000000000000000000000000000000..f788118b7d20ad116c0a3323330ed20a598a712f
--- /dev/null
+++ b/python/moose/add_Delete_ChemicalSolver.py
@@ -0,0 +1,82 @@
+from . import _moose as moose
+
+
+def moosedeleteChemSolver(modelRoot):
+    """Delete solvers from Chemical Compartment
+
+    """
+    compts = moose.wildcardFind(modelRoot + '/##[ISA=ChemCompt]')
+    for compt in compts:
+        if moose.exists(compt.path + '/stoich'):
+            st = moose.element(compt.path + '/stoich')
+            st_ksolve = st.ksolve
+            moose.delete(st)
+            if moose.exists((st_ksolve).path):
+                moose.delete(st_ksolve)
+                print("Solver is deleted for modelpath %s " % modelRoot)
+
+
+def mooseaddChemSolver(modelRoot, solver):
+    """
+     Add the solvers to Chemical compartment
+    """
+    compt = moose.wildcardFind(modelRoot + '/##[ISA=ChemCompt]')
+    if compt:
+        comptinfo = moose.Annotator(moose.element(compt[0]).path + '/info')
+        previousSolver = comptinfo.solver
+        currentSolver = previousSolver
+        if solver == "Gillespie":
+            currentSolver = "gssa"
+        elif solver == "Runge Kutta":
+            currentSolver = "gsl"
+        elif solver == "Exponential Euler":
+            currentSolver = "ee"
+
+        if previousSolver != currentSolver:
+            # if previousSolver != currentSolver
+            comptinfo.solver = currentSolver
+            if (moose.exists(compt[0].path + '/stoich')):
+                # "A: and stoich exists then delete the stoich add solver"
+                deleteSolver(modelRoot)
+                setCompartmentSolver(modelRoot, currentSolver)
+                return True
+            else:
+                # " B: stoich doesn't exists then addSolver, this is when object is deleted which delete's the solver "
+                #  " and solver is also changed, then add addsolver "
+                setCompartmentSolver(modelRoot, currentSolver)
+                return True
+        else:
+            if moose.exists(compt[0].path + '/stoich'):
+                # " stoich exist, doing nothing"
+                return False
+            else:
+                # "but stoich doesn't exist,this is when object is deleted which deletes the solver
+                # " but solver are not changed, then also call addSolver"
+                setCompartmentSolver(modelRoot, currentSolver)
+                return True
+    return False
+
+
+def setCompartmentSolver(modelRoot, solver):
+    compts = moose.wildcardFind(modelRoot + '/##[ISA=ChemCompt]')
+    for compt in compts:
+        if (solver == 'gsl') or (solver == 'Runge Kutta'):
+            ksolve = moose.Ksolve(compt.path + '/ksolve')
+        if (solver == 'gssa') or (solver == 'Gillespie'):
+            ksolve = moose.Gsolve(compt.path + '/gsolve')
+        if (solver != 'ee'):
+            stoich = moose.Stoich(compt.path + '/stoich')
+            stoich.compartment = compt
+            stoich.ksolve = ksolve
+            if moose.exists(compt.path):
+                stoich.path = compt.path + "/##"
+    stoichList = moose.wildcardFind(modelRoot + '/##[ISA=Stoich]')
+    if len(stoichList) == 2:
+        stoichList[1].buildXreacs(stoichList[0])
+    if len(stoichList) == 3:
+        stoichList[1].buildXreacs(stoichList[0])
+        stoichList[1].buildXreacs(stoichList[2])
+
+    for i in stoichList:
+        i.filterXreacs()
+    print( " Solver is added to model path %s" % modelRoot )
diff --git a/python/moose/genesis/__init__.py b/python/moose/genesis/__init__.py
index 37da15439974c3cd452c1e170b1dfd04d571ba01..2d73bdb1b74df92071100aa9344565734b642089 100644
--- a/python/moose/genesis/__init__.py
+++ b/python/moose/genesis/__init__.py
@@ -1,3 +1 @@
-from _main import write
-
-__all__ = ["write"]
\ No newline at end of file
+from  .writeKkit import mooseWriteKkit
diff --git a/python/moose/genesis/_main.py b/python/moose/genesis/writeKkit.py
similarity index 83%
rename from python/moose/genesis/_main.py
rename to python/moose/genesis/writeKkit.py
index 65963cabf65f4f233c174c1856479e392c66b98f..226fe2a319b000f199357f41a3fac3fdf0f85a73 100644
--- a/python/moose/genesis/_main.py
+++ b/python/moose/genesis/writeKkit.py
@@ -11,12 +11,11 @@ __status__           = "Development"
 
 import sys
 import random
-from moose import wildcardFind, element, loadModel, ChemCompt, exists, Annotator, Pool, ZombiePool,PoolBase,CplxEnzBase,Function,ZombieFunction
+import moose
 import numpy as np
 import re
 from collections import Counter
 import networkx as nx
-from PyQt4.QtGui import QColor
 import matplotlib 
 
 GENESIS_COLOR_SEQUENCE = ((248, 0, 255), (240, 0, 255), (232, 0, 255), (224, 0, 255), (216, 0, 255), (208, 0, 255),
@@ -39,7 +38,7 @@ GENESIS_COLOR_SEQUENCE = ((248, 0, 255), (240, 0, 255), (232, 0, 255), (224, 0,
 #Todo : To be written
 #               --StimulusTable
 
-def write( modelpath, filename,sceneitems=None):
+def mooseWriteKkit( modelpath, filename,sceneitems=None):
     if filename.rfind('.') != -1:
         filename = filename[:filename.rfind('.')]
     else:
@@ -55,7 +54,7 @@ def write( modelpath, filename,sceneitems=None):
     ymin = 0
     ymax = 1
 
-    compt = wildcardFind(modelpath+'/##[ISA=ChemCompt]')
+    compt = moose.wildcardFind(modelpath+'/##[ISA=ChemCompt]')
     maxVol = estimateDefaultVol(compt)
     f = open(filename, 'w')
 
@@ -64,7 +63,7 @@ def write( modelpath, filename,sceneitems=None):
         setupItem(modelpath,srcdesConnection)
         meshEntry = setupMeshObj(modelpath)
         cmin,cmax,sceneitems = autoCoordinates(meshEntry,srcdesConnection)
-        for k,v in sceneitems.items():
+        for k,v in list(sceneitems.items()):
             v = sceneitems[k]
             x1 = calPrime(v['x'])
             y1 = calPrime(v['y'])
@@ -72,7 +71,7 @@ def write( modelpath, filename,sceneitems=None):
             sceneitems[k]['y'] = y1
     else:
         cs, xcord, ycord = [], [] ,[]
-        for k,v in sceneitems.items():
+        for k,v in list(sceneitems.items()):
             xcord.append(v['x'])
             cs.append(v['x'])
             ycord.append(v['y'])
@@ -94,7 +93,7 @@ def write( modelpath, filename,sceneitems=None):
         writeSumtotal(modelpath,f)
         f.write("simundump xgraph /graphs/conc1 0 0 99 0.001 0.999 0\n"
                 "simundump xgraph /graphs/conc2 0 0 100 0 1 0\n")
-        tgraphs = wildcardFind(modelpath+'/##[ISA=Table2]')
+        tgraphs = moose.wildcardFind(modelpath+'/##[ISA=Table2]')
         first, second = " ", " "
         if tgraphs:
             first,second = writeplot(tgraphs,f)
@@ -117,7 +116,7 @@ def write( modelpath, filename,sceneitems=None):
         writeFooter2(f)
         return True
     else:
-        print("Warning: writeKkit:: No model found on " , modelpath)
+        print(("Warning: writeKkit:: No model found on " , modelpath))
         return False
 
 def calPrime(x):
@@ -137,60 +136,59 @@ def setupItem(modelPath,cntDict):
         if modelPath != '/':
             path = modelPath+path
         if ( (baseObj == 'ReacBase') or (baseObj == 'EnzBase')):
-            for items in wildcardFind(path):
+            for items in moose.wildcardFind(path):
                 sublist = []
                 prdlist = []
                 uniqItem,countuniqItem = countitems(items,'subOut')
                 subNo = uniqItem
                 for sub in uniqItem: 
-                    sublist.append((element(sub),'s',countuniqItem[sub]))
+                    sublist.append((moose.element(sub),'s',countuniqItem[sub]))
 
                 uniqItem,countuniqItem = countitems(items,'prd')
                 prdNo = uniqItem
                 if (len(subNo) == 0 or len(prdNo) == 0):
-                    print "Substrate Product is empty ",path, " ",items
+                    print("Substrate Product is empty ",path, " ",items)
                     
                 for prd in uniqItem:
-                    prdlist.append((element(prd),'p',countuniqItem[prd]))
+                    prdlist.append((moose.element(prd),'p',countuniqItem[prd]))
                 
                 if (baseObj == 'CplxEnzBase') :
                     uniqItem,countuniqItem = countitems(items,'toEnz')
                     for enzpar in uniqItem:
-                        sublist.append((element(enzpar),'t',countuniqItem[enzpar]))
+                        sublist.append((moose.element(enzpar),'t',countuniqItem[enzpar]))
                     
                     uniqItem,countuniqItem = countitems(items,'cplxDest')
                     for cplx in uniqItem:
-                        prdlist.append((element(cplx),'cplx',countuniqItem[cplx]))
+                        prdlist.append((moose.element(cplx),'cplx',countuniqItem[cplx]))
 
                 if (baseObj == 'EnzBase'):
                     uniqItem,countuniqItem = countitems(items,'enzDest')
                     for enzpar in uniqItem:
-                        sublist.append((element(enzpar),'t',countuniqItem[enzpar]))
+                        sublist.append((moose.element(enzpar),'t',countuniqItem[enzpar]))
                 cntDict[items] = sublist,prdlist
         elif baseObj == 'Function':
-            for items in wildcardFind(path):
+            for items in moose.wildcardFind(path):
                 sublist = []
                 prdlist = []
                 item = items.path+'/x[0]'
                 uniqItem,countuniqItem = countitems(item,'input')
                 for funcpar in uniqItem:
-                    sublist.append((element(funcpar),'sts',countuniqItem[funcpar]))
+                    sublist.append((moose.element(funcpar),'sts',countuniqItem[funcpar]))
                 
                 uniqItem,countuniqItem = countitems(items,'valueOut')
                 for funcpar in uniqItem:
-                    prdlist.append((element(funcpar),'stp',countuniqItem[funcpar]))
+                    prdlist.append((moose.element(funcpar),'stp',countuniqItem[funcpar]))
                 cntDict[items] = sublist,prdlist
         else:
-            for tab in wildcardFind(path):
+            for tab in moose.wildcardFind(path):
                 tablist = []
                 uniqItem,countuniqItem = countitems(tab,'output')
                 for tabconnect in uniqItem:
-                    tablist.append((element(tabconnect),'tab',countuniqItem[tabconnect]))
+                    tablist.append((moose.element(tabconnect),'tab',countuniqItem[tabconnect]))
                 cntDict[tab] = tablist
 def countitems(mitems,objtype):
     items = []
-    #print "mitems in countitems ",mitems,objtype
-    items = element(mitems).neighbors[objtype]
+    items = moose.element(mitems).neighbors[objtype]
     uniqItems = set(items)
     countuniqItems = Counter(items)
     return(uniqItems,countuniqItems)
@@ -209,19 +207,19 @@ def setupMeshObj(modelRoot):
     meshEntryWildcard = '/##[ISA=ChemCompt]'
     if modelRoot != '/':
         meshEntryWildcard = modelRoot+meshEntryWildcard
-    for meshEnt in wildcardFind(meshEntryWildcard):
+    for meshEnt in moose.wildcardFind(meshEntryWildcard):
         mollist = []
         cplxlist = []
-        mol_cpl  = wildcardFind(meshEnt.path+'/##[ISA=PoolBase]')
-        funclist = wildcardFind(meshEnt.path+'/##[ISA=Function]')
-        enzlist  = wildcardFind(meshEnt.path+'/##[ISA=EnzBase]')
-        realist  = wildcardFind(meshEnt.path+'/##[ISA=ReacBase]')
-        tablist  = wildcardFind(meshEnt.path+'/##[ISA=StimulusTable]')
+        mol_cpl  = moose.wildcardFind(meshEnt.path+'/##[ISA=PoolBase]')
+        funclist = moose.wildcardFind(meshEnt.path+'/##[ISA=Function]')
+        enzlist  = moose.wildcardFind(meshEnt.path+'/##[ISA=EnzBase]')
+        realist  = moose.wildcardFind(meshEnt.path+'/##[ISA=ReacBase]')
+        tablist  = moose.wildcardFind(meshEnt.path+'/##[ISA=StimulusTable]')
         if mol_cpl or funclist or enzlist or realist or tablist:
             for m in mol_cpl:
-                if isinstance(element(m.parent),CplxEnzBase):
+                if isinstance(moose.element(m.parent),moose.CplxEnzBase):
                     cplxlist.append(m)
-                elif isinstance(element(m),PoolBase):
+                elif isinstance(moose.element(m),moose.PoolBase):
                     mollist.append(m)
                     
             meshEntry[meshEnt] = {'enzyme':enzlist,
@@ -234,11 +232,11 @@ def setupMeshObj(modelRoot):
     return(meshEntry)
 def autoCoordinates(meshEntry,srcdesConnection):
     G = nx.Graph()
-    for cmpt,memb in meshEntry.items():
+    for cmpt,memb in list(meshEntry.items()):
         for enzObj in find_index(memb,'enzyme'):
             #G.add_node(enzObj.path)
             G.add_node(enzObj.path,label=enzObj.name,shape='ellipse',color='',style='filled',fontname='Helvetica',fontsize=12,fontcolor='blue')
-    for cmpt,memb in meshEntry.items():
+    for cmpt,memb in list(meshEntry.items()):
         for poolObj in find_index(memb,'pool'):
             #G.add_node(poolObj.path)
             G.add_node(poolObj.path,label = poolObj.name,shape = 'box',color = '',style = 'filled',fontname = 'Helvetica',fontsize = 12,fontcolor = 'blue')
@@ -248,43 +246,46 @@ def autoCoordinates(meshEntry,srcdesConnection):
             #G.add_edge((cplxObj.parent).path,cplxObj.path)
         for reaObj in find_index(memb,'reaction'):
             #G.add_node(reaObj.path)
-            G.add_node(reaObj.path,label=reaObj.name,shape='record',color='')
+            G.add_node(reaObj.path,label=reaObj.name,shape='',color='')
         for funcObj in find_index(memb,'function'):
             G.add_node(poolObj.path,label = funcObj.name,shape = 'box',color = 'red',style = 'filled',fontname = 'Helvetica',fontsize = 12,fontcolor = 'blue')
 
         
-    for inn,out in srcdesConnection.items():
+    for inn,out in list(srcdesConnection.items()):
         if (inn.className =='ZombieReac'): arrowcolor = 'green'
         elif(inn.className =='ZombieEnz'): arrowcolor = 'red'
         else: arrowcolor = 'blue'
         if isinstance(out,tuple):
             if len(out[0])== 0:
-                print inn.className + ':' +inn.name + "  doesn't have input message"
+                print(inn.className + ':' +inn.name + "  doesn't have input message")
             else:
                 for items in (items for items in out[0] ):
-                    G.add_edge(element(items[0]).path,inn.path)
+                    G.add_edge(moose.element(items[0]).path,inn.path)
             if len(out[1]) == 0:
-                print inn.className + ':' + inn.name + "doesn't have output mssg"
+                print(inn.className + ':' + inn.name + "doesn't have output mssg")
             else:
                 for items in (items for items in out[1] ):
-                    G.add_edge(inn.path,element(items[0]).path)
+                    G.add_edge(inn.path,moose.element(items[0]).path)
         elif isinstance(out,list):
             if len(out) == 0:
-                print "Func pool doesn't have sumtotal"
+                print("Func pool doesn't have sumtotal")
             else:
                 for items in (items for items in out ):
-                    G.add_edge(element(items[0]).path,inn.path)
+                    G.add_edge(moose.element(items[0]).path,inn.path)
     
     position = nx.graphviz_layout(G, prog = 'dot')
+    if int( nx.__version__.split( '.' )[-1] ) >= 11:
+        position = nx.spring_layout( G )
+
     #agraph = nx.to_agraph(G)
     #agraph.draw("writetogenesis.png", format = 'png', prog = 'dot')
     sceneitems = {}
     xycord = []
 
-    for key,value in position.items():
+    for key,value in list(position.items()):
         xycord.append(value[0])
         xycord.append(value[1])
-        sceneitems[element(key)] = {'x':value[0],'y':value[1]}
+        sceneitems[moose.element(key)] = {'x':value[0],'y':value[1]}
     cmin = min(xycord)
     cmax = max(xycord)
     return cmin,cmax,sceneitems
@@ -314,15 +315,15 @@ def storeMMenzMsgs( enz, f):
     prdList = enz.neighbors["prd"]
     enzDestList = enz.neighbors["enzDest"]
     for esub in subList:
-        es = "addmsg /kinetics/" + trimPath(element(esub)) + " /kinetics/" + trimPath(enz) + " SUBSTRATE n \n";
-        es = es+"addmsg /kinetics/" + trimPath(enz) + " /kinetics/" + trimPath(element(esub)) + " REAC sA B \n";
+        es = "addmsg /kinetics/" + trimPath(moose.element(esub)) + " /kinetics/" + trimPath(enz) + " SUBSTRATE n \n";
+        es = es+"addmsg /kinetics/" + trimPath(enz) + " /kinetics/" + trimPath(moose.element(esub)) + " REAC sA B \n";
         f.write(es)
 
     for eprd in prdList:
-        es = "addmsg /kinetics/" + trimPath( enz ) + " /kinetics/" + trimPath( element(eprd)) + " MM_PRD pA \n";
+        es = "addmsg /kinetics/" + trimPath( enz ) + " /kinetics/" + trimPath( moose.element(eprd)) + " MM_PRD pA \n";
         f.write(es)
     for eenzDest in enzDestList:
-        enzDest = "addmsg /kinetics/" + trimPath( element(eenzDest)) + " /kinetics/" + trimPath( enz ) + " ENZYME n \n";
+        enzDest = "addmsg /kinetics/" + trimPath( moose.element(eenzDest)) + " /kinetics/" + trimPath( enz ) + " ENZYME n \n";
         f.write(enzDest)
 
 def storeEnzMsg( enzList, f):
@@ -334,7 +335,7 @@ def storeEnzMsg( enzList, f):
             storeCplxEnzMsgs( enz, f )
 
 def writeEnz( modelpath,f,sceneitems):
-    enzList = wildcardFind(modelpath+'/##[ISA=EnzBase]')
+    enzList = moose.wildcardFind(modelpath+'/##[ISA=EnzBase]')
     for enz in enzList:
         x = random.randrange(0,10)
         y = random.randrange(0,10)
@@ -348,7 +349,7 @@ def writeEnz( modelpath,f,sceneitems):
         n = 0;
         conc = 0;
         enzParent = enz.parent
-        if (isinstance(enzParent.className,Pool)) or (isinstance(enzParent.className,ZombiePool)):
+        if (isinstance(enzParent.className,moose.Pool)) or (isinstance(enzParent.className,moose.ZombiePool)):
             print(" raise exception enz doesn't have pool as parent")
             return False
         else:
@@ -376,11 +377,11 @@ def writeEnz( modelpath,f,sceneitems):
                 y = sceneitems[enz]['y']
 
             einfo = enz.path+'/info'
-            if exists(einfo):
-                color = Annotator(einfo).getField('color')
+            if moose.exists(einfo):
+                color = moose.Annotator(einfo).getField('color')
                 color = getColorCheck(color,GENESIS_COLOR_SEQUENCE)
 
-                textcolor = Annotator(einfo).getField('textColor')
+                textcolor = moose.Annotator(einfo).getField('textColor')
                 textcolor = getColorCheck(textcolor,GENESIS_COLOR_SEQUENCE)
 
             if color == "" or color == " ":
@@ -432,7 +433,7 @@ def storeReacMsg(reacList,f):
             f.write( s)
 
 def writeReac(modelpath,f,sceneitems):
-    reacList = wildcardFind(modelpath+'/##[ISA=ReacBase]')
+    reacList = moose.wildcardFind(modelpath+'/##[ISA=ReacBase]')
     for reac in reacList :
         color = ""
         textcolor = ""
@@ -445,11 +446,11 @@ def writeReac(modelpath,f,sceneitems):
         x = sceneitems[reac]['x']
         y = sceneitems[reac]['y']
         rinfo = reac.path+'/info'
-        if exists(rinfo):
-            color = Annotator(rinfo).getField('color')
+        if moose.exists(rinfo):
+            color = moose.Annotator(rinfo).getField('color')
             color = getColorCheck(color,GENESIS_COLOR_SEQUENCE)
 
-            textcolor = Annotator(rinfo).getField('textColor')
+            textcolor = moose.Annotator(rinfo).getField('textColor')
             textcolor = getColorCheck(textcolor,GENESIS_COLOR_SEQUENCE)
         
         if color == "" or color == " ":
@@ -462,22 +463,20 @@ def writeReac(modelpath,f,sceneitems):
  
 def trimPath(mobj):
     original = mobj
-    mobj = element(mobj)
+    mobj = moose.element(mobj)
     found = False
-    while not isinstance(mobj,ChemCompt) and mobj.path != "/":
-        mobj = element(mobj.parent)
+    while not isinstance(mobj,moose.ChemCompt) and mobj.path != "/":
+        mobj = moose.element(mobj.parent)
         found = True
     if mobj.path == "/":
-        print("compartment is not found with the given path and the path has reached root ",original)
+        print(("compartment is not found with the given path and the path has reached root ",original))
         return
     #other than the kinetics compartment, all the othername are converted to group in Genesis which are place under /kinetics
     # Any moose object comes under /kinetics then one level down the path is taken.
     # e.g /group/poolObject or /Reac
     if found:
         if mobj.name != "kinetics" and (mobj.className != "CubeMesh"):
-            print " 478 ",mobj.name,mobj.className
             splitpath = original.path[(original.path.find(mobj.name)):len(original.path)]
-            print " splitpath ",original,splitpath
         else:
             pos = original.path.find(mobj.name)
             slash = original.path.find('/',pos+1)
@@ -487,12 +486,12 @@ def trimPath(mobj):
         return s
 
 def writeSumtotal( modelpath,f):
-    funclist = wildcardFind(modelpath+'/##[ISA=Function]')
+    funclist = moose.wildcardFind(modelpath+'/##[ISA=Function]')
     for func in funclist:
-        funcInputs = element(func.path+'/x[0]')
+        funcInputs = moose.element(func.path+'/x[0]')
         s = ""
         for funcInput in funcInputs.neighbors["input"]:
-            s = s+ "addmsg /kinetics/" + trimPath(funcInput)+ " /kinetics/" + trimPath(element(func.parent)) + " SUMTOTAL n nInit\n"
+            s = s+ "addmsg /kinetics/" + trimPath(funcInput)+ " /kinetics/" + trimPath(moose.element(func.parent)) + " SUMTOTAL n nInit\n"
         f.write(s)
 
 def storePlotMsgs( tgraphs,f):
@@ -510,12 +509,12 @@ def storePlotMsgs( tgraphs,f):
                     slash1 = graph.path.find('/',slash)
                     tabPath = "/graphs/conc1" +graph.path[slash1:len(graph.path)]
 
-                if len(element(graph).msgOut):
-                    poolPath = (element(graph).msgOut)[0].e2.path
-                    poolEle = element(poolPath)
+                if len(moose.element(graph).msgOut):
+                    poolPath = (moose.element(graph).msgOut)[0].e2.path
+                    poolEle = moose.element(poolPath)
                     poolName = poolEle.name
                     bgPath = (poolEle.path+'/info')
-                    bg = Annotator(bgPath).color
+                    bg = moose.Annotator(bgPath).color
                     bg = getColorCheck(bg,GENESIS_COLOR_SEQUENCE)
                     tabPath = re.sub("\[[0-9]+\]", "", tabPath)
                     s = s+"addmsg /kinetics/" + trimPath( poolEle ) + " " + tabPath + \
@@ -536,11 +535,11 @@ def writeplot( tgraphs,f ):
                 else:
                     slash1 = graphs.path.find('/',slash)
                     tabPath = "/graphs/conc1" +graphs.path[slash1:len(graphs.path)]
-                if len(element(graphs).msgOut):
-                    poolPath = (element(graphs).msgOut)[0].e2.path
-                    poolEle = element(poolPath)
+                if len(moose.element(graphs).msgOut):
+                    poolPath = (moose.element(graphs).msgOut)[0].e2.path
+                    poolEle = moose.element(poolPath)
                     poolAnno = (poolEle.path+'/info')
-                    fg = Annotator(poolAnno).textColor
+                    fg = moose.Annotator(poolAnno).textColor
                     fg = getColorCheck(fg,GENESIS_COLOR_SEQUENCE)
                     tabPath = re.sub("\[[0-9]+\]", "", tabPath)
                     if tabPath.find("conc1") >= 0 or tabPath.find("conc2") >= 0:
@@ -550,10 +549,9 @@ def writeplot( tgraphs,f ):
     return first,second
 
 def writePool(modelpath,f,volIndex,sceneitems):
-    print " modelpath ",modelpath
     color = ""
     textcolor = ""
-    for p in wildcardFind(modelpath+'/##[ISA=PoolBase]'):
+    for p in moose.wildcardFind(modelpath+'/##[ISA=PoolBase]'):
         slave_enable = 0
         if (p.className == "BufPool" or p.className == "ZombieBufPool"):
             pool_children = p.children
@@ -576,10 +574,10 @@ def writePool(modelpath,f,volIndex,sceneitems):
             #     y = calPrime(value['y'])
                 
             pinfo = p.path+'/info'
-            if exists(pinfo):
-                color = Annotator(pinfo).getField('color')
+            if moose.exists(pinfo):
+                color = moose.Annotator(pinfo).getField('color')
                 color = getColorCheck(color,GENESIS_COLOR_SEQUENCE)
-                textcolor = Annotator(pinfo).getField('textColor')
+                textcolor = moose.Annotator(pinfo).getField('textColor')
                 textcolor = getColorCheck(textcolor,GENESIS_COLOR_SEQUENCE)
             
             geometryName = volIndex[p.volume]
@@ -632,11 +630,11 @@ def getColorCheck(color,GENESIS_COLOR_SEQUENCE):
 
 ignoreColor= ["mistyrose","antiquewhite","aliceblue","azure","bisque","black","blanchedalmond","blue","cornsilk","darkolivegreen","darkslategray","dimgray","floralwhite","gainsboro","ghostwhite","honeydew","ivory","lavender","lavenderblush","lemonchiffon","lightcyan","lightgoldenrodyellow","lightgray","lightyellow","linen","mediumblue","mintcream","navy","oldlace","papayawhip","saddlebrown","seashell","snow","wheat","white","whitesmoke","aquamarine","lightsalmon","moccasin","limegreen","snow","sienna","beige","dimgrey","lightsage"]
 matplotcolor = {}
-for name,hexno in matplotlib.colors.cnames.iteritems():
+for name,hexno in matplotlib.colors.cnames.items():
     matplotcolor[name]=hexno
 
 def getRandColor():
-    k = random.choice(matplotcolor.keys())
+    k = random.choice(list(matplotcolor.keys()))
     if k in ignoreColor:
         return getRandColor()
     else:
@@ -672,7 +670,7 @@ def writeCompartment(modelpath,compts,f):
 
 def writeGroup(modelpath,f):
     ignore = ["graphs","moregraphs","geometry","groups","conc1","conc2","conc3","conc4","model","data","graph_0","graph_1","graph_2","graph_3","graph_4","graph_5"]
-    for g in wildcardFind(modelpath+'/##[TYPE=Neutral]'):
+    for g in moose.wildcardFind(modelpath+'/##[TYPE=Neutral]'):
         if not g.name in ignore:
             if trimPath(g) != None:
                 x = xmin+1
@@ -740,20 +738,20 @@ def estimateDefaultVol(compts):
 
 def writeNotes(modelpath,f):
     notes = ""
-    #items = wildcardFind(modelpath+"/##[ISA=ChemCompt],/##[ISA=ReacBase],/##[ISA=PoolBase],/##[ISA=EnzBase],/##[ISA=Function],/##[ISA=StimulusTable]")
+    #items = moose.wildcardFind(modelpath+"/##[ISA=ChemCompt],/##[ISA=ReacBase],/##[ISA=PoolBase],/##[ISA=EnzBase],/##[ISA=Function],/##[ISA=StimulusTable]")
     items = []
-    items = wildcardFind(modelpath+"/##[ISA=ChemCompt]") +\
-            wildcardFind(modelpath+"/##[ISA=PoolBase]") +\
-            wildcardFind(modelpath+"/##[ISA=ReacBase]") +\
-            wildcardFind(modelpath+"/##[ISA=EnzBase]") +\
-            wildcardFind(modelpath+"/##[ISA=Function]") +\
-            wildcardFind(modelpath+"/##[ISA=StimulusTable]")
+    items = moose.wildcardFind(modelpath+"/##[ISA=ChemCompt]") +\
+            moose.wildcardFind(modelpath+"/##[ISA=PoolBase]") +\
+            moose.wildcardFind(modelpath+"/##[ISA=ReacBase]") +\
+            moose.wildcardFind(modelpath+"/##[ISA=EnzBase]") +\
+            moose.wildcardFind(modelpath+"/##[ISA=Function]") +\
+            moose.wildcardFind(modelpath+"/##[ISA=StimulusTable]")
     for item in items:
-        if exists(item.path+'/info'):
+        if moose.exists(item.path+'/info'):
             info = item.path+'/info'
-            notes = Annotator(info).getField('notes')
+            notes = moose.Annotator(info).getField('notes')
             if (notes):
-                f.write("call /kinetics/"+ trimPath(item)+"/notes LOAD \ \n\""+Annotator(info).getField('notes')+"\"\n")
+                f.write("call /kinetics/"+ trimPath(item)+"/notes LOAD \ \n\""+moose.Annotator(info).getField('notes')+"\"\n")
 
 def writeFooter1(f):
     f.write("\nenddump\n // End of dump\n")
@@ -766,10 +764,10 @@ if __name__ == "__main__":
 
     filename = sys.argv[1]
     modelpath = filename[0:filename.find('.')]
-    loadModel(filename,'/'+modelpath,"gsl")
+    moose.loadModel(filename,'/'+modelpath,"gsl")
     output = modelpath+"_4mmoose.g"
     written = write('/'+modelpath,output)
     if written:
-            print(" file written to ",output)
+            print((" file written to ",output))
     else:
             print(" could be written to kkit format")
diff --git a/python/moose/merge.py b/python/moose/merge.py
index aaf05c12b915d6cc967dac331530fdc92ebd0042..70f37b24530de75e7aaf80dd7c30b152e55198b5 100644
--- a/python/moose/merge.py
+++ b/python/moose/merge.py
@@ -1,3 +1,4 @@
+from __future__ import print_function 
 
 #*******************************************************************
 # * File:            merge.py
@@ -52,9 +53,9 @@ def merge(A,B):
 	comptAdict = comptList(apath)
 	comptBdict = comptList(bpath)
 
-	for key in comptBdict.keys():
+	for key in list(comptBdict.keys()):
 
-		if not comptAdict.has_key(key):
+		if key not in comptAdict:
 			# comptBdict[key] - compartment from model B which does not exist in model A
 			moose.copy(comptBdict[key],moose.element(apath))
 		else:			
@@ -81,10 +82,10 @@ def merge(A,B):
 						c = moose.copy(pool,neutral_compartment)
 						copied.append(c)
 					elif (pool.parent).className == "ZombieEnz" or (pool.parent).className == "Enz":
-						print " Pool not in modelA but enz parent",pool.name
+						print(" Pool not in modelA but enz parent",pool.name)
 						pass
 					else:
-						print " Check this pool, parent which doesn't have ChemCompt or Enz",
+						print(" Check this pool, parent which doesn't have ChemCompt or Enz", end=' ')
 			
 			#Mergering StimulusTable
 			stimName_a = []
@@ -173,9 +174,9 @@ def merge(A,B):
 						rBprdname = subprdList(reac,"prd")
 						mooseConnect(comptAdict[key].path,reac,rBsubname,"sub")
 						mooseConnect(comptAdict[key].path,reac,rBprdname,"prd")
-	print "\ncopied: ", copied, \
+	print("\ncopied: ", copied, \
 		 "\n\nDuplicated: ",duplicated, \
-		  "\n\nwarning: ",war_msg
+		  "\n\nwarning: ",war_msg)
 	return copied,duplicated,war_msg
 def loadModels(filename):
 	apath = '/'
@@ -244,4 +245,4 @@ if __name__ == "__main__":
 	#model2 = '/home/harsha/Trash/modelB.g'
 	model1 = '/home/harsha/genesis_files/gfile/acc44.g'
 	model2 = '/home/harsha/genesis_files/gfile/acc45.g'
-	mergered = merge(model1,model2)
\ No newline at end of file
+	mergered = merge(model1,model2)
diff --git a/python/moose/moose.py b/python/moose/moose.py
index 7581c65f25532c2b352d018b536d57893087a1d3..edc9954ede60f22beac919c43c91e22210dd60b6 100644
--- a/python/moose/moose.py
+++ b/python/moose/moose.py
@@ -1,56 +1,50 @@
-# moose.py --- 
- 
-# Filename: moose.py
-# Description: 
-# Author: Subhasis Ray
-# Maintainer: 
-# Copyright (C) 2010 Subhasis Ray, all rights reserved.
-# Created: Sat Mar 12 14:02:40 2011 (+0530)
-# Version: 
-# Last-Updated: Tue Oct 27 15:00:31 2015 (-0400)
-#           By: Subhasis Ray
-#     Update #: 2182
-# URL: 
-# Keywords: 
-# Compatibility: 
-# 
-# 
-
-# Commentary: 
-# 
+# moose.py ---
 # This is the primary moose module. It wraps _moose.so and adds some
 # utility functions.
-# 
 
-# Change log:
-# 
-# Mon Sep 9 22:56:35 IST 2013 - Renamed some function parameters and
-# updated docstrings to consistently follow numpy docstring
-# convention.
-# 
-
-# Code:
+# Filename: moose.py
+# Author: Subhasis Ray
+# Maintainer: Dilawar Singh, Harsha Rani, Upi Bhalla
 
 from __future__ import print_function
 from contextlib import closing
 import warnings
 import platform
 import pydoc
+import os
 from io import StringIO
 from collections import defaultdict
 from . import _moose
 from ._moose import *
 import __main__ as main
 
-sequence_types = [ 'vector<double>',
-                   'vector<int>',
-                   'vector<long>',
-                   'vector<unsigned int>',
-                   'vector<float>',
-                   'vector<unsigned long>',
-                   'vector<short>',
-                   'vector<Id>',
-                   'vector<ObjId>' ]
+sbmlSupport_, genesisSupport_ = True, True
+try:
+    import SBML.readSBML
+    import SBML.writeSBML 
+except Exception as e:
+    print( 'MOOSE could not load SBML support due to %s' % e )
+    sbmlSupport_ = False
+
+try:
+    import genesis.writeKkit
+except Exception as e:
+    print('MOOSE could not load GENESIS support')
+    print('\tError was %s' % e)
+    genesisSupport_ = False
+
+from . import add_Delete_ChemicalSolver 
+
+sequence_types = ['vector<double>',
+                  'vector<int>',
+                  'vector<long>',
+                  'vector<unsigned int>',
+                  'vector<float>',
+                  'vector<unsigned long>',
+                  'vector<short>',
+                  'vector<Id>',
+                  'vector<ObjId>']
+
 known_types = ['void',
                'char',
                'short',
@@ -64,10 +58,97 @@ known_types = ['void',
                'vec',
                'melement'] + sequence_types
 
+# SBML related functions.
+
+
+def mooseReadSBML(filepath, loadpath, solver='ee'):
+    """Load SBML model.
+
+    keyword arguments: \n
+
+    filepath -- filepath to be loaded \n
+    loadpath -- Root path for this model e.g. /model/mymodel \n
+    solver   -- Solver to use (default 'ee' ) \n
+
+    """
+    global sbmlSupport_
+    if not sbmlSupport_:
+        print('SBML support was not loaded')
+        return None
+    if not os.path.isfile(filepath):
+        raise UserWarning('File %s not found' % filepath)
+
+    return SBML.readSBML.mooseReadSBML( filepath, loadpath, solver )
+
+
+def mooseWriteSBML(modelpath, filenpath, sceneitems={}):
+    """Writes loaded model under modelpath to a file in SBML format.
+
+    keyword arguments:\n
+
+    modelpath -- model path in moose e.g /model/mymodel \n
+    filepath -- Path of output file. \n
+    sceneitems -- dictlist (UserWarning: user need not worry about this) \n
+                    layout position is saved in Annotation field of all the moose Object (pool,Reaction,enzyme)\n
+                    If this function is called from \n
+                        -- GUI, the layout position of moose object is passed \n
+                        -- command line, \n
+                            ---if genesis/kkit model is loaded then layout position is taken from the file \n
+                            --- else, auto-coordinates is used for layout position and passed
+
+    """
+
+    global sbmlSupport_
+    if not sbmlSupport_:
+        print('SBML support was not loaded')
+        return None
+
+    return SBML.writeSBML.mooseWriteSBML(modelpath, filepath, sceneitems)
+
+
+def mooseWriteKkit(modelpath, filepath):
+    """Writes  loded model under modelpath to a file in Kkit format.
+
+    keyword arguments:\n
+
+    modelpath -- model path in moose \n
+    filepath -- Path of output file.
+    """
+    global genesisSupport_
+    if not genesisSupport_:
+        print('GENESIS(kkit) support was not loaded')
+        return None
+
+    return moose.genesis.writeKkit.mooseWiteKkit(modelpath, filepath)
+
+
+def moosedeleteChemSolver(modelpath):
+    """ deletes solver on all the compartment and its children.
+        This is neccesary while created a new moose object on a pre-existing modelpath,\n
+        this should be followed by mooseaddChemSolver for add solvers on to compartment to simulate else
+        default is Exponential Euler (ee)
+    """
+    return add_Delete_ChemicalSolver.moosedeleteChemSolver(modelpath)
+
+
+def mooseaddChemSolver(modelpath, solver):
+    """ Add solver on chemical compartment and its children for calculation
+
+    keyword arguments:\n
+
+    modelpath -- model path that is loaded into moose \n
+    solver -- "Exponential Euler" (ee) (default), \n
+              "Gillespie"         ("gssa"), \n
+              "Runge Kutta"       ("gsl")
+
+    """
+    return add_Delete_ChemicalSolver.mooseaddChemSolver(modelpath, solver)
+
 ################################################################
 # Wrappers for global functions
-################################################################ 
-    
+################################################################
+
+
 def pwe():
     """Print present working element. Convenience function for GENESIS
     users. If you want to retrieve the element in stead of printing
@@ -77,11 +158,12 @@ def pwe():
     pwe_ = _moose.getCwe()
     print(pwe_.getPath())
     return pwe_
-    
+
+
 def le(el=None):
     """List elements under `el` or current element if no argument
     specified.
-    
+
     Parameters
     ----------
     el : str/melement/vec/None
@@ -100,13 +182,14 @@ def le(el=None):
             raise ValueError('no such element')
         el = element(el)
     elif isinstance(el, vec):
-        el = el[0]    
+        el = el[0]
     print('Elements under', el.path)
     for ch in el.children:
         print(ch.path)
     return [child.path for child in el.children]
 
-ce = setCwe # ce is a GENESIS shorthand for change element.
+ce = setCwe  # ce is a GENESIS shorthand for change element.
+
 
 def syncDataHandler(target):
     """Synchronize data handlers for target.
@@ -134,6 +217,7 @@ First fix that issue with SynBase or something in that line.')
         target = vec(target)
         _moose.syncDataHandler(target)
 
+
 def showfield(el, field='*', showtype=False):
     """Show the fields of the element `el`, their data types and
     values in human readable format. Convenience function for GENESIS
@@ -159,13 +243,14 @@ def showfield(el, field='*', showtype=False):
         if not exists(el):
             raise ValueError('no such element')
         el = element(el)
-    if field == '*':        
+    if field == '*':
         value_field_dict = getFieldDict(el.className, 'valueFinfo')
         max_type_len = max(len(dtype) for dtype in value_field_dict.values())
         max_field_len = max(len(dtype) for dtype in value_field_dict.keys())
         print('\n[', el.path, ']')
-        for key, dtype in sorted( value_field_dict.items() ):
-            if dtype == 'bad' or key == 'this' or key == 'dummy' or key == 'me' or dtype.startswith('vector') or 'ObjId' in dtype:
+        for key, dtype in sorted(value_field_dict.items()):
+            if dtype == 'bad' or key == 'this' or key == 'dummy' or key == 'me' or dtype.startswith(
+                    'vector') or 'ObjId' in dtype:
                 continue
             value = el.getField(key)
             if showtype:
@@ -179,22 +264,26 @@ def showfield(el, field='*', showtype=False):
         try:
             print(field, '=', el.getField(field))
         except AttributeError:
-            pass # Genesis silently ignores non existent fields
+            pass  # Genesis silently ignores non existent fields
+
 
 def showfields(el, showtype=False):
     """Convenience function. Should be deprecated if nobody uses it.
 
     """
-    warnings.warn('Deprecated. Use showfield(element, field="*", showtype=True) instead.', DeprecationWarning)
+    warnings.warn(
+        'Deprecated. Use showfield(element, field="*", showtype=True) instead.',
+        DeprecationWarning)
     showfield(el, field='*', showtype=showtype)
 
-# Predefined field types and their human readable names    
-finfotypes = [('valueFinfo', 'value field') , 
+# Predefined field types and their human readable names
+finfotypes = [('valueFinfo', 'value field'),
               ('srcFinfo', 'source message field'),
               ('destFinfo', 'destination message field'),
               ('sharedFinfo', 'shared message field'),
               ('lookupFinfo', 'lookup field')]
 
+
 def listmsg(el):
     """Return a list containing the incoming and outgoing messages of
     `el`.
@@ -207,7 +296,7 @@ def listmsg(el):
     Returns
     -------
     msg : list
-        List of Msg objects corresponding to incoming and outgoing 
+        List of Msg objects corresponding to incoming and outgoing
         connections of `el`.
 
     """
@@ -219,6 +308,7 @@ def listmsg(el):
         ret.append(msg)
     return ret
 
+
 def showmsg(el):
     """Print the incoming and outgoing messages of `el`.
 
@@ -235,33 +325,44 @@ def showmsg(el):
     obj = element(el)
     print('INCOMING:')
     for msg in obj.msgIn:
-        print(msg.e2.path, msg.destFieldsOnE2, '<---', msg.e1.path, msg.srcFieldsOnE1)
+        print(
+            msg.e2.path,
+            msg.destFieldsOnE2,
+            '<---',
+            msg.e1.path,
+            msg.srcFieldsOnE1)
     print('OUTGOING:')
     for msg in obj.msgOut:
-        print(msg.e1.path, msg.srcFieldsOnE1, '--->', msg.e2.path, msg.destFieldsOnE2)
+        print(
+            msg.e1.path,
+            msg.srcFieldsOnE1,
+            '--->',
+            msg.e2.path,
+            msg.destFieldsOnE2)
+
 
 def getfielddoc(tokens, indent=''):
     """Return the documentation for field specified by `tokens`.
-    
+
     Parameters
     ----------
     tokens : (className, fieldName) str
-        A sequence whose first element is a MOOSE class name and second 
+        A sequence whose first element is a MOOSE class name and second
         is the field name.
-              
+
     indent : str
-        indentation (default: empty string) prepended to builtin 
+        indentation (default: empty string) prepended to builtin
         documentation string.
 
     Returns
     -------
     docstring : str
-        string of the form 
+        string of the form
         `{indent}{className}.{fieldName}: {datatype} - {finfoType}\n{Description}\n`
 
     Raises
     ------
-    NameError 
+    NameError
         If the specified fieldName is not present in the specified class.
     """
     assert(len(tokens) > 1)
@@ -272,7 +373,7 @@ def getfielddoc(tokens, indent=''):
             classelement = _moose.element('/classes/' + classname)
             for finfo in classelement.children:
                 for fieldelement in finfo:
-                    baseinfo = '' 
+                    baseinfo = ''
                     if classname != tokens[0]:
                         baseinfo = ' (inherited from {})'.format(classname)
                     if fieldelement.fieldName == fieldname:
@@ -288,20 +389,22 @@ def getfielddoc(tokens, indent=''):
                             docs=fieldelement.docs)
             classname = classelement.baseClass
         except ValueError:
-            raise NameError('`%s` has no field called `%s`' 
-                    % (tokens[0], tokens[1]))
-                    
-def toUnicode( v, encoding= 'utf8' ):
-    #if isinstance(v, str):
-        #return v
+            raise NameError('`%s` has no field called `%s`'
+                            % (tokens[0], tokens[1]))
+
+
+def toUnicode(v, encoding='utf8'):
+    # if isinstance(v, str):
+        # return v
     try:
         return v.decode(encoding)
     except (AttributeError, UnicodeEncodeError):
         return str(v)
-    
+
+
 def getmoosedoc(tokens, inherited=False):
     """Return MOOSE builtin documentation.
-  
+
     Parameters
     ----------
     tokens : (className, [fieldName])
@@ -313,7 +416,7 @@ def getmoosedoc(tokens, inherited=False):
 
     Returns
     -------
-    docstring : str        
+    docstring : str
         Documentation string for class `className`.`fieldName` if both
         are specified, for the class `className` if fieldName is not
         specified. In the latter case, the fields and their data types
@@ -323,7 +426,7 @@ def getmoosedoc(tokens, inherited=False):
     ------
     NameError
         If class or field does not exist.
-    
+
     """
     indent = '    '
     with closing(StringIO()) as docstring:
@@ -334,17 +437,17 @@ def getmoosedoc(tokens, inherited=False):
         except ValueError:
             raise NameError('name \'%s\' not defined.' % (tokens[0]))
         if len(tokens) > 1:
-            docstring.write( toUnicode( getfielddoc(tokens)) )
+            docstring.write(toUnicode(getfielddoc(tokens)))
         else:
-            docstring.write( toUnicode('%s\n' % (class_element.docs) ) )
+            docstring.write(toUnicode('%s\n' % (class_element.docs)))
             append_finfodocs(tokens[0], docstring, indent)
             if inherited:
                 mro = eval('_moose.%s' % (tokens[0])).mro()
                 for class_ in mro[1:]:
                     if class_ == _moose.melement:
                         break
-                    docstring.write( toUnicode( 
-                        '\n\n#Inherited from %s#\n' % (class_.__name__) ) )
+                    docstring.write(toUnicode(
+                        '\n\n#Inherited from %s#\n' % (class_.__name__)))
                     append_finfodocs(class_.__name__, docstring, indent)
                     if class_ == _moose.Neutral:    # Neutral is the toplevel moose class
                         break
@@ -358,38 +461,39 @@ def append_finfodocs(classname, docstring, indent):
     except ValueError:
         raise NameError('class \'%s\' not defined.' % (classname))
     for ftype, rname in finfotypes:
-        docstring.write( toUnicode( '\n*%s*\n' % (rname.capitalize())) )
+        docstring.write(toUnicode('\n*%s*\n' % (rname.capitalize())))
         try:
             finfo = _moose.element('%s/%s' % (class_element.path, ftype))
             for field in finfo.vec:
-                docstring.write( toUnicode( 
-                    '%s%s: %s\n' % (indent, field.fieldName, field.type)) )
+                docstring.write(toUnicode(
+                    '%s%s: %s\n' % (indent, field.fieldName, field.type)))
         except ValueError:
-            docstring.write( toUnicode( '%sNone\n' % (indent) ) )
-    
-    
+            docstring.write(toUnicode('%sNone\n' % (indent)))
+
+
 # the global pager is set from pydoc even if the user asks for paged
 # help once. this is to strike a balance between GENESIS user's
 # expectation of control returning to command line after printing the
 # help and python user's expectation of seeing the help via more/less.
-pager=None
+pager = None
+
 
 def doc(arg, inherited=True, paged=True):
     """Display the documentation for class or field in a class.
-    
+
     Parameters
     ----------
     arg : str/class/melement/vec
         A string specifying a moose class name and a field name
         separated by a dot. e.g., 'Neutral.name'. Prepending `moose.`
         is allowed. Thus moose.doc('moose.Neutral.name') is equivalent
-        to the above.    
+        to the above.
         It can also be string specifying just a moose class name or a
         moose class or a moose object (instance of melement or vec
         or there subclasses). In that case, the builtin documentation
         for the corresponding moose class is displayed.
 
-    paged: bool    
+    paged: bool
         Whether to display the docs via builtin pager or print and
         exit. If not specified, it defaults to False and
         moose.doc(xyz) will print help on xyz and return control to
@@ -431,7 +535,7 @@ def doc(arg, inherited=True, paged=True):
         pager(text)
     else:
         print(text)
-                
 
-# 
+
+#
 # moose.py ends here
diff --git a/python/moose/neuroml/MorphML.py b/python/moose/neuroml/MorphML.py
index cf217741e4c0ada360dc037dae918e7ab8197dfc..6b66346bfce93588a39bd0568256aba67f12caf7 100644
--- a/python/moose/neuroml/MorphML.py
+++ b/python/moose/neuroml/MorphML.py
@@ -632,7 +632,7 @@ class MorphML():
                     moose.connect(channel,'channel',compartment,'channel')
             ## if mechanism is present in compartment, just wrap it
             else:
-                neutralObj = moose.Neutral(compartment.path+'/'+mechanismname)
+                neutralObj = moose.element(compartment.path+'/'+mechanismname)
                 if 'CaConc' == neutralObj.className: # Ion concentration pool
                     caconc = moose.CaConc(compartment.path+'/'+mechanismname) # wraps existing channel
                     channel = None
diff --git a/python/moose/neuroml2/generated_neuromlsub.py b/python/moose/neuroml2/generated_neuromlsub.py
index 7e7957be79d98254c612e40fde43736a617f2f56..55e2300a6eda802370e3f03b5d675272d75dd70c 100644
--- a/python/moose/neuroml2/generated_neuromlsub.py
+++ b/python/moose/neuroml2/generated_neuromlsub.py
@@ -20,7 +20,8 @@
 import sys
 from lxml import etree as etree_
 
-import ??? as supermod
+# FIXME: Comment it out 
+# import ??? as supermod
 
 def parsexml_(infile, parser=None, **kwargs):
     if parser is None:
diff --git a/python/rdesigneur/rdesigneurProtos.py b/python/rdesigneur/rdesigneurProtos.py
index 48c7f904b1f2674ae6b96f83d031fb8f90eb82d7..ea794d9bf6f7d0e520b5827165a7a85c87232fd7 100644
--- a/python/rdesigneur/rdesigneurProtos.py
+++ b/python/rdesigneur/rdesigneurProtos.py
@@ -110,33 +110,33 @@ def make_HH_K(name = 'HH_K', parent='/library', vmin=-120e-3, vmax=40e-3, vdivs=
 #========================================================================
 
 def make_glu( name ):
-	if moose.exists( '/library/' + name ):
-		return
-	glu = moose.SynChan( '/library/' + name )
-	glu.Ek = 0.0
-	glu.tau1 = 2.0e-3
-	glu.tau2 = 9.0e-3
-        sh = moose.SimpleSynHandler( glu.path + '/sh' )
-        moose.connect( sh, 'activationOut', glu, 'activation' )
-        sh.numSynapses = 1
-        sh.synapse[0].weight = 1
-        return glu
+    if moose.exists( '/library/' + name ):
+        return
+    glu = moose.SynChan( '/library/' + name )
+    glu.Ek = 0.0
+    glu.tau1 = 2.0e-3
+    glu.tau2 = 9.0e-3
+    sh = moose.SimpleSynHandler( glu.path + '/sh' )
+    moose.connect( sh, 'activationOut', glu, 'activation' )
+    sh.numSynapses = 1
+    sh.synapse[0].weight = 1
+    return glu
 
 #========================================================================
 #                SynChan: GABA receptor
 #========================================================================
 
 def make_GABA( name ):
-	if moose.exists( '/library/' + name ):
-		return
-	GABA = moose.SynChan( '/library/' + name )
-	GABA.Ek = EK + 10.0e-3
-	GABA.tau1 = 4.0e-3
-	GABA.tau2 = 9.0e-3
-        sh = moose.SimpleSynHandler( GABA.path + '/sh' )
-        moose.connect( sh, 'activationOut', GABA, 'activation' )
-        sh.numSynapses = 1
-        sh.synapse[0].weight = 1
+    if moose.exists( '/library/' + name ):
+        return
+    GABA = moose.SynChan( '/library/' + name )
+    GABA.Ek = EK + 10.0e-3
+    GABA.tau1 = 4.0e-3
+    GABA.tau2 = 9.0e-3
+    sh = moose.SimpleSynHandler( GABA.path + '/sh' )
+    moose.connect( sh, 'activationOut', GABA, 'activation' )
+    sh.numSynapses = 1
+    sh.synapse[0].weight = 1
 
 
 def makeChemOscillator( name = 'osc', parent = '/library' ):
diff --git a/build-moose-core b/scripts/build-moose-core
similarity index 100%
rename from build-moose-core
rename to scripts/build-moose-core
diff --git a/scripts/color.sh b/scripts/color.sh
old mode 100644
new mode 100755
diff --git a/shell/Shell.cpp b/shell/Shell.cpp
index 8ba30eb5c5cdb564ad86a55bcf920cbb8fd76526..b2e3b2892e33890012b62fb65b82f9a68d71ec0b 100644
--- a/shell/Shell.cpp
+++ b/shell/Shell.cpp
@@ -28,11 +28,6 @@ using namespace std;
 // Want to separate out this search path into the Makefile options
 #include "../scheduling/Clock.h"
 
-/*#ifdef USE_SBML
-#include "../sbml/MooseSbmlWriter.h"
-#include "../sbml/MooseSbmlReader.h"
-#endif
-*/
 const unsigned int Shell::OkStatus = ~0;
 const unsigned int Shell::ErrorStatus = ~1;
 
@@ -51,10 +46,6 @@ double Shell::runtime_( 0.0 );
 const Cinfo* Shell::initCinfo()
 {
 
-#ifdef ENABLE_LOGGER
-    clock_t t = clock();
-#endif
-
 ////////////////////////////////////////////////////////////////
 // Value Finfos
 ////////////////////////////////////////////////////////////////
@@ -369,6 +360,21 @@ void Shell::doStart( double runtime, bool notify )
 {
     Id clockId( 1 );
     SetGet2< double, bool >::set( clockId, "start", runtime, notify );
+
+    /*-----------------------------------------------------------------------------
+     *  Now that simulation is over, call cleanUp function of Streamer class
+     *  objects. The purpose of this is to write whatever is left in tables to
+     *  the output file.
+     *-----------------------------------------------------------------------------*/
+    vector< ObjId > streamers;
+    wildcardFind( "/##[TYPE=Streamer]", streamers );
+    LOG( moose::debug,  "total streamers " << streamers.size( ) );
+    for( vector<ObjId>::const_iterator itr = streamers.begin()
+            ; itr != streamers.end(); itr++ )
+    {
+        Streamer* pStreamer = reinterpret_cast<Streamer*>( itr->data( ) );
+        pStreamer->cleanUp( );
+    }
 }
 
 bool isDoingReinit()
@@ -398,14 +404,6 @@ void Shell::doStop( )
 void Shell::doSetClock( unsigned int tickNum, double dt )
 {
     LookupField< unsigned int, double >::set( ObjId( 1 ), "tickDt", tickNum, dt );
-
-    // FIXME:
-    // HACK: If clock 18 is being updated, make sure that clock 19 (streamer is also
-    // updated with correct dt (10 or 100*dt). This is bit hacky.
-    if( tickNum == 18 )
-        LookupField< unsigned int, double >::set( ObjId( 1 ), "tickDt"
-                , tickNum + 1, max( 100 * dt, 10.0 )
-                );
 }
 
 void Shell::doUseClock( string path, string field, unsigned int tick )
@@ -416,41 +414,6 @@ void Shell::doUseClock( string path, string field, unsigned int tick )
     // innerUseClock( path, field, tick);
 }
 
-/**
- * Write given model to SBML file. Returns success value.
- */
- /*
-int Shell::doWriteSBML( const string& fname, const string& modelpath )
-{
-#ifdef USE_SBML
-    moose::SbmlWriter sw;
-    int ret = sw.write( fname, modelpath );
-    return ret;
-#else
-
-    cerr << "Shell::WriteSBML: This copy of MOOSE has not been compiled with SBML writing support.\n";
-    return -2;
-#endif
-}
-*/
-/**
- * read given SBML model to moose. Returns success value.
- */
-/*
-Id Shell::doReadSBML( const string& fname, const string& modelpath, const string& solverclass )
-{
-#ifdef USE_SBML
-    moose::SbmlReader sr;
-    return sr.read( fname, modelpath,solverclass);
-#else
-    cerr << "Shell::ReadSBML: This copy of MOOSE has not been compiled with SBML reading support.\n";
-    return Id();
-#endif
-}
-*/
-
-////////////////////////////////////////////////////////////////////////
-
 void Shell::doMove( Id orig, ObjId newParent )
 {
     if ( orig == Id() )
@@ -610,36 +573,6 @@ bool Shell::chopPath( const string& path, vector< string >& ret,
     return isAbsolute;
 }
 
-/*
-/// non-static func. Fallback which treats index brackets as part of
-/// name string, and does not try to extract integer indices.
-ObjId Shell::doFindWithoutIndexing( const string& path ) const
-{
-	Id curr = Id();
-	vector< string > names;
-	vector< vector< unsigned int > > indices;
-	bool isAbsolute = chopString( path, names, '/' );
-
-	if ( !isAbsolute )
-		curr = cwe_;
-
-	for ( vector< string >::iterator i = names.begin();
-		i != names.end(); ++i ) {
-		if ( *i == "." ) {
-		} else if ( *i == ".." ) {
-			curr = Neutral::parent( curr.eref() ).id;
-		} else {
-			curr = Neutral::child( curr.eref(), *i );
-		}
-	}
-
-	assert( curr.element() );
-	assert( curr.element()->dataHandler() );
-	return ObjId( curr, 0 );
-}
-*/
-
-/// non-static func. Returns the Id found by traversing the specified path.
 ObjId Shell::doFind( const string& path ) const
 {
     if ( path == "/" || path == "/root" )
@@ -1078,6 +1011,9 @@ void Shell::handleUseClock( const Eref& e,
     		*/
 }
 
+/**
+ * @brief This function is NOT called when simulation ends normally.
+ */
 void Shell::handleQuit()
 {
     Shell::keepLooping_ = 0;
@@ -1099,13 +1035,6 @@ void Shell::error( const string& text )
     cout << "Error: Shell:: " << text << endl;
 }
 
-/*
-void Shell::wildcard( const string& path, vector< ObjId >& list )
-{
-	wildcardFind( path, list );
-}
-*/
-
 /**
  * @brief Clean-up MOOSE before shutting down. This function is called whenever
  * keyboard interrupt terminates the simulation.
@@ -1118,7 +1047,7 @@ void Shell::cleanSimulation()
     Neutral::children( sheller, kids );
     for ( vector< Id >::iterator i = kids.begin(); i != kids.end(); ++i )
     {
-        if ( i->value() > 4 )
+        if ( i->value() > 4 )                   /* These are created by users */
         {
             LOG( moose::debug
                     , "Shell::cleanSimulation: deleted cruft at " <<
diff --git a/shell/Shell.h b/shell/Shell.h
index f3410f2f94d9d02d2ea584ca160d3176603ffa40..1b2a7f45a57173b46a528e0d65627415dd0c9056 100644
--- a/shell/Shell.h
+++ b/shell/Shell.h
@@ -26,627 +26,617 @@ extern DestFinfo* receiveGet();
 //extern SrcFinfo2< unsigned int, unsigned int >* ack(); // Not currently used.
 
 enum NodePolicy { MooseGlobal, MooseBlockBalance, MooseSingleNode };
-class NodeBalance {
-	public:
-		NodeBalance( unsigned int nd, NodePolicy np, unsigned int node )
-				: numData( nd ), policy( np ), preferredNode( node )
-		{;}
-
-		unsigned int numData;
-		NodePolicy policy;
-		unsigned int preferredNode;
+class NodeBalance
+{
+public:
+    NodeBalance( unsigned int nd, NodePolicy np, unsigned int node )
+        : numData( nd ), policy( np ), preferredNode( node )
+    {
+        ;
+    }
+
+    unsigned int numData;
+    NodePolicy policy;
+    unsigned int preferredNode;
 };
 
 class Shell
 {
-	public:
-		Shell();
-		~Shell();
+public:
+    Shell();
+    ~Shell();
 
 #ifdef  CYMOOSE
-                
-                    /**
-                     * @brief Initialize shell.
-                     *
-                     * @return Pointer to shell.
-                     *
-                     * This function initialize shell and returns a pointer to it.
-                     * This function must create a fully functional shell which can
-                     * be used by cython interface.
-                     */
-                    Shell* initShell();
-
-
-                /**
-                 * @brief A thin wrapper around doCreate function. Used in
-                 * cython interface.
-                 *
-                 * @param type Type of Moose-element to be created e.g. Table,
-                 * Compartment, etc.
-                 * @param parent Parent element under which this element is
-                 * being created.
-                 * @param name Name of the element. String.
-                 * @param numData 
-                 * @param nodePolicy
-                 * @param preferredNode
-                 *
-                 * @return Id of the element.
-                 */
-                Id create( string type, string name, unsigned int numData, 
-                        NodePolicy nodePolicy = MooseBlockBalance,
-                        unsigned int preferredNode = 1 );
+
+    /**
+     * @brief Initialize shell.
+     *
+     * @return Pointer to shell.
+     *
+     * This function initialize shell and returns a pointer to it.
+     * This function must create a fully functional shell which can
+     * be used by cython interface.
+     */
+    Shell* initShell();
+
+
+    /**
+     * @brief A thin wrapper around doCreate function. Used in
+     * cython interface.
+     *
+     * @param type Type of Moose-element to be created e.g. Table,
+     * Compartment, etc.
+     * @param parent Parent element under which this element is
+     * being created.
+     * @param name Name of the element. String.
+     * @param numData
+     * @param nodePolicy
+     * @param preferredNode
+     *
+     * @return Id of the element.
+     */
+    Id create( string type, string name, unsigned int numData,
+               NodePolicy nodePolicy = MooseBlockBalance,
+               unsigned int preferredNode = 1 );
 
 
 #endif     /* -----  CYMOOSE  ----- */
-		///////////////////////////////////////////////////////////
-		// Field functions
-		///////////////////////////////////////////////////////////
-                /**
-                 * Returns version number of the software.
-                 */
-                string doVersion();
-
-		/**
-		 * Assigns the current working Element of the Shell
-		 */
-		void setCwe( ObjId cwe );
-
-		/**
-		 * Returns the current working Element of the Shell
-		 */
-		ObjId getCwe() const;
-
-		/**
-		 * Returns flag to indicate whether simulation is still running
-		 */
-		bool isRunning() const;
-
-		///////////////////////////////////////////////////////////
-		// Parser functions
-		///////////////////////////////////////////////////////////
-
-		/**
-		 * Create an Element. Returns its id.
-		 * type: Specifies classname of Objects in Element.
-		 * parent: Id of parent element
-		 * name: Name to be used for identifying Element.
-		 * numData: Size of array.
-		 */
-		Id doCreate( string type, ObjId parent, string name, 
-				unsigned int numData, 
-				NodePolicy nodePolicy = MooseBlockBalance,
-				unsigned int preferredNode = 1 );
-
-		/**
-		 * Delete specified Element and all its children and all 
-		 * Msgs connected to it. This also works for Msgs, which are
-		 * also identified by an ObjId. Unlike regular objects, only
-		 * the one Msg entry specified by the DataIndex part of the ObjId
-		 * argument is deleted. 
-		 */
-		bool doDelete( ObjId oid );
-
-		/**
-		 * Sets up a Message of specified type.
-		 * Later need to consider doing this through MsgSpecs only.
-		 * Here the 'args' vector handles whatever arguments we may need
-		 * to pass to the specified msgType.
-		 */
-		ObjId doAddMsg( const string& msgType, 
-			ObjId src, const string& srcField, 
-			ObjId dest, const string& destField );
-
-		/**
-		 * Cleanly quits simulation, wrapping up all nodes and threads.
-		 */
-		void doQuit( );
-
-		/**
-		 * Starts off simulation, to run for 'runtime' more than current
-		 * time. This version is blocking, and returns only when the 
-		 * simulation is done. If `nofity = true' then also notify user
-                 * whenever 10\% of simulation is over.
-		 */
-		void doStart( double runtime, bool notify = false );
-
-		/**
-		 * Starts off simulation, to run for 'runtime' more than current
-		 * time. This version returns at once, and the parser can go
-		 * on to do other things. It has to check with the 
-		 * Shell::isRunning function (accessible as a MOOSE field)
-		 * to find out if it is finished. Can call 'doStop', 'doTerminate'
-		 * or 'doReinit' at any time to stop the run with increasing
-		 * levels of prejudice.
-		 */
-		void doNonBlockingStart( double runtime );
-
-		/**
-		 * Reinitializes simulation: time goes to zero, all scheduled
-		 * objects are set to initial conditions. If simulation is
-		 * already running, first stops it.
-		 */
-		void doReinit();
-
-		/**
-		 * Cleanly stops simulation, ready to take up again from where
-		 * the stop occurred. Waits till current operations are done.
-		 */
-		void doStop();
-
-		/**
-		 * Terminate ongoing simulation, with prejudice.
-		 * Uncleanly stops simulation. Things may be in a mess with
-		 * different objects at different times, but it stops at once.
-		 */
-		void doTerminate();
-
-		/**
-		 * shifts orig Element (including offspring) to newParent. All old 
-		 * hierarchy, data, Msgs etc are preserved below the orig.
-		 */
-		void doMove( Id orig, ObjId newParent );
-
-		/**
-		 * Copies orig Element to newParent. n specifies how many copies
-		 * are made.
-		 * copyExtMsgs specifies whether to also copy messages from orig
-		 * to objects outside the copy tree. Usually we don't do this.
-		 */
-		Id doCopy( Id orig, ObjId newParent, string newName,
-			unsigned int n, bool toGlobal, bool copyExtMsgs );
-
-		/**
-		 * Looks up the Id specified by the given path. May include
-		 * relative references and the internal cwe 
-		 * (current working Element) on the shell
-		 */
-		ObjId doFind( const string& path ) const;
-
-		/**
-		 * Deprecated.
-		 * Fallback Find function which treats index brackets as part of 
-		 * name string, and does not try to extract integer indices.
-		ObjId doFindWithoutIndexing( const string& path ) const;
-		 */
-
-		/**
-		 * Connects up process messages from the specified Tick to the
-		 * targets on the path. Does so for whole Elements, not individual
-		 * entries in the Element array.
-		 * The target on the path usually has the 'process' field but
-		 * other options are allowed, like 'init'
-		 */
-		void doUseClock( string path, string field, unsigned int tick );
-
-		/**
-		 * Loads in a model to a specified path.
-		 * Tries to figure out model type from fname or contents of file.
-		 * Currently knows about kkit, cspace.
-		 * Soon to learn .p, SBML, NeuroML.
-		 * Later to learn NineML
-		 */
-		 Id doLoadModel( const string& fname, const string& modelpath, 
-		 	const string& solverClass = "" );
-
-		/**
-		 * Saves specified model to specified file, using filetype 
-		 * identified by filename extension. Currently known filetypes are:
-		 * .g: Kkit model
-		 *
-		 * Still to come:
-		 * .p: GENESIS neuron morphology and channel spec file
-		 * .sbml: SBML file
-		 * .nml: NeuroML file
-		 * .9ml: NineML file
-		 * .snml: SigNeurML
-		 */
-		 void doSaveModel( Id model, const string& fileName, 
-			 bool qflag = 0 ) const;
-		
-		/**
-		 * Write given model to SBML file. Returns success value.
-		 */
-		 //int doWriteSBML( const string& fname, const string& modelpath );
-		 //Id doReadSBML( const string& fname, const string& modelpath, const string& solverclass=""
-		 //);
-		 
-		/**
- 		 * This function synchronizes fieldDimension on the DataHandler 
-		 * across nodes. Used after function calls that might alter the
-		 * number of Field entries in the table..
- 		 * The tgt is the FieldElement whose fieldDimension needs updating.
- 		 */
-		void doSyncDataHandler( Id tgt );
-
-		/**
- 		 * This function builds a reac-diffusion mesh starting at the
- 		 * specified ChemCompt, which houses MeshEntry FieldElements.
- 		 * Assumes that the dimensions of the baseCompartment have just been
- 		 * redefined, and we now need to go through and update the child 
- 		 * reaction system.
- 		 */
-		void doReacDiffMesh( Id baseCompartment );
-
-		/**
-		 * This function is called by the parser to tell the ProcessLoop
-		 * to wait a bit between cycles. Used when we are waiting for user
-		 * input and there is no point in having the ProcessLoop go at
-		 * full speed. When flag is true, then the ProcessLoop will sleep
-		 * a bit, when false it will work at full speed.
-		 */
-		void doSetParserIdleFlag( bool isParserIdle );
-
-		/**
-		 * Works through internal queue of operations that modify the
-		 * structure of the simulation. These operations have to be 
-		 * carefully separated from any other functions or messaging,
-		 * so this happens while all other threads are blocked. 
-		 */
-		static void clearRestructuringQ();
-		///////////////////////////////////////////////////////////
-		// DestFinfo functions
-		///////////////////////////////////////////////////////////
-
-		/**
-		 * Sets of a simulation for duration runTime. Handles
-		 * cases including single-thread, multithread, and multinode
-		 */
-		void start( double runTime );
-
-		/**
- 		 * Initialize acks. This call should be done before the 'send' goes 
- 		 * out, because with the wonders of threading we might get a 
-		 * response to the 'send' before this call is executed.
- 		 * This MUST be followed by a waitForAck call.
- 		 */
-		void initAck();
-
-		/**
- 		 * test for completion of request. This MUST be preceded by an
- 		 * initAck call.
- 		 */
-		void waitForAck();
-
-		/**
- 		 * Generic handler for ack msgs from various nodes. Keeps track of
- 		 * which nodes have responded.
- 		 */
-		void handleAck( unsigned int ackNode, unsigned int status );
-
-		/**
- 		 * Test for receipt of acks from all nodes
- 		 */ 
-		bool isAckPending() const;
-
-		/**
-		 * Wraps up operations. Doesn't quit instantly, completes the
-		 * current process cycle first.
-		 */
-		void handleQuit();
-
-		void handleCreate( const Eref& e,
-			string type, ObjId parent, Id newElm, string name,
-			NodeBalance nb, unsigned int parentMsgIndex );
-		void destroy( const Eref& e, ObjId oid);
-
-		/**
-		 * Function that does the actual work of creating a new Element.
-		 * The Class of the Moose objects formed is specified by type.
-		 * The NodeBalance specifies how many entries and how they are
-		 * distributed across nodes.
-		 * The parentMsgIndex specifies the index for the 
-		 * parent-child message.
-		 */
-		void innerCreate( string type, ObjId parent, Id newElm, string name,
-			const NodeBalance& nb, unsigned int parentMsgIndex );
-
-		/// Does actual work of copying. Returns true on success.
-		bool innerCopy( const vector< ObjId >& args, const string& newName,
-			unsigned int n, bool toGlobal, bool copyExtMsgs );
-
-		/**
-		 * Connects src to dest on appropriate fields, with specified
-		 * msgType. 
-		 * This inner function does NOT send an ack. Returns true on 
-		 * success
-		 */
-		const Msg* innerAddMsg( string msgType, ObjId src, string srcField, 
-			ObjId dest, string destField, unsigned int msgIndex );
-
-		/**
-		 * Connects src to dest on appropriate fields, with specified
-		 * msgType. 
-		 * This wrapper function sends the ack back to the master node.
-		 */
-		void handleAddMsg( const Eref& e, 
-			string msgType,
-			ObjId src, string srcField, 
-			ObjId dest, string destField, 
-			unsigned int msgIndex );
-
-		/**
-		 * Moves Element orig onto the newParent.
-		 */
-		bool innerMove( Id orig, ObjId newParent );
-
-		/**
-		 * Handler to move Element orig onto the newParent.
-		 */
-		void handleMove( const Eref& e,
-			Id orig, ObjId newParent );
-
-		/**
-		 * Handles sync of DataHandler indexing across nodes
-		 */
-		void handleSync( const Eref& e, Id elm, FuncId fid);
-
-		/**
-		 * Deep copy of source element to target, renaming it to newName.
-		 * The Args are orig, newParent, newElm
-		 * where the newElm is the Id passed in for the root of the copy.
-		 * All subsequent created Elements should have successive Ids.
-		 * The copy may generate an array with n entries.
-		 * Normally only copies msgs within the tree, but if the flag
-		 * copyExtMsgs is true then it copies external Msgs too.
-		 */
-		void handleCopy( const Eref& e,
-			vector< ObjId > args, string newName, unsigned int n, 
-			bool toGlobal, bool copyExtMsgs );
-
-		/**
-		 * Sets up scheduling for elements on the path.
-		 */
-		bool innerUseClock( string path, string field, 
-						unsigned int tick, unsigned int msgIndex);
-		void handleUseClock( const Eref& e,
-			string path, string field, unsigned int tick, 
-			unsigned int msgIndex );
-
-		/**
-		 * Utility function to set up messages to schedule a list of Ids 
-		 * using the specified field and tick
-		 */
-		void addClockMsgs( const vector< ObjId >& list, 
-			const string& field, unsigned int tick, unsigned int msgIndex );
-
-		/**
-		 * Utility function to unschedule the specified elist operating
-		 * on the specified field, typically 'process'
-		 */
-		static void dropClockMsgs(
-			const vector< ObjId >& list, const string& field );
-		////////////////////////////////////////////////////////////////
-		// Thread and MPI handling functions
-		////////////////////////////////////////////////////////////////
-		
-		/**
-		 * Assigns the hardware availability. Assumes that each node will
-		 * have the same number of cores available.
-		 */
-		static void setHardware( 
-			unsigned int numCores, unsigned int numNodes, 
-			unsigned int myNode );
-
-		static unsigned int myNode();
-		static unsigned int numNodes();
-		static unsigned int numCores();
-		static unsigned int numProcessThreads();
-
-		/**
-		 * Stub for eventual function to handle load balancing. This must
-		 * be called to set up default groups.
-		 */
-		static void loadBalance();
-
-		static void launchParser();
-
-		/**
-	 	 * True when the parser is in a call which is being blocked because
-		 * it requires the event loop to complete some actions.
-		 */
-		static bool inBlockingParserCall();
-
-		/**
-		 * True in single-threaded mode. This is a special mode of
-		 * the system in which it does not start up the event loop
-		 * at all, and the whole thing operates on one thread, which
-		 * is ultimately under the control of the parser.
-		 * Note that this is distinct from running on one core. It is
-		 * possible, and even recommended, to run in multithread mode
-		 * even when the system has just one core to run it on.
-		 */
-		static bool isSingleThreaded();
-
-		/**
-		 * True as long as the main process loop is looping
-		 */
-		static bool keepLooping();
-
-		/**
-		 * Flag to indicate if the parser is idle. If so, the main
-		 * ProcessLoop should also slow down to avoid pounding on the CPUs
-		 */
-		static bool isParserIdle();
-
-		/**
-		 * This function sets up the threading for the entire system.
-		 * It creates all the worker threads and the threads for
-		 * handling MPI and handling shell requests.
-		 */
-		static void launchThreads();
-
-		/**
-		 * Checks for highest 'val' on all nodes
-		 */
-		static unsigned int reduceInt( unsigned int val );
-
-		////////////////////////////////////////////////////////////////
-		// Sets up clock ticks. Essentially is a call into the 
-		// Clock::setupTick function, but may be needed to be called from
-		// the parser so it is a Shell function too.
-		void doSetClock( unsigned int tickNum, double dt );
-
-		// Should set these up as streams so that we can build error
-		// messages similar to cout.
-		void warning( const string& text );
-		void error( const string& text );
-
-		static const Cinfo* initCinfo();
-
-		////////////////////////////////////////////////////////////////
-		// Utility functions
-		////////////////////////////////////////////////////////////////
-		static bool adopt( ObjId parent, Id child, unsigned int msgIndex );
-		static bool adopt( Id parent, Id child, unsigned int msgIndex );
-
-		static const unsigned int OkStatus;
-		static const unsigned int ErrorStatus;
-
-		// Initialization function, used only in main.cpp:init()
-		void setShellElement( Element* shelle );
-
-		/// Static func for returning the ProcInfo of the shell.
-		static const ProcInfo* procInfo();
-
-		const ProcInfo* getProcInfo( unsigned int index ) const;
-
-		/**
- 		 * Chops up the names in the string into the vector of strings,
-		 * using the specified separator.
- 		 * Returns true if it is an absolute path, that is, starts with the
-		 * separator.
-		 */
-		static bool chopString( const string& path, vector< string >& ret,
-			char separator = '/' );
-
-		/** 
-		 * Checks that the provided name is valid for an object.
-		 * This returns false if it finds the reserved path chars /#[]
-		 */
-		static bool isNameValid( const string& name );
-
-		/**
-		 * Chop up the path into a vector of Element names, and 
- 		 * also fills out a matching vector of indices. If at any level of
- 		 * the path there are no indices or the index is zero, the 
-		 * index entry * remains empty. Otherwise the entry contains a 
-		 * vector with index values for this level of the path. 
-		 * The zeroth position of this index vector is the slowest
- 		 * varying, i.e., most significant.
- 		 * Returns true if it starts at '/'.
- 		 *
- 		 * Example: /foo/bar[10]/zod[3][4][5] would return:
- 		 * ret: {"foo", "bar", "zod" }
- 		 * index: { {}, {10}, {3,4,5} }
- 		 */
-		static bool chopPath( const string& path, vector< string >& ret,
-			vector< unsigned int >& index ); 
-
-		// static void wildcard( const string& path, vector< Id >& list );
-
-		/**
-		 * Cleans up all Elements except /root itself, /clock, /classes,
-		 * and /Msgs.
-		 * In due course will also do suitable reinitialization of
-		 * tick and other values.
-		 */
-		 static void cleanSimulation();
-
-		/**
-		 * set the gettingVector_ flag 
-		 */
-		void expectVector( bool flag );
-		
-	private:
-		Element* shelle_; // It is useful for the Shell to have this.
-
-		/**
-		 * Buffer into which return values from the 'get' command are placed
-		 * Only index 0 is used for any single-value 'get' call.
-		 * If it was the 'getVec' command then the array is filled up
-		 */
-		vector< double* > getBuf_;
-
-		/**
-		 * Flag, used by the 'get' subsystem which maintains a buffer for
-		 * returned value. True when the returned value is a vector.
-		 */
-		bool gettingVector_;
-
-		/**
-		 * Counter, used by the 'get' subsystem in order to keep track of
-		 * number of returned values, especially for getVec.
-		 */
-		unsigned int numGetVecReturns_;
-
-		/**
-		 * Flag: True when the parser thread is blocked waiting for 
-		 * some system call to be handled by the threading and the 
-		 * MPI connected nodes.
-		 */
-		static bool isBlockedOnParser_;
-
-		/**
-		 * Flag: Tells the ProcessLoop to keep on going.
-		 * Should only be altered during a barrier.
-		 */
-		static bool keepLooping_;
-
-		/**
-		 * Number of CPU cores in system. 
-		 */
-		static unsigned int numCores_;
-
-		/**
-		 * Number of threads dedicated to the ProcessLoop.
-		 * The parser thread is the master thread.
-		 * Additional threads may be created for graphics, but not now.
-		 */
-		 static unsigned int numProcessThreads_;
-
-		/**
-		 * Number of nodes in MPI-based system. Each node may have many
-		 * threads.
-		 */
-		static unsigned int numNodes_;
-
-		/**
-		 * Identifier for current node
-		 */
-		static unsigned int myNode_;
-
-		/**
-		 * Shell owns its own ProcInfo, has global thread/node info.
-		 * Used to talk to parser and for thread specification in
-		 * setup operations.
-		 */
-		static ProcInfo p_; 
-
-		static vector< ProcInfo > threadProcs_;
-
-		/**
-		 * Array of threads, initialized in launchThreads.
-		 */
-
-		static unsigned int numAcks_;
-		static vector< unsigned int > acked_;
-
-
-		/**
-		 * Flag to tell system to reinitialize. We use this to defer the
-		 * actual operation to the 'process' call for a clean reinit.
-		 */
-		static bool doReinit_;
-
-		/**
-		 * Simulation run time
-		 */
-		static double runtime_;
-
-		static bool isParserIdle_;
-
-		/// Current working Element
-		ObjId cwe_;
+    ///////////////////////////////////////////////////////////
+    // Field functions
+    ///////////////////////////////////////////////////////////
+    /**
+     * Returns version number of the software.
+     */
+    string doVersion();
+
+    /**
+     * Assigns the current working Element of the Shell
+     */
+    void setCwe( ObjId cwe );
+
+    /**
+     * Returns the current working Element of the Shell
+     */
+    ObjId getCwe() const;
+
+    /**
+     * Returns flag to indicate whether simulation is still running
+     */
+    bool isRunning() const;
+
+    ///////////////////////////////////////////////////////////
+    // Parser functions
+    ///////////////////////////////////////////////////////////
+
+    /**
+     * Create an Element. Returns its id.
+     * type: Specifies classname of Objects in Element.
+     * parent: Id of parent element
+     * name: Name to be used for identifying Element.
+     * numData: Size of array.
+     */
+    Id doCreate( string type, ObjId parent, string name,
+                 unsigned int numData,
+                 NodePolicy nodePolicy = MooseBlockBalance,
+                 unsigned int preferredNode = 1 );
+
+    /**
+     * Delete specified Element and all its children and all
+     * Msgs connected to it. This also works for Msgs, which are
+     * also identified by an ObjId. Unlike regular objects, only
+     * the one Msg entry specified by the DataIndex part of the ObjId
+     * argument is deleted.
+     */
+    bool doDelete( ObjId oid );
+
+    /**
+     * Sets up a Message of specified type.
+     * Later need to consider doing this through MsgSpecs only.
+     * Here the 'args' vector handles whatever arguments we may need
+     * to pass to the specified msgType.
+     */
+    ObjId doAddMsg( const string& msgType,
+                    ObjId src, const string& srcField,
+                    ObjId dest, const string& destField );
+
+    /**
+     * Cleanly quits simulation, wrapping up all nodes and threads.
+     */
+    void doQuit( );
+
+    /**
+     * Starts off simulation, to run for 'runtime' more than current
+     * time. This version is blocking, and returns only when the
+     * simulation is done. If `nofity = true' then also notify user
+             * whenever 10\% of simulation is over.
+     */
+    void doStart( double runtime, bool notify = false );
+
+    /**
+     * Starts off simulation, to run for 'runtime' more than current
+     * time. This version returns at once, and the parser can go
+     * on to do other things. It has to check with the
+     * Shell::isRunning function (accessible as a MOOSE field)
+     * to find out if it is finished. Can call 'doStop', 'doTerminate'
+     * or 'doReinit' at any time to stop the run with increasing
+     * levels of prejudice.
+     */
+    void doNonBlockingStart( double runtime );
+
+    /**
+     * Reinitializes simulation: time goes to zero, all scheduled
+     * objects are set to initial conditions. If simulation is
+     * already running, first stops it.
+     */
+    void doReinit();
+
+    /**
+     * Cleanly stops simulation, ready to take up again from where
+     * the stop occurred. Waits till current operations are done.
+     */
+    void doStop();
+
+    /**
+     * Terminate ongoing simulation, with prejudice.
+     * Uncleanly stops simulation. Things may be in a mess with
+     * different objects at different times, but it stops at once.
+     */
+    void doTerminate();
+
+    /**
+     * shifts orig Element (including offspring) to newParent. All old
+     * hierarchy, data, Msgs etc are preserved below the orig.
+     */
+    void doMove( Id orig, ObjId newParent );
+
+    /**
+     * Copies orig Element to newParent. n specifies how many copies
+     * are made.
+     * copyExtMsgs specifies whether to also copy messages from orig
+     * to objects outside the copy tree. Usually we don't do this.
+     */
+    Id doCopy( Id orig, ObjId newParent, string newName,
+               unsigned int n, bool toGlobal, bool copyExtMsgs );
+
+    /**
+     * Looks up the Id specified by the given path. May include
+     * relative references and the internal cwe
+     * (current working Element) on the shell
+     */
+    ObjId doFind( const string& path ) const;
+
+    /**
+     * Connects up process messages from the specified Tick to the
+     * targets on the path. Does so for whole Elements, not individual
+     * entries in the Element array.
+     * The target on the path usually has the 'process' field but
+     * other options are allowed, like 'init'
+     */
+    void doUseClock( string path, string field, unsigned int tick );
+
+    /**
+     * Loads in a model to a specified path.
+     * Tries to figure out model type from fname or contents of file.
+     * Currently knows about kkit, cspace.
+     * Soon to learn .p, SBML, NeuroML.
+     * Later to learn NineML
+     */
+    Id doLoadModel( const string& fname, const string& modelpath,
+                    const string& solverClass = "" );
+
+    /**
+     * Saves specified model to specified file, using filetype
+     * identified by filename extension. Currently known filetypes are:
+     * .g: Kkit model
+     *
+     * Still to come:
+     * .p: GENESIS neuron morphology and channel spec file
+     * .sbml: SBML file
+     * .nml: NeuroML file
+     * .9ml: NineML file
+     * .snml: SigNeurML
+     */
+    void doSaveModel( Id model, const string& fileName, bool qflag = 0 ) const;
+
+    /**
+     * This function synchronizes fieldDimension on the DataHandler
+     * across nodes. Used after function calls that might alter the
+     * number of Field entries in the table..
+     * The tgt is the FieldElement whose fieldDimension needs updating.
+     */
+    void doSyncDataHandler( Id tgt );
+
+    /**
+     * This function builds a reac-diffusion mesh starting at the
+     * specified ChemCompt, which houses MeshEntry FieldElements.
+     * Assumes that the dimensions of the baseCompartment have just been
+     * redefined, and we now need to go through and update the child
+     * reaction system.
+     */
+    void doReacDiffMesh( Id baseCompartment );
+
+    /**
+     * This function is called by the parser to tell the ProcessLoop
+     * to wait a bit between cycles. Used when we are waiting for user
+     * input and there is no point in having the ProcessLoop go at
+     * full speed. When flag is true, then the ProcessLoop will sleep
+     * a bit, when false it will work at full speed.
+     */
+    void doSetParserIdleFlag( bool isParserIdle );
+
+    /**
+     * Works through internal queue of operations that modify the
+     * structure of the simulation. These operations have to be
+     * carefully separated from any other functions or messaging,
+     * so this happens while all other threads are blocked.
+     */
+    static void clearRestructuringQ();
+    ///////////////////////////////////////////////////////////
+    // DestFinfo functions
+    ///////////////////////////////////////////////////////////
+
+    /**
+     * Sets of a simulation for duration runTime. Handles
+     * cases including single-thread, multithread, and multinode
+     */
+    void start( double runTime );
+
+    /**
+     * Initialize acks. This call should be done before the 'send' goes
+     * out, because with the wonders of threading we might get a
+     * response to the 'send' before this call is executed.
+     * This MUST be followed by a waitForAck call.
+     */
+    void initAck();
+
+    /**
+     * test for completion of request. This MUST be preceded by an
+     * initAck call.
+     */
+    void waitForAck();
+
+    /**
+     * Generic handler for ack msgs from various nodes. Keeps track of
+     * which nodes have responded.
+     */
+    void handleAck( unsigned int ackNode, unsigned int status );
+
+    /**
+     * Test for receipt of acks from all nodes
+     */
+    bool isAckPending() const;
+
+    /**
+     * Wraps up operations. Doesn't quit instantly, completes the
+     * current process cycle first.
+     */
+    void handleQuit();
+
+    void handleCreate( const Eref& e,
+                       string type, ObjId parent, Id newElm, string name,
+                       NodeBalance nb, unsigned int parentMsgIndex );
+    void destroy( const Eref& e, ObjId oid);
+
+    /**
+     * Function that does the actual work of creating a new Element.
+     * The Class of the Moose objects formed is specified by type.
+     * The NodeBalance specifies how many entries and how they are
+     * distributed across nodes.
+     * The parentMsgIndex specifies the index for the
+     * parent-child message.
+     */
+    void innerCreate( string type, ObjId parent, Id newElm, string name,
+                      const NodeBalance& nb, unsigned int parentMsgIndex );
+
+    /// Does actual work of copying. Returns true on success.
+    bool innerCopy( const vector< ObjId >& args, const string& newName,
+                    unsigned int n, bool toGlobal, bool copyExtMsgs );
+
+    /**
+     * Connects src to dest on appropriate fields, with specified
+     * msgType.
+     * This inner function does NOT send an ack. Returns true on
+     * success
+     */
+    const Msg* innerAddMsg( string msgType, ObjId src, string srcField,
+                            ObjId dest, string destField, unsigned int msgIndex );
+
+    /**
+     * Connects src to dest on appropriate fields, with specified
+     * msgType.
+     * This wrapper function sends the ack back to the master node.
+     */
+    void handleAddMsg( const Eref& e,
+                       string msgType,
+                       ObjId src, string srcField,
+                       ObjId dest, string destField,
+                       unsigned int msgIndex );
+
+    /**
+     * Moves Element orig onto the newParent.
+     */
+    bool innerMove( Id orig, ObjId newParent );
+
+    /**
+     * Handler to move Element orig onto the newParent.
+     */
+    void handleMove( const Eref& e,
+                     Id orig, ObjId newParent );
+
+    /**
+     * Handles sync of DataHandler indexing across nodes
+     */
+    void handleSync( const Eref& e, Id elm, FuncId fid);
+
+    /**
+     * Deep copy of source element to target, renaming it to newName.
+     * The Args are orig, newParent, newElm
+     * where the newElm is the Id passed in for the root of the copy.
+     * All subsequent created Elements should have successive Ids.
+     * The copy may generate an array with n entries.
+     * Normally only copies msgs within the tree, but if the flag
+     * copyExtMsgs is true then it copies external Msgs too.
+     */
+    void handleCopy( const Eref& e,
+                     vector< ObjId > args, string newName, unsigned int n,
+                     bool toGlobal, bool copyExtMsgs );
+
+    /**
+     * Sets up scheduling for elements on the path.
+     */
+    bool innerUseClock( string path, string field,
+                        unsigned int tick, unsigned int msgIndex);
+
+    void handleUseClock( const Eref& e,
+                         string path, string field, unsigned int tick,
+                         unsigned int msgIndex );
+
+    /**
+     * Utility function to set up messages to schedule a list of Ids
+     * using the specified field and tick
+     */
+    void addClockMsgs( const vector< ObjId >& list,
+                       const string& field, unsigned int tick, unsigned int msgIndex );
+
+    /**
+     * Utility function to unschedule the specified elist operating
+     * on the specified field, typically 'process'
+     */
+    static void dropClockMsgs(
+        const vector< ObjId >& list, const string& field );
+
+    ////////////////////////////////////////////////////////////////
+    // Thread and MPI handling functions
+    ////////////////////////////////////////////////////////////////
+
+    /**
+     * Assigns the hardware availability. Assumes that each node will
+     * have the same number of cores available.
+     */
+    static void setHardware(
+        unsigned int numCores, unsigned int numNodes,
+        unsigned int myNode );
+
+    static unsigned int myNode();
+    static unsigned int numNodes();
+    static unsigned int numCores();
+    static unsigned int numProcessThreads();
+
+    /**
+     * Stub for eventual function to handle load balancing. This must
+     * be called to set up default groups.
+     */
+    static void loadBalance();
+
+    static void launchParser();
+
+    /**
+     * True when the parser is in a call which is being blocked because
+     * it requires the event loop to complete some actions.
+     */
+    static bool inBlockingParserCall();
+
+    /**
+     * True in single-threaded mode. This is a special mode of
+     * the system in which it does not start up the event loop
+     * at all, and the whole thing operates on one thread, which
+     * is ultimately under the control of the parser.
+     * Note that this is distinct from running on one core. It is
+     * possible, and even recommended, to run in multithread mode
+     * even when the system has just one core to run it on.
+     */
+    static bool isSingleThreaded();
+
+    /**
+     * True as long as the main process loop is looping
+     */
+    static bool keepLooping();
+
+    /**
+     * Flag to indicate if the parser is idle. If so, the main
+     * ProcessLoop should also slow down to avoid pounding on the CPUs
+     */
+    static bool isParserIdle();
+
+    /**
+     * This function sets up the threading for the entire system.
+     * It creates all the worker threads and the threads for
+     * handling MPI and handling shell requests.
+     */
+    static void launchThreads();
+
+    /**
+     * Checks for highest 'val' on all nodes
+     */
+    static unsigned int reduceInt( unsigned int val );
+
+    ////////////////////////////////////////////////////////////////
+    // Sets up clock ticks. Essentially is a call into the
+    // Clock::setupTick function, but may be needed to be called from
+    // the parser so it is a Shell function too.
+    void doSetClock( unsigned int tickNum, double dt );
+
+    // Should set these up as streams so that we can build error
+    // messages similar to cout.
+    void warning( const string& text );
+    void error( const string& text );
+
+    static const Cinfo* initCinfo();
+
+    ////////////////////////////////////////////////////////////////
+    // Utility functions
+    ////////////////////////////////////////////////////////////////
+    static bool adopt( ObjId parent, Id child, unsigned int msgIndex );
+    static bool adopt( Id parent, Id child, unsigned int msgIndex );
+
+    static const unsigned int OkStatus;
+    static const unsigned int ErrorStatus;
+
+    // Initialization function, used only in main.cpp:init()
+    void setShellElement( Element* shelle );
+
+    /// Static func for returning the ProcInfo of the shell.
+    static const ProcInfo* procInfo();
+
+    const ProcInfo* getProcInfo( unsigned int index ) const;
+
+    /**
+     * Chops up the names in the string into the vector of strings,
+     * using the specified separator.
+     * Returns true if it is an absolute path, that is, starts with the
+     * separator.
+     */
+    static bool chopString( const string& path, vector< string >& ret,
+                            char separator = '/' );
+
+    /**
+     * Checks that the provided name is valid for an object.
+     * This returns false if it finds the reserved path chars /#[]
+     */
+    static bool isNameValid( const string& name );
+
+    /**
+     * Chop up the path into a vector of Element names, and
+     * also fills out a matching vector of indices. If at any level of
+     * the path there are no indices or the index is zero, the
+     * index entry * remains empty. Otherwise the entry contains a
+     * vector with index values for this level of the path.
+     * The zeroth position of this index vector is the slowest
+     * varying, i.e., most significant.
+     * Returns true if it starts at '/'.
+     *
+     * Example: /foo/bar[10]/zod[3][4][5] would return:
+     * ret: {"foo", "bar", "zod" }
+     * index: { {}, {10}, {3,4,5} }
+     */
+    static bool chopPath( const string& path, vector< string >& ret,
+                          vector< unsigned int >& index );
+
+    // static void wildcard( const string& path, vector< Id >& list );
+
+    /**
+     * Cleans up all Elements except /root itself, /clock, /classes,
+     * and /Msgs.
+     * In due course will also do suitable reinitialization of
+     * tick and other values.
+     */
+    static void cleanSimulation();
+
+    /**
+     * set the gettingVector_ flag
+     */
+    void expectVector( bool flag );
+
+private:
+    Element* shelle_; // It is useful for the Shell to have this.
+
+    /**
+     * Buffer into which return values from the 'get' command are placed
+     * Only index 0 is used for any single-value 'get' call.
+     * If it was the 'getVec' command then the array is filled up
+     */
+    vector< double* > getBuf_;
+
+    /**
+     * Flag, used by the 'get' subsystem which maintains a buffer for
+     * returned value. True when the returned value is a vector.
+     */
+    bool gettingVector_;
+
+    /**
+     * Counter, used by the 'get' subsystem in order to keep track of
+     * number of returned values, especially for getVec.
+     */
+    unsigned int numGetVecReturns_;
+
+    /**
+     * Flag: True when the parser thread is blocked waiting for
+     * some system call to be handled by the threading and the
+     * MPI connected nodes.
+     */
+    static bool isBlockedOnParser_;
+
+    /**
+     * Flag: Tells the ProcessLoop to keep on going.
+     * Should only be altered during a barrier.
+     */
+    static bool keepLooping_;
+
+    /**
+     * Number of CPU cores in system.
+     */
+    static unsigned int numCores_;
+
+    /**
+     * Number of threads dedicated to the ProcessLoop.
+     * The parser thread is the master thread.
+     * Additional threads may be created for graphics, but not now.
+     */
+    static unsigned int numProcessThreads_;
+
+    /**
+     * Number of nodes in MPI-based system. Each node may have many
+     * threads.
+     */
+    static unsigned int numNodes_;
+
+    /**
+     * Identifier for current node
+     */
+    static unsigned int myNode_;
+
+    /**
+     * Shell owns its own ProcInfo, has global thread/node info.
+     * Used to talk to parser and for thread specification in
+     * setup operations.
+     */
+    static ProcInfo p_;
+
+    static vector< ProcInfo > threadProcs_;
+
+    /**
+     * Array of threads, initialized in launchThreads.
+     */
+
+    static unsigned int numAcks_;
+    static vector< unsigned int > acked_;
+
+
+    /**
+     * Flag to tell system to reinitialize. We use this to defer the
+     * actual operation to the 'process' call for a clean reinit.
+     */
+    static bool doReinit_;
+
+    /**
+     * Simulation run time
+     */
+    static double runtime_;
+
+    static bool isParserIdle_;
+
+    /// Current working Element
+    ObjId cwe_;
 };
 
 /*
diff --git a/shell/Wildcard.cpp b/shell/Wildcard.cpp
index 0607fcca273b7950f04b9d1cf77eded4f1a1fca7..17e69dc23e1ef1cf3c7019ea27b0879bfb739a55 100644
--- a/shell/Wildcard.cpp
+++ b/shell/Wildcard.cpp
@@ -14,14 +14,14 @@
 #include "Wildcard.h"
 // #define NOINDEX (UINT_MAX - 2)
 
-static int wildcardRelativeFind( ObjId start, const vector< string >& path, 
-		unsigned int depth, vector< ObjId >& ret );
+static int wildcardRelativeFind( ObjId start, const vector< string >& path,
+                                 unsigned int depth, vector< ObjId >& ret );
 
-static unsigned int findBraceContent( const string& path, 
-				string& beforeBrace, string& insideBrace );
+static unsigned int findBraceContent( const string& path,
+                                      string& beforeBrace, string& insideBrace );
 
 static bool matchName( ObjId id, unsigned int index,
-	const string& beforeBrace, const string& insideBrace ); 
+                       const string& beforeBrace, const string& insideBrace );
 
 // static bool matchBeforeBrace( ObjId id, const string& name );
 
@@ -34,53 +34,53 @@ static bool matchInsideBrace( ObjId id, const string& inside );
  */
 static bool wildcardFieldComparison( ObjId oid, const string& mid )
 {
-	// where = could be the usual comparison operators and val
-	// could be a number. No strings yet
-
-	string::size_type pos = mid.find(')');
-	if ( pos == string::npos )
-		return 0;
-	string fieldName = mid.substr( 0, pos );
-	string::size_type pos2 = mid.find_last_of( "=<>" );
-	if ( pos2 == string::npos )
-		return 0;
-	string op = mid.substr( pos + 1, pos2 - pos );
-
-	string testValue = mid.substr( pos2 + 1 );
-
-	if ( testValue.length() == 0 )
-		return 0;
-
-	/*
-	const Finfo* f = id()->findFinfo( fieldName );
-	if ( !f )
-		return 0;
-
-	string actualValue;
-	bool ret = f->strGet( id.eref(), actualValue );
-	*/
-	string actualValue;
-
-	bool ret = SetGet::strGet( oid, fieldName, actualValue );
-	if ( ret == 0 )
-		return 0;
-	if ( op == "==" || op == "=" )
-		return ( testValue == actualValue );
-	if ( op == "!=" )
-		return ( testValue != actualValue );
-	
-	double v1 = atof( actualValue.c_str() );
-	double v2 = atof( testValue.c_str() );
-	if ( op == ">" )
-		return ( v1 > v2 );
-	if ( op == ">=" )
-		return ( v1 >= v2 );
-	if ( op == "<" )
-		return ( v1 < v2 );
-	if ( op == "<=" )
-		return ( v1 <= v2 );
-
-	return 0;
+    // where = could be the usual comparison operators and val
+    // could be a number. No strings yet
+
+    string::size_type pos = mid.find(')');
+    if ( pos == string::npos )
+        return 0;
+    string fieldName = mid.substr( 0, pos );
+    string::size_type pos2 = mid.find_last_of( "=<>" );
+    if ( pos2 == string::npos )
+        return 0;
+    string op = mid.substr( pos + 1, pos2 - pos );
+
+    string testValue = mid.substr( pos2 + 1 );
+
+    if ( testValue.length() == 0 )
+        return 0;
+
+    /*
+    const Finfo* f = id()->findFinfo( fieldName );
+    if ( !f )
+    	return 0;
+
+    string actualValue;
+    bool ret = f->strGet( id.eref(), actualValue );
+    */
+    string actualValue;
+
+    bool ret = SetGet::strGet( oid, fieldName, actualValue );
+    if ( ret == 0 )
+        return 0;
+    if ( op == "==" || op == "=" )
+        return ( testValue == actualValue );
+    if ( op == "!=" )
+        return ( testValue != actualValue );
+
+    double v1 = atof( actualValue.c_str() );
+    double v2 = atof( testValue.c_str() );
+    if ( op == ">" )
+        return ( v1 > v2 );
+    if ( op == ">=" )
+        return ( v1 >= v2 );
+    if ( op == "<" )
+        return ( v1 < v2 );
+    if ( op == "<=" )
+        return ( v1 <= v2 );
+
+    return 0;
 }
 
 /**
@@ -88,36 +88,38 @@ static bool wildcardFieldComparison( ObjId oid, const string& mid )
  */
 static int innerFind( const string& path, vector< ObjId >& ret)
 {
-	if ( path == "/" || path == "/root") {
-		ret.push_back( Id() );
-		return 1;
-	}
-
-	vector< string > names;
-	vector< vector< unsigned int > > indices;
-	bool isAbsolute = Shell::chopString( path, names, '/' );
-	ObjId start; // set to root id.
-	if ( !isAbsolute ) {
-		Shell* s = reinterpret_cast< Shell* >( ObjId().data() );
-		start = s->getCwe();
-	}
-		
-		/*
-	if ( path[0] == '/' ) {
-		// separateString puts in a blank first entry if the first char
-		// is a separator.
-		separateString( path.substr( 1 ) , names, "/" );
-	} else {
-		Shell* s = reinterpret_cast< Shell* >( Id.eref().data() );
-		separateString( path, names, "/" );
-		start = s->getCwe();
-	}
-	*/
-	return wildcardRelativeFind( start, names, 0, ret );
+    if ( path == "/" || path == "/root")
+    {
+        ret.push_back( Id() );
+        return 1;
+    }
+
+    vector< string > names;
+    vector< vector< unsigned int > > indices;
+    bool isAbsolute = Shell::chopString( path, names, '/' );
+    ObjId start; // set to root id.
+    if ( !isAbsolute )
+    {
+        Shell* s = reinterpret_cast< Shell* >( ObjId().data() );
+        start = s->getCwe();
+    }
+
+    /*
+    if ( path[0] == '/' ) {
+    // separateString puts in a blank first entry if the first char
+    // is a separator.
+    separateString( path.substr( 1 ) , names, "/" );
+    } else {
+    Shell* s = reinterpret_cast< Shell* >( Id.eref().data() );
+    separateString( path, names, "/" );
+    start = s->getCwe();
+    }
+    */
+    return wildcardRelativeFind( start, names, 0, ret );
 }
 
 /*
-static int wildcardRelativeFind( Id start, const vector< string >& path, 
+static int wildcardRelativeFind( Id start, const vector< string >& path,
 		unsigned int depth, vector< Id >& ret )
 		*/
 
@@ -134,40 +136,42 @@ static int wildcardRelativeFind( Id start, const vector< string >& path,
  */
 int simpleWildcardFind( const string& path, vector< ObjId >& ret)
 {
-	if ( path.length() == 0 )
-		return 0;
-	unsigned int n = ret.size();
-	vector< string > wildcards;
-	Shell::chopString( path, wildcards, ',' );
-	// separateString( path, wildcards, "," );
-	vector< string >::iterator i;
-	for ( i = wildcards.begin(); i != wildcards.end(); ++i )
-		innerFind( *i, ret );
-
-	return ret.size() - n;
+    if ( path.length() == 0 )
+        return 0;
+    unsigned int n = ret.size();
+    vector< string > wildcards;
+    Shell::chopString( path, wildcards, ',' );
+    // separateString( path, wildcards, "," );
+    vector< string >::iterator i;
+    for ( i = wildcards.begin(); i != wildcards.end(); ++i )
+        innerFind( *i, ret );
+
+    return ret.size() - n;
 }
 
 static void myUnique(vector<ObjId>& ret)
 {
-	sort(ret.begin(), ret.end());
-	unsigned int i, j;
-	j = 0;
-	for (i = 1; i < ret.size(); i++) {
-		if (ret[j] != ret[i]) {
-			ret[++j] = ret[i];
-		}
-	}
-	j++;
-	if (j < ret.size())
-		ret.resize(j);
+    sort(ret.begin(), ret.end());
+    unsigned int i, j;
+    j = 0;
+    for (i = 1; i < ret.size(); i++)
+    {
+        if (ret[j] != ret[i])
+        {
+            ret[++j] = ret[i];
+        }
+    }
+    j++;
+    if (j < ret.size())
+        ret.resize(j);
 }
 
-int wildcardFind(const string& path, vector<ObjId>& ret) 
+int wildcardFind(const string& path, vector<ObjId>& ret)
 {
-	ret.resize( 0 );
-	simpleWildcardFind( path, ret );
-	myUnique( ret );
-	return ret.size();
+    ret.resize( 0 );
+    simpleWildcardFind( path, ret );
+    myUnique( ret );
+    return ret.size();
 }
 
 /**
@@ -178,91 +182,105 @@ int wildcardFind(const string& path, vector<ObjId>& ret)
  */
 int singleLevelWildcard( ObjId start, const string& path, vector< ObjId >& ret )
 {
-	if ( path.length() == 0 )
-		return 0;
-	unsigned int nret = ret.size();
-
-	string beforeBrace;
-	string insideBrace;
-	// This has to handle ghastly cases like foo[][FIELD(x)=12.3]
-	unsigned int index = findBraceContent( path, beforeBrace, insideBrace );
-	if ( beforeBrace == "##" )
-		// recursive.
-		return allChildren( start, index, insideBrace, ret ); 
-
-	vector< Id > kids;
-	Neutral::children( start.eref(), kids );
-	vector< Id >::iterator i;
-	for ( i = kids.begin(); i != kids.end(); i++ ) {
-		if ( matchName( ObjId( *i, ALLDATA ), 
-								index, beforeBrace, insideBrace ) ) {
-			if ( index == ALLDATA ) {
-				for ( unsigned int j = 0; j < i->element()->numData(); ++j )
-					ret.push_back( ObjId( *i, j ) );
-			} else if ( i->element()->hasFields() && index < i->element()->numField( start.dataIndex ) ) {
-				ret.push_back( ObjId( *i, start.dataIndex, index ) );
-			} else if ( !i->element()->hasFields() && index < i->element()->numData() ) {
-				ret.push_back( ObjId( *i, index ) );
-			}
-		}
-	}
-
-	return ret.size() - nret;
+    if ( path.length() == 0 )
+        return 0;
+    unsigned int nret = ret.size();
+
+    string beforeBrace;
+    string insideBrace;
+    // This has to handle ghastly cases like foo[][FIELD(x)=12.3]
+    unsigned int index = findBraceContent( path, beforeBrace, insideBrace );
+    if ( beforeBrace == "##" )
+        // recursive.
+        return allChildren( start, index, insideBrace, ret );
+
+    vector< Id > kids;
+    Neutral::children( start.eref(), kids );
+    vector< Id >::iterator i;
+    for ( i = kids.begin(); i != kids.end(); i++ )
+    {
+        if ( matchName( ObjId( *i, ALLDATA ),
+                        index, beforeBrace, insideBrace ) )
+        {
+            if ( index == ALLDATA )
+            {
+                for ( unsigned int j = 0; j < i->element()->numData(); ++j )
+                    ret.push_back( ObjId( *i, j ) );
+            }
+            else if ( i->element()->hasFields() && index < i->element()->numField( start.dataIndex ) )
+            {
+                ret.push_back( ObjId( *i, start.dataIndex, index ) );
+            }
+            else if ( !i->element()->hasFields() && index < i->element()->numData() )
+            {
+                ret.push_back( ObjId( *i, index ) );
+            }
+        }
+    }
+
+    return ret.size() - nret;
 }
 
 /**
- * Parses the name and separates out the stuff before the brace, 
- * the stuff inside it, and if present, the index which is also in a 
+ * Parses the name and separates out the stuff before the brace,
+ * the stuff inside it, and if present, the index which is also in a
  * brace. Returns the index, and if not found, zero.
- * Assume order is 
- * foo[index][insideBrace] 
+ * Assume order is
+ * foo[index][insideBrace]
  * or foo[index]
  * or foo[insideBrace]
  * or foo
  *
- * Note that for the index, an empty [] means ALLDATA, but the 
+ * Note that for the index, an empty [] means ALLDATA, but the
  * absence of the braces altogether means zero.
  *
  * Note also that if the name ends in the wildcard '#', then we assume
  * that all indices are OK, unless overridden by a subsequent specific
- * index via braces. 
+ * index via braces.
  * So foo# gives all indices
  * but foo#[3] only gives index == 3.
  */
-unsigned int findBraceContent( const string& path, string& beforeBrace, 
-	string& insideBrace )
+unsigned int findBraceContent( const string& path, string& beforeBrace,
+                               string& insideBrace )
 {
-	int index = 0;
-	beforeBrace = "";
-	insideBrace = "";
-
-	if ( path.length() == 0 )
-		return 0;
-	vector< string > names;
-	Shell::chopString( path, names, '[' );
-	if ( names.size() == 0 )
-		return 0;
-	if ( names.size() >= 1 )
-		beforeBrace = names[0];
-	unsigned int len = beforeBrace.length();
-	if ( len > 0 && beforeBrace[len -1] == '#' )
-		index = ALLDATA;
-	if ( names.size() >= 2 ) {
-		const string& n = names[1];
-		if ( n == "]" ) { // A [] construct means use all indices.
-			index = ALLDATA;
-		} else if ( isdigit( n[0] ) ) {
-			index = atoi( n.c_str() );
-		} else { // some complicated text construct for the brace
-			insideBrace = n.substr( 0, n.length() - 1 );
-			return index; 
-		}
-		if ( names.size() == 3 ) { // name[number][another_string]
-			string n1 = names[2].substr( 0, names[2].length() - 1 );
-			insideBrace = n1;
-		}
-	}
-	return index;
+    int index = 0;
+    beforeBrace = "";
+    insideBrace = "";
+
+    if ( path.length() == 0 )
+        return 0;
+    vector< string > names;
+    Shell::chopString( path, names, '[' );
+    if ( names.size() == 0 )
+        return 0;
+    if ( names.size() >= 1 )
+        beforeBrace = names[0];
+    unsigned int len = beforeBrace.length();
+    if ( len > 0 && beforeBrace[len -1] == '#' )
+        index = ALLDATA;
+    if ( names.size() >= 2 )
+    {
+        const string& n = names[1];
+        if ( n == "]" )   // A [] construct means use all indices.
+        {
+            index = ALLDATA;
+        }
+        else if ( isdigit( n[0] ) )
+        {
+            index = atoi( n.c_str() );
+        }
+        else     // some complicated text construct for the brace
+        {
+            insideBrace = n.substr( 0, n.length() - 1 );
+            return index;
+        }
+        if ( names.size() == 3 )   // name[number][another_string]
+        {
+            string n1 = names[2].substr( 0, names[2].length() - 1 );
+            insideBrace = n1;
+        }
+    }
+    return index;
 }
 
 /**
@@ -273,23 +291,28 @@ unsigned int findBraceContent( const string& path, string& beforeBrace,
  * - Simple elements with index as part of their names.
  */
 bool matchName( ObjId id, unsigned int index,
-	const string& beforeBrace, const string& insideBrace )
+                const string& beforeBrace, const string& insideBrace )
 {
-	string temp = id.element()->getName();
-	if ( temp.length() <= 0 ){
-	  return false;
-	}
-
-	// if ( index == ALLDATA || index == id.dataIndex ) {
-		if ( matchBeforeBrace( id, beforeBrace ) ) {
-			if ( insideBrace.length() == 0 ) {
-				return true;
-			} else {
-				return matchInsideBrace( id, insideBrace );
-			}
-		}
-	// }
-	return 0;
+    string temp = id.element()->getName();
+    if ( temp.length() <= 0 )
+    {
+        return false;
+    }
+
+    // if ( index == ALLDATA || index == id.dataIndex ) {
+    if ( matchBeforeBrace( id, beforeBrace ) )
+    {
+        if ( insideBrace.length() == 0 )
+        {
+            return true;
+        }
+        else
+        {
+            return matchInsideBrace( id, insideBrace );
+        }
+    }
+    // }
+    return 0;
 }
 
 /**
@@ -298,67 +321,76 @@ bool matchName( ObjId id, unsigned int index,
  */
 bool matchInsideBrace( ObjId id, const string& inside )
 {
-	/* Map from Genesis class names to Moose class names */
-	// const map< string, string >& classNameMap = sliClassNameConvert();
-	if ( inside == "" )
-		return true; // empty means that there is no condition to apply.
-	
-	if ( inside.substr(0, 4 ) == "TYPE" ||
-		inside.substr(0, 5 ) == "CLASS" ||
-		inside.substr(0, 3 ) == "ISA" )
-	{
-		string::size_type pos = inside.rfind( "=" );
-		if ( pos == string::npos ) 
-			return false;
-		bool isEquality = ( inside[ pos - 1 ] != '!' );
-		string typeName = inside.substr( pos + 1 );
-		if ( typeName == "membrane" )
-			typeName = "Compartment";
-		
-		if ( inside.substr( 0, 5 ) == "CLASS" && typeName == "channel" )
-			typeName = "HHChannel";
-		
-		bool isEqual;
-		if ( inside.substr( 0, 3 ) == "ISA" ) {
-			isEqual = id.element()->cinfo()->isA( typeName );
-		} else {
-			isEqual = ( typeName == id.element()->cinfo()->name() );
-		}
-		/*
-		map< string, string >::const_iterator iter = classNameMap.find( typeName );
-		if ( iter != classNameMap.end() )
-			isEqual = ( iter->second == id()->className() );
-		else
-			isEqual = ( typeName == id()->className() );
-			*/
-		
-		return ( isEqual == isEquality );
-	} else if ( inside.substr( 0, 6 ) == "FIELD(" ) {
-		if ( id.dataIndex == ALLDATA ) {
-			return wildcardFieldComparison( id.id, inside.substr( 6 ) );
-		} else {
-			return wildcardFieldComparison( id, inside.substr( 6 ) );
-		}
-	}
-
-	return false;
+    /* Map from Genesis class names to Moose class names */
+    // const map< string, string >& classNameMap = sliClassNameConvert();
+    if ( inside == "" )
+        return true; // empty means that there is no condition to apply.
+
+    if ( inside.substr(0, 4 ) == "TYPE" ||
+            inside.substr(0, 5 ) == "CLASS" ||
+            inside.substr(0, 3 ) == "ISA" )
+    {
+        string::size_type pos = inside.rfind( "=" );
+        if ( pos == string::npos )
+            return false;
+        bool isEquality = ( inside[ pos - 1 ] != '!' );
+        string typeName = inside.substr( pos + 1 );
+        if ( typeName == "membrane" )
+            typeName = "Compartment";
+
+        if ( inside.substr( 0, 5 ) == "CLASS" && typeName == "channel" )
+            typeName = "HHChannel";
+
+        bool isEqual;
+        if ( inside.substr( 0, 3 ) == "ISA" )
+        {
+            isEqual = id.element()->cinfo()->isA( typeName );
+        }
+        else
+        {
+            isEqual = ( typeName == id.element()->cinfo()->name() );
+        }
+        /*
+        map< string, string >::const_iterator iter = classNameMap.find( typeName );
+        if ( iter != classNameMap.end() )
+        	isEqual = ( iter->second == id()->className() );
+        else
+        	isEqual = ( typeName == id()->className() );
+        	*/
+
+        return ( isEqual == isEquality );
+    }
+    else if ( inside.substr( 0, 6 ) == "FIELD(" )
+    {
+        if ( id.dataIndex == ALLDATA )
+        {
+            return wildcardFieldComparison( id.id, inside.substr( 6 ) );
+        }
+        else
+        {
+            return wildcardFieldComparison( id, inside.substr( 6 ) );
+        }
+    }
+
+    return false;
 }
 
 /**
  * Returns true if the name matches the wildcard string. Doesn't care about
- * following characters in 'name'. Single character wildcards are 
+ * following characters in 'name'. Single character wildcards are
  * indicated with '?'
  */
 bool alignedSingleWildcardMatch( const string& name, const string& wild )
 {
-	unsigned int len = wild.length();
-	if ( name.length() < len )
-		return false;
-	for ( unsigned int i = 0; i < len; i++ ) {
-		if ( wild[i] != '?' && name[i] != wild[i] )
-			return false;
-	}
-	return true;
+    unsigned int len = wild.length();
+    if ( name.length() < len )
+        return false;
+    for ( unsigned int i = 0; i < len; i++ )
+    {
+        if ( wild[i] != '?' && name[i] != wild[i] )
+            return false;
+    }
+    return true;
 }
 
 /**
@@ -370,18 +402,19 @@ bool alignedSingleWildcardMatch( const string& name, const string& wild )
  * findWithSingleCharWildcard( "xyzabc", 1, "a?c" ): return 3;
  * findWithSingleCharWildcard( "xyzabb", 1, "a?c" ): return ~0U;
  */
-unsigned int findWithSingleCharWildcard( 
-				const string& name, unsigned int start, const string& wild )
+unsigned int findWithSingleCharWildcard(
+    const string& name, unsigned int start, const string& wild )
 {
-	unsigned int len = wild.length();
-	if ( len + start > name.length() )
-		return ~0;
-	unsigned int end = 1 + name.length() - len;
-	for ( unsigned int i = start; i < end; ++i ) {
-		if ( alignedSingleWildcardMatch( name.substr(i), wild ) )
-			return i;
-	}
-	return ~0;
+    unsigned int len = wild.length();
+    if ( len + start > name.length() )
+        return ~0;
+    unsigned int end = 1 + name.length() - len;
+    for ( unsigned int i = start; i < end; ++i )
+    {
+        if ( alignedSingleWildcardMatch( name.substr(i), wild ) )
+            return i;
+    }
+    return ~0;
 }
 
 /**
@@ -398,95 +431,104 @@ unsigned int findWithSingleCharWildcard(
  */
 bool matchBeforeBrace( ObjId id, const string& wild )
 {
-	if ( wild == "#" || wild == "##" )
-		return true;
-
-	string ename = id.element()->getName();
-	if ( wild == ename )
-		return true;
-
-	// Check if the wildcard string has any # or ? symbols.
-	if ( wild.find_first_of( "#?" ) == string::npos )
-		return false;
-
-	// Break the 'wild' into the sections that must match, at the #s.
-	// Then go through each of these sections doing a match to ename.
-	// If not found, then return false.
-	vector< string > chops;
-	Shell::chopString( wild, chops, '#' );
-	unsigned int prev = 0;
-	unsigned int start = 0;
-
-	for ( vector< string >::iterator 
-				i = chops.begin(); i != chops.end(); ++i ) {
-		start = findWithSingleCharWildcard( ename, prev, *i );
-		if ( start == ~0U )
-			return false;
-		if ( prev == 0 && start > 0 && wild[0] != '#' )
-			return false;
-		prev = start + i->length();
-	}
-	return true;
-
-	/*
-
-	string::size_type pre = name.find( "#" );
-	string::size_type post = name.rfind( "#" );
-
-	// # may only be used once in the wildcard, but substitutes for any
-	// number of characters.
-	if ( pre != string::npos && post == pre ) {
-		if ( ename.length() < ( name.length() - post - 1 ) )
-				return false;
-		unsigned int epos = ename.length() - ( name.length() - post - 1 );
-		return ( name.substr( 0, pre ) == ename.substr( 0, pre ) &&
-			name.substr( post + 1 ) == ename.substr( epos ) );
-	}
-
-	// ? may be used any number of times in the wildcard, and
-	// must substitute exactly for characters.
-	if ( name.length() != ename.length() )
-		return 0;
-	for ( unsigned int i = 0; i < name.length(); i++ )
-		if ( name[i] != '?' && name[i] != ename[i] )
-			return false;
-	return true;
-	*/
+    if ( wild == "#" || wild == "##" )
+        return true;
+
+    string ename = id.element()->getName();
+    if ( wild == ename )
+        return true;
+
+    // Check if the wildcard string has any # or ? symbols.
+    if ( wild.find_first_of( "#?" ) == string::npos )
+        return false;
+
+    // Break the 'wild' into the sections that must match, at the #s.
+    // Then go through each of these sections doing a match to ename.
+    // If not found, then return false.
+    vector< string > chops;
+    Shell::chopString( wild, chops, '#' );
+    unsigned int prev = 0;
+    unsigned int start = 0;
+
+    for ( vector< string >::iterator
+            i = chops.begin(); i != chops.end(); ++i )
+    {
+        start = findWithSingleCharWildcard( ename, prev, *i );
+        if ( start == ~0U )
+            return false;
+        if ( prev == 0 && start > 0 && wild[0] != '#' )
+            return false;
+        prev = start + i->length();
+    }
+    return true;
+
+    /*
+
+    string::size_type pre = name.find( "#" );
+    string::size_type post = name.rfind( "#" );
+
+    // # may only be used once in the wildcard, but substitutes for any
+    // number of characters.
+    if ( pre != string::npos && post == pre ) {
+    	if ( ename.length() < ( name.length() - post - 1 ) )
+    			return false;
+    	unsigned int epos = ename.length() - ( name.length() - post - 1 );
+    	return ( name.substr( 0, pre ) == ename.substr( 0, pre ) &&
+    		name.substr( post + 1 ) == ename.substr( epos ) );
+    }
+
+    // ? may be used any number of times in the wildcard, and
+    // must substitute exactly for characters.
+    if ( name.length() != ename.length() )
+    	return 0;
+    for ( unsigned int i = 0; i < name.length(); i++ )
+    	if ( name[i] != '?' && name[i] != ename[i] )
+    		return false;
+    return true;
+    */
 }
 
 /**
  * Recursive function to compare all descendants and cram matches into ret.
  * Returns number of matches.
  */
-int allChildren( ObjId start, 
-	unsigned int index, const string& insideBrace, vector< ObjId >& ret )
+int allChildren( ObjId start,
+                 unsigned int index, const string& insideBrace, vector< ObjId >& ret )
 {
-	unsigned int nret = ret.size();
-	vector< Id > kids;
-	Neutral::children( start.eref(), kids );
-	vector< Id >::iterator i;
-	for ( i = kids.begin(); i != kids.end(); i++ ) {
-		if ( i->element()->hasFields() ) {
-			if ( matchInsideBrace( *i, insideBrace ) ) {
-				if ( index == ALLDATA ) {
-					ObjId oid( *i, start.dataIndex );
-					ret.push_back( oid );
-				} else if (index < i->element()->numField( start.dataIndex ) ) {
-					ObjId oid( *i, start.dataIndex, index );
-					ret.push_back( oid );
-				}
-			}
-		} else {
-			for ( unsigned int j = 0; j < i->element()->numData(); ++j )
-		   	{
-				ObjId oid( *i, j );
-				allChildren( oid, index, insideBrace, ret );
-				if ( (index == ALLDATA || index == j) && matchInsideBrace( oid, insideBrace ) )
-					ret.push_back( oid );
-			}
-		}
-	}
-	return ret.size() - nret;
+    unsigned int nret = ret.size();
+    vector< Id > kids;
+    Neutral::children( start.eref(), kids );
+    vector< Id >::iterator i;
+    for ( i = kids.begin(); i != kids.end(); i++ )
+    {
+        if ( i->element()->hasFields() )
+        {
+            if ( matchInsideBrace( *i, insideBrace ) )
+            {
+                if ( index == ALLDATA )
+                {
+                    ObjId oid( *i, start.dataIndex );
+                    ret.push_back( oid );
+                }
+                else if (index < i->element()->numField( start.dataIndex ) )
+                {
+                    ObjId oid( *i, start.dataIndex, index );
+                    ret.push_back( oid );
+                }
+            }
+        }
+        else
+        {
+            for ( unsigned int j = 0; j < i->element()->numData(); ++j )
+            {
+                ObjId oid( *i, j );
+                allChildren( oid, index, insideBrace, ret );
+                if ( (index == ALLDATA || index == j) && matchInsideBrace( oid, insideBrace ) )
+                    ret.push_back( oid );
+            }
+        }
+    }
+    return ret.size() - nret;
 }
 
 /**
@@ -499,313 +541,332 @@ int allChildren( ObjId start,
  * refers to messaging and basic Element information that is present on
  * all nodes.
  */
-int wildcardRelativeFind( ObjId start, const vector< string >& path, 
-		unsigned int depth, vector< ObjId >& ret )
+int wildcardRelativeFind( ObjId start, const vector< string >& path,
+                          unsigned int depth, vector< ObjId >& ret )
 {
-	int nret = 0;
-	vector< ObjId > currentLevelIds;
-	if ( depth == path.size() ) {
-		if ( ret.size() == 0 || ret.back() != start ) {
-			ret.push_back( start );
-		}
-		return 1;
-	}
-
-	if ( singleLevelWildcard( start, path[depth], currentLevelIds ) > 0 ) {
-		vector< ObjId >::iterator i;
-		for ( i = currentLevelIds.begin(); i != currentLevelIds.end(); ++i )
-			nret += wildcardRelativeFind( *i, path, depth + 1, ret );
-	}
-	return nret;
+    int nret = 0;
+    vector< ObjId > currentLevelIds;
+    if ( depth == path.size() )
+    {
+        if ( ret.size() == 0 || ret.back() != start )
+        {
+            ret.push_back( start );
+        }
+        return 1;
+    }
+
+    if ( singleLevelWildcard( start, path[depth], currentLevelIds ) > 0 )
+    {
+        vector< ObjId >::iterator i;
+        for ( i = currentLevelIds.begin(); i != currentLevelIds.end(); ++i )
+            nret += wildcardRelativeFind( *i, path, depth + 1, ret );
+    }
+    return nret;
 }
 
 void wildcardTestFunc( ObjId* elist, unsigned int ne, const string& path )
 {
-	vector< ObjId > ret;
-	simpleWildcardFind( path, ret );
-	if ( ne != ret.size() ) {
-		cout << "!\nAssert	'" << path << "' : expected " <<
-			ne << ", found " << ret.size() << "\n";
-		assert( 0 );
-	}
-	sort( ret.begin(), ret.end() );
-	for ( unsigned int i = 0; i < ne ; i++ ) {
-		if ( elist[ i ] != ret[ i ] ) {
-			cout << "!\nAssert	" << path << ": item " << i << 
-				": " << elist[i].element()->getName() << " != " <<
-					ret[i].element()->getName() << "\n";
-			assert( 0 );
-		}
-	}
-	cout << ".";
+    vector< ObjId > ret;
+    simpleWildcardFind( path, ret );
+    if ( ne != ret.size() )
+    {
+        cout << "!\nAssert	'" << path << "' : expected " <<
+             ne << ", found " << ret.size() << "\n";
+        assert( 0 );
+    }
+    sort( ret.begin(), ret.end() );
+    for ( unsigned int i = 0; i < ne ; i++ )
+    {
+        if ( elist[ i ] != ret[ i ] )
+        {
+            cout << "!\nAssert	" << path << ": item " << i <<
+                 ": " << elist[i].element()->getName() << " != " <<
+                 ret[i].element()->getName() << "\n";
+            assert( 0 );
+        }
+    }
+    cout << ".";
 }
 
 void testWildcard()
 {
-	unsigned long i;
-	string bb;
-	string ib;
-	i = findBraceContent( "foo[23][TYPE=Compartment]", bb, ib );
-	assert( bb == "foo" );
-	assert( i == 23 );
-	assert( ib == "TYPE=Compartment" );
-	i = findBraceContent( "foo[][TYPE=Channel]", bb, ib );
-	assert( i == ALLDATA );
-	assert( bb == "foo" );
-	assert( ib == "TYPE=Channel" );
-	i = findBraceContent( "foo[TYPE=membrane]", bb, ib );
-	assert( i == 0 );
-	assert( bb == "foo" );
-	assert( ib == "TYPE=membrane" );
-	i = findBraceContent( "bar[]", bb, ib );
-	assert( i == ALLDATA );
-	assert( bb == "bar" );
-	assert( ib == "" );
-	i = findBraceContent( "zod[24]", bb, ib );
-	assert( i == 24 );
-	assert( bb == "zod" );
-	assert( ib == "" );
-
-	i = findBraceContent( "zod#", bb, ib );
-	assert( i == ALLDATA );
-	assert( bb == "zod#" );
-	assert( ib == "" );
-	i = findBraceContent( "zod#[]", bb, ib );
-	assert( i == ALLDATA );
-	assert( bb == "zod#" );
-	assert( ib == "" );
-	i = findBraceContent( "zod#[ISA=hippo]", bb, ib );
-	assert( i == ALLDATA );
-	assert( bb == "zod#" );
-	assert( ib == "ISA=hippo" );
-	i = findBraceContent( "zod#[3]", bb, ib );
-	assert( i == 3 );
-	assert( bb == "zod#" );
-	assert( ib == "" );
-	i = findBraceContent( "zod##", bb, ib );
-	assert( i == ALLDATA );
-	assert( bb == "zod##" );
-	assert( ib == "" );
-
-	bool ret = alignedSingleWildcardMatch( "a123456", "a123" );
-	assert( ret == true );
-	ret = alignedSingleWildcardMatch( "a123456", "1234" );
-	assert( ret == false );
-	ret = alignedSingleWildcardMatch( "a123456", "?1234" );
-	assert( ret == true );
-	ret = alignedSingleWildcardMatch( "a123456", "a????" );
-	assert( ret == true );
-	ret = alignedSingleWildcardMatch( "a123456", "??2??" );
-	assert( ret == true );
-	ret = alignedSingleWildcardMatch( "a123456", "??3??" );
-	assert( ret == false );
-	ret = alignedSingleWildcardMatch( "a1", "a?" );
-	assert( ret == true );
-
-	unsigned int j = findWithSingleCharWildcard( "a12345678", 0, "a123" );
-	assert( j == 0 );
-	j = findWithSingleCharWildcard( "a12345678", 0, "123" );
-	assert( j == 1 );
-	j = findWithSingleCharWildcard( "a12345678", 0, "?123" );
-	assert( j == 0 );
-	j = findWithSingleCharWildcard( "a12345678", 0, "?23456?" );
-	assert( j == 1 );
-	j = findWithSingleCharWildcard( "a12345678", 0, "??6?" );
-	assert( j == 4 );
-
-	Shell* shell = reinterpret_cast< Shell* >( Id().eref().data() );
-	Id a1 = shell->doCreate( "Neutral", Id(), "a1", 1 );
-	Id c1 = shell->doCreate( "Arith", a1, "c1", 1 );
-	Id c2 = shell->doCreate( "Arith", a1, "c2", 1 );
-	Id c3 = shell->doCreate( "Arith", a1, "c3", 1 );
-	Id cIndex = shell->doCreate( "Neutral", a1, "c4", 1 );
-	Id c5 = shell->doCreate( "Neutral", a1, "Seg5_apical_1234_spine_234",1);
-
-	ret = matchBeforeBrace( a1, "a1" );
-	assert( ret );
-	ret = matchBeforeBrace( a1, "a2" );
-	assert( ret == 0 );
-	ret = matchBeforeBrace( a1, "a?" );
-	assert( ret == 1 );
-	ret = matchBeforeBrace( a1, "?1" );
-	assert( ret == 1 );
-	ret = matchBeforeBrace( a1, "??" );
-	assert( ret == 1 );
-	ret = matchBeforeBrace( a1, "#" );
-	assert( ret == 1 );
-	ret = matchBeforeBrace( a1, "a#" );
-	assert( ret == 1 );
-	ret = matchBeforeBrace( a1, "#1" );
-	assert( ret == 1 );
-
-	ret = matchBeforeBrace( cIndex, "c4" );
-	assert( ret == 1 );
-	ret = matchBeforeBrace( cIndex, "##" );
-	assert( ret == 1 );
-	ret = matchBeforeBrace( cIndex, "#4" );
-	assert( ret == 1 );
-	ret = matchBeforeBrace( cIndex, "#" );
-	assert( ret == 1 );
-	ret = matchBeforeBrace( cIndex, "?4" );
-	assert( ret == 1 );
-	ret = matchBeforeBrace( cIndex, "c1" );
-	assert( ret == 0 );
-	ret = matchBeforeBrace( cIndex, "c?" );
-	assert( ret == 1 );
-	ret = matchBeforeBrace( cIndex, "??" );
-	assert( ret == 1 );
-
-	ret = matchBeforeBrace( c5, "Seg?_apical_#_spine_#" );
-	assert( ret == true );
-	ret = matchBeforeBrace( c5, "#Seg?_apical_#_spine_#" );
-	assert( ret == true );
-	ret = matchBeforeBrace( c5, "#?_apical_#_spine_#" );
-	assert( ret == true );
-	ret = matchBeforeBrace( c5, "#5_apical_#_spine_#" );
-	assert( ret == true );
-	ret = matchBeforeBrace( c5, "#e?5_apical_#_spine_#" );
-	assert( ret == true );
-	ret = matchBeforeBrace( c5, "#e5_apical_#_spine_#" );
-	assert( ret == false );
-	ret = matchBeforeBrace( c5, "#Seg5_apical_#_spine_#" );
-	assert( ret == true );
-	ret = matchBeforeBrace( c5, "#Seg#_apical_#_spine_#" );
-	assert( ret == true );
-	ret = matchBeforeBrace( c5, "Seg#_apical_#_spine_#" );
-	assert( ret == true );
-	ret = matchBeforeBrace( c5, "Seg#_a????l_#_spine_#" );
-	assert( ret == true );
-	ret = matchBeforeBrace( c5, "#?_a????l_#_spine_#" );
-	assert( ret == true );
-	ret = matchBeforeBrace( c5, "Seg?_a?????l_#_spine_#" );
-	assert( ret == false );
-	ret = matchBeforeBrace( c5, "Seg#_spine_#" );
-	assert( ret == true );
-
-
-	ret = matchInsideBrace( a1, "TYPE=Neutral" );
-	assert( ret );
-	ret = matchInsideBrace( a1, "TYPE==Neutral" );
-	assert( ret );
-	ret = matchInsideBrace( a1, "CLASS=Neutral" );
-	assert( ret );
-	ret = matchInsideBrace( a1, "ISA=Neutral" );
-	assert( ret );
-	ret = matchInsideBrace( a1, "CLASS=Neutral" );
-	assert( ret );
-	ret = matchInsideBrace( a1, "TYPE!=Channel" );
-	assert( ret );
-	ret = matchInsideBrace( a1, "CLASS!=Channel" );
-	assert( ret );
-	ret = matchInsideBrace( a1, "ISA!=Channel" );
-	assert( ret );
-	ret = matchInsideBrace( c3, "ISA==Neutral" ); // Everything is a Neutral
-	assert( ret );
-	ret = matchInsideBrace( c3, "ISA=Arith" );
-	assert( ret );
-	ret = matchInsideBrace( c3, "TYPE=membrane" );
-	assert( !ret );
-
-	Field<double>::set( ObjId( c3, 0 ), "outputValue", 123.5 );
-	ret = matchInsideBrace( c3, "FIELD(outputValue)=123.5" );
-	assert( ret );
-	ret = matchInsideBrace( c3, "FIELD(outputValue)==123.5" );
-	assert( ret );
-	ret = matchInsideBrace( c3, "FIELD(outputValue)!=123.4" );
-	assert( ret );
-	ret = matchInsideBrace( c3, "FIELD(outputValue)>123.4" );
-	assert( ret );
-	ret = matchInsideBrace( c3, "FIELD(outputValue)<123.6" );
-	assert( ret );
-	ret = matchInsideBrace( c3, "FIELD(outputValue)>=123.4" );
-	assert( ret );
-	ret = matchInsideBrace( c3, "FIELD(outputValue)<=123.6" );
-	assert( ret );
-	ret = matchInsideBrace( c3, "FIELD(outputValue)>=123.5" );
-	assert( ret );
-	ret = matchInsideBrace( c3, "FIELD(outputValue)<=123.5" );
-	assert( ret );
-	ret = matchInsideBrace( c3, "FIELD(outputValue)==123.4" );
-	assert( !ret );
-	ret = matchInsideBrace( c3, "FIELD(outputValue)<123.4" );
-	assert( !ret );
-
-
-	ObjId el1[] = { ObjId(), a1, c1 };
-	wildcardTestFunc( el1, 3, "/,/a1,/a1/c1" );
-	ObjId el3[] = { c1, c2, c3, cIndex };
-	wildcardTestFunc( el3, 4, "/a1/c#" );
-	wildcardTestFunc( el3, 3, "/a1/c#[TYPE=Arith]" );
-
-	ObjId el2[ 100 ];
-	for ( i = 0 ; i < 100; i++ ) {
-		char name[10];
-		sprintf( name, "ch%ld", i );
-		el2[i] = shell->doCreate( "Annotator", c1, name, 1 );
-		//el2[i] = Neutral::create( "HHChannel", name, c1->id(), Id::scratchId() );
-		Field< double >::set( ObjId( el2[i], 0 ), "z", i );
-	}
-
-	wildcardTestFunc( el2, 100, "/a1/c1/##" );
-	wildcardTestFunc( el2, 100, "/a1/c1/#" );
-
-	wildcardTestFunc( el2, 0, "/a1/##[TYPE=IntFire]" );
-	wildcardTestFunc( el2, 100, "/a1/##[TYPE=Annotator]" );
-	wildcardTestFunc( el2, 50, "/a1/c1/##[][FIELD(z)<50]" );
-
-	// Here we set up some thoroughly ugly nesting.
-	// Note the sequence: The wildcarding goes depth first,
-	// and then in order of creation.
-	ObjId el4[12];
-	i = 0;
-	el4[i] = shell->doCreate( "IntFire", el2[0], "g0", 1 ); ++i;
-	el4[i] = shell->doCreate( "IntFire", el2[1], "g1", 1 ); ++i;
-	el4[i] = shell->doCreate( "IntFire", el2[1], "g2", 1 ); ++i;
-	el4[i] = shell->doCreate( "IntFire", el2[2], "g3", 1 ); ++i;
-	el4[i] = shell->doCreate( "IntFire", el2[2], "g4", 1 ); ++i;
-	el4[i] = shell->doCreate( "IntFire", el2[4], "g5", 1 ); ++i;
-	el4[i] = shell->doCreate( "IntFire", el2[5], "g6", 1 ); ++i;
-	el4[i] = shell->doCreate( "IntFire", el2[6], "g7", 1 ); ++i;
-	el4[i] = shell->doCreate( "IntFire", el2[1], "g8", 1 ); ++i;
-	el4[i] = shell->doCreate( "IntFire", el2[1], "g9", 1 ); ++i;
-	el4[i] = shell->doCreate( "IntFire", c2, "g10", 1 ); ++i;
-	el4[i] = shell->doCreate( "IntFire", c3, "g11", 1 ); ++i;
-
-	wildcardTestFunc( el4, 12, "/a1/##[TYPE=IntFire]" );
-	wildcardTestFunc( el4, 12, "/##[TYPE=IntFire]" );
-
-	// Here I test wildcards with array Elements.
-	Id x = shell->doCreate( "Arith", a1, "x", 5 );
-	Id y = shell->doCreate( "Arith", ObjId( x, 2 ), "y", 5 );
-	Id z = shell->doCreate( "Arith", ObjId( y, 3 ), "z", 5 );
-	vector< ObjId > vec;
-	simpleWildcardFind( "/a1/x[]/##", vec );
-	assert( vec.size() == 10 );
-	vec.clear();
-	simpleWildcardFind( "/a1/x[]/##,/a1/x[]", vec );
-	assert( vec.size() == 15 );
-	vec.clear();
-	simpleWildcardFind( "/a1/x[2]/y[]", vec );
-	assert( vec.size() == 5 );
-
-	// Here I test exclusive wildcards, should NOT get additional terms.
-	Id xyzzy = shell->doCreate( "Arith", a1, "xyzzy", 5 );
-	Id xdotp = shell->doCreate( "Arith", a1, "x.P", 5 );
-	vec.clear();
-	simpleWildcardFind( "/a1/x", vec );
-	assert( vec.size() == 1 );
-	vec.clear();
-	simpleWildcardFind( "/a1/x[0]", vec );
-	assert( vec.size() == 1 );
-	vec.clear();
-	simpleWildcardFind( "/a1/x[2]", vec );
-	assert( vec.size() == 1 );
-	vec.clear();
-	simpleWildcardFind( "/a1/x[]", vec );
-	assert( vec.size() == 5 );
-
-	//a1.destroy();
-	shell->doDelete( a1 );
-	cout << "." << flush;
+    unsigned long i;
+    string bb;
+    string ib;
+    i = findBraceContent( "foo[23][TYPE=Compartment]", bb, ib );
+    assert( bb == "foo" );
+    assert( i == 23 );
+    assert( ib == "TYPE=Compartment" );
+    i = findBraceContent( "foo[][TYPE=Channel]", bb, ib );
+    assert( i == ALLDATA );
+    assert( bb == "foo" );
+    assert( ib == "TYPE=Channel" );
+    i = findBraceContent( "foo[TYPE=membrane]", bb, ib );
+    assert( i == 0 );
+    assert( bb == "foo" );
+    assert( ib == "TYPE=membrane" );
+    i = findBraceContent( "bar[]", bb, ib );
+    assert( i == ALLDATA );
+    assert( bb == "bar" );
+    assert( ib == "" );
+    i = findBraceContent( "zod[24]", bb, ib );
+    assert( i == 24 );
+    assert( bb == "zod" );
+    assert( ib == "" );
+
+    i = findBraceContent( "zod#", bb, ib );
+    assert( i == ALLDATA );
+    assert( bb == "zod#" );
+    assert( ib == "" );
+    i = findBraceContent( "zod#[]", bb, ib );
+    assert( i == ALLDATA );
+    assert( bb == "zod#" );
+    assert( ib == "" );
+    i = findBraceContent( "zod#[ISA=hippo]", bb, ib );
+    assert( i == ALLDATA );
+    assert( bb == "zod#" );
+    assert( ib == "ISA=hippo" );
+    i = findBraceContent( "zod#[3]", bb, ib );
+    assert( i == 3 );
+    assert( bb == "zod#" );
+    assert( ib == "" );
+    i = findBraceContent( "zod##", bb, ib );
+    assert( i == ALLDATA );
+    assert( bb == "zod##" );
+    assert( ib == "" );
+
+    bool ret = alignedSingleWildcardMatch( "a123456", "a123" );
+    assert( ret == true );
+    ret = alignedSingleWildcardMatch( "a123456", "1234" );
+    assert( ret == false );
+    ret = alignedSingleWildcardMatch( "a123456", "?1234" );
+    assert( ret == true );
+    ret = alignedSingleWildcardMatch( "a123456", "a????" );
+    assert( ret == true );
+    ret = alignedSingleWildcardMatch( "a123456", "??2??" );
+    assert( ret == true );
+    ret = alignedSingleWildcardMatch( "a123456", "??3??" );
+    assert( ret == false );
+    ret = alignedSingleWildcardMatch( "a1", "a?" );
+    assert( ret == true );
+
+    unsigned int j = findWithSingleCharWildcard( "a12345678", 0, "a123" );
+    assert( j == 0 );
+    j = findWithSingleCharWildcard( "a12345678", 0, "123" );
+    assert( j == 1 );
+    j = findWithSingleCharWildcard( "a12345678", 0, "?123" );
+    assert( j == 0 );
+    j = findWithSingleCharWildcard( "a12345678", 0, "?23456?" );
+    assert( j == 1 );
+    j = findWithSingleCharWildcard( "a12345678", 0, "??6?" );
+    assert( j == 4 );
+
+    Shell* shell = reinterpret_cast< Shell* >( Id().eref().data() );
+    Id a1 = shell->doCreate( "Neutral", Id(), "a1", 1 );
+    Id c1 = shell->doCreate( "Arith", a1, "c1", 1 );
+    Id c2 = shell->doCreate( "Arith", a1, "c2", 1 );
+    Id c3 = shell->doCreate( "Arith", a1, "c3", 1 );
+    Id cIndex = shell->doCreate( "Neutral", a1, "c4", 1 );
+    Id c5 = shell->doCreate( "Neutral", a1, "Seg5_apical_1234_spine_234",1);
+
+    ret = matchBeforeBrace( a1, "a1" );
+    assert( ret );
+    ret = matchBeforeBrace( a1, "a2" );
+    assert( ret == 0 );
+    ret = matchBeforeBrace( a1, "a?" );
+    assert( ret == 1 );
+    ret = matchBeforeBrace( a1, "?1" );
+    assert( ret == 1 );
+    ret = matchBeforeBrace( a1, "??" );
+    assert( ret == 1 );
+    ret = matchBeforeBrace( a1, "#" );
+    assert( ret == 1 );
+    ret = matchBeforeBrace( a1, "a#" );
+    assert( ret == 1 );
+    ret = matchBeforeBrace( a1, "#1" );
+    assert( ret == 1 );
+
+    ret = matchBeforeBrace( cIndex, "c4" );
+    assert( ret == 1 );
+    ret = matchBeforeBrace( cIndex, "##" );
+    assert( ret == 1 );
+    ret = matchBeforeBrace( cIndex, "#4" );
+    assert( ret == 1 );
+    ret = matchBeforeBrace( cIndex, "#" );
+    assert( ret == 1 );
+    ret = matchBeforeBrace( cIndex, "?4" );
+    assert( ret == 1 );
+    ret = matchBeforeBrace( cIndex, "c1" );
+    assert( ret == 0 );
+    ret = matchBeforeBrace( cIndex, "c?" );
+    assert( ret == 1 );
+    ret = matchBeforeBrace( cIndex, "??" );
+    assert( ret == 1 );
+
+    ret = matchBeforeBrace( c5, "Seg?_apical_#_spine_#" );
+    assert( ret == true );
+    ret = matchBeforeBrace( c5, "#Seg?_apical_#_spine_#" );
+    assert( ret == true );
+    ret = matchBeforeBrace( c5, "#?_apical_#_spine_#" );
+    assert( ret == true );
+    ret = matchBeforeBrace( c5, "#5_apical_#_spine_#" );
+    assert( ret == true );
+    ret = matchBeforeBrace( c5, "#e?5_apical_#_spine_#" );
+    assert( ret == true );
+    ret = matchBeforeBrace( c5, "#e5_apical_#_spine_#" );
+    assert( ret == false );
+    ret = matchBeforeBrace( c5, "#Seg5_apical_#_spine_#" );
+    assert( ret == true );
+    ret = matchBeforeBrace( c5, "#Seg#_apical_#_spine_#" );
+    assert( ret == true );
+    ret = matchBeforeBrace( c5, "Seg#_apical_#_spine_#" );
+    assert( ret == true );
+    ret = matchBeforeBrace( c5, "Seg#_a????l_#_spine_#" );
+    assert( ret == true );
+    ret = matchBeforeBrace( c5, "#?_a????l_#_spine_#" );
+    assert( ret == true );
+    ret = matchBeforeBrace( c5, "Seg?_a?????l_#_spine_#" );
+    assert( ret == false );
+    ret = matchBeforeBrace( c5, "Seg#_spine_#" );
+    assert( ret == true );
+
+
+    ret = matchInsideBrace( a1, "TYPE=Neutral" );
+    assert( ret );
+    ret = matchInsideBrace( a1, "TYPE==Neutral" );
+    assert( ret );
+    ret = matchInsideBrace( a1, "CLASS=Neutral" );
+    assert( ret );
+    ret = matchInsideBrace( a1, "ISA=Neutral" );
+    assert( ret );
+    ret = matchInsideBrace( a1, "CLASS=Neutral" );
+    assert( ret );
+    ret = matchInsideBrace( a1, "TYPE!=Channel" );
+    assert( ret );
+    ret = matchInsideBrace( a1, "CLASS!=Channel" );
+    assert( ret );
+    ret = matchInsideBrace( a1, "ISA!=Channel" );
+    assert( ret );
+    ret = matchInsideBrace( c3, "ISA==Neutral" ); // Everything is a Neutral
+    assert( ret );
+    ret = matchInsideBrace( c3, "ISA=Arith" );
+    assert( ret );
+    ret = matchInsideBrace( c3, "TYPE=membrane" );
+    assert( !ret );
+
+    Field<double>::set( ObjId( c3, 0 ), "outputValue", 123.5 );
+    ret = matchInsideBrace( c3, "FIELD(outputValue)=123.5" );
+    assert( ret );
+    ret = matchInsideBrace( c3, "FIELD(outputValue)==123.5" );
+    assert( ret );
+    ret = matchInsideBrace( c3, "FIELD(outputValue)!=123.4" );
+    assert( ret );
+    ret = matchInsideBrace( c3, "FIELD(outputValue)>123.4" );
+    assert( ret );
+    ret = matchInsideBrace( c3, "FIELD(outputValue)<123.6" );
+    assert( ret );
+    ret = matchInsideBrace( c3, "FIELD(outputValue)>=123.4" );
+    assert( ret );
+    ret = matchInsideBrace( c3, "FIELD(outputValue)<=123.6" );
+    assert( ret );
+    ret = matchInsideBrace( c3, "FIELD(outputValue)>=123.5" );
+    assert( ret );
+    ret = matchInsideBrace( c3, "FIELD(outputValue)<=123.5" );
+    assert( ret );
+    ret = matchInsideBrace( c3, "FIELD(outputValue)==123.4" );
+    assert( !ret );
+    ret = matchInsideBrace( c3, "FIELD(outputValue)<123.4" );
+    assert( !ret );
+
+
+    ObjId el1[] = { ObjId(), a1, c1 };
+    wildcardTestFunc( el1, 3, "/,/a1,/a1/c1" );
+    ObjId el3[] = { c1, c2, c3, cIndex };
+    wildcardTestFunc( el3, 4, "/a1/c#" );
+    wildcardTestFunc( el3, 3, "/a1/c#[TYPE=Arith]" );
+
+    ObjId el2[ 100 ];
+    for ( i = 0 ; i < 100; i++ )
+    {
+        char name[10];
+        sprintf( name, "ch%ld", i );
+        el2[i] = shell->doCreate( "Annotator", c1, name, 1 );
+        //el2[i] = Neutral::create( "HHChannel", name, c1->id(), Id::scratchId() );
+        Field< double >::set( ObjId( el2[i], 0 ), "z", i );
+    }
+
+    wildcardTestFunc( el2, 100, "/a1/c1/##" );
+    wildcardTestFunc( el2, 100, "/a1/c1/#" );
+
+    wildcardTestFunc( el2, 0, "/a1/##[TYPE=IntFire]" );
+    wildcardTestFunc( el2, 100, "/a1/##[TYPE=Annotator]" );
+    wildcardTestFunc( el2, 50, "/a1/c1/##[][FIELD(z)<50]" );
+
+    // Here we set up some thoroughly ugly nesting.
+    // Note the sequence: The wildcarding goes depth first,
+    // and then in order of creation.
+    ObjId el4[12];
+    i = 0;
+    el4[i] = shell->doCreate( "IntFire", el2[0], "g0", 1 );
+    ++i;
+    el4[i] = shell->doCreate( "IntFire", el2[1], "g1", 1 );
+    ++i;
+    el4[i] = shell->doCreate( "IntFire", el2[1], "g2", 1 );
+    ++i;
+    el4[i] = shell->doCreate( "IntFire", el2[2], "g3", 1 );
+    ++i;
+    el4[i] = shell->doCreate( "IntFire", el2[2], "g4", 1 );
+    ++i;
+    el4[i] = shell->doCreate( "IntFire", el2[4], "g5", 1 );
+    ++i;
+    el4[i] = shell->doCreate( "IntFire", el2[5], "g6", 1 );
+    ++i;
+    el4[i] = shell->doCreate( "IntFire", el2[6], "g7", 1 );
+    ++i;
+    el4[i] = shell->doCreate( "IntFire", el2[1], "g8", 1 );
+    ++i;
+    el4[i] = shell->doCreate( "IntFire", el2[1], "g9", 1 );
+    ++i;
+    el4[i] = shell->doCreate( "IntFire", c2, "g10", 1 );
+    ++i;
+    el4[i] = shell->doCreate( "IntFire", c3, "g11", 1 );
+    ++i;
+
+    wildcardTestFunc( el4, 12, "/a1/##[TYPE=IntFire]" );
+    wildcardTestFunc( el4, 12, "/##[TYPE=IntFire]" );
+
+    // Here I test wildcards with array Elements.
+    Id x = shell->doCreate( "Arith", a1, "x", 5 );
+    Id y = shell->doCreate( "Arith", ObjId( x, 2 ), "y", 5 );
+    Id z = shell->doCreate( "Arith", ObjId( y, 3 ), "z", 5 );
+    vector< ObjId > vec;
+    simpleWildcardFind( "/a1/x[]/##", vec );
+    assert( vec.size() == 10 );
+    vec.clear();
+    simpleWildcardFind( "/a1/x[]/##,/a1/x[]", vec );
+    assert( vec.size() == 15 );
+    vec.clear();
+    simpleWildcardFind( "/a1/x[2]/y[]", vec );
+    assert( vec.size() == 5 );
+
+    // Here I test exclusive wildcards, should NOT get additional terms.
+    Id xyzzy = shell->doCreate( "Arith", a1, "xyzzy", 5 );
+    Id xdotp = shell->doCreate( "Arith", a1, "x.P", 5 );
+    vec.clear();
+    simpleWildcardFind( "/a1/x", vec );
+    assert( vec.size() == 1 );
+    vec.clear();
+    simpleWildcardFind( "/a1/x[0]", vec );
+    assert( vec.size() == 1 );
+    vec.clear();
+    simpleWildcardFind( "/a1/x[2]", vec );
+    assert( vec.size() == 1 );
+    vec.clear();
+    simpleWildcardFind( "/a1/x[]", vec );
+    assert( vec.size() == 5 );
+
+    //a1.destroy();
+    shell->doDelete( a1 );
+    cout << "." << flush;
 }
 
diff --git a/synapse/CMakeLists.txt b/synapse/CMakeLists.txt
index 0a91167008b7b27e5510c27d6f6cf6c00b7807d4..bb47b9779b8f3d9c7393cd01f44c27f803ee4248 100644
--- a/synapse/CMakeLists.txt
+++ b/synapse/CMakeLists.txt
@@ -1,14 +1,5 @@
-cmake_minimum_required(VERSION 2.6)
-include_directories(../basecode ../utility ../kinetics)
+cmake_minimum_required(VERSION 2.8)
+include_directories( ../basecode ../utility ../kinetics)
 include_directories( ../external/muparser/include/ )
-add_library(synapse
-    SynHandlerBase.cpp
-    SimpleSynHandler.cpp
-    STDPSynHandler.cpp
-    GraupnerBrunel2012CaPlasticitySynHandler.cpp
-    Synapse.cpp
-    STDPSynapse.cpp
-    RollingMatrix.cpp 
-    SeqSynHandler.cpp
-    testSynapse.cpp
-    )
+file(GLOB SYNAPSE_SRCS *.cpp)
+add_library(synapse ${SYNAPSE_SRCS} )
diff --git a/tests/python/Rallpacks/moose_vs_neuron/rallpack3/moose_sim.py b/tests/python/Rallpacks/moose_vs_neuron/rallpack3/moose_sim.py
index 807ec30a1fd8e802ba82560b3a484faf9f2998b1..98f927efe7d2c134a791a169c2be26f5aaf52953 100644
--- a/tests/python/Rallpacks/moose_vs_neuron/rallpack3/moose_sim.py
+++ b/tests/python/Rallpacks/moose_vs_neuron/rallpack3/moose_sim.py
@@ -21,6 +21,7 @@ import numpy as np
 
 import moose
 from moose import utils
+import time
 
 EREST_ACT = -65e-3
 per_ms = 1e3
@@ -256,18 +257,16 @@ def simulate( runTime, dt):
     moose.useClock(1, '/##', 'process')
     moose.reinit()
     setupSolver( hsolveDt = dt )
-    utils.verify()
+    t = time.time( )
     moose.start( runTime )
+    print( 'Time taken to simulate %f = %f' % (  runTime, time.time() - t ) )
 
 def main(args):
     global cable
     dt = args['dt']
     makeCable(args)
     setupDUT( dt )
-    table0 = utils.recordAt( '/table0', cable[0], 'vm')
-    table1 = utils.recordAt( '/table1', cable[-1], 'vm')
     simulate( args['run_time'], dt )
-    utils.saveTables( [ table0, table1 ], file = args['output'], xscale = dt )
 
 if __name__ == '__main__':
     import argparse
diff --git a/tests/python/Rallpacks/rallpacks_cable_hhchannel.py b/tests/python/Rallpacks/rallpacks_cable_hhchannel.py
index 941c669eb4961a2d3538189579173fac3ae27a9d..d970434753334df4e407d422cdf00ca078d594f2 100644
--- a/tests/python/Rallpacks/rallpacks_cable_hhchannel.py
+++ b/tests/python/Rallpacks/rallpacks_cable_hhchannel.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-
 """rallpacks_cable_hhchannel.py: 
 
     A cable with 1000 compartments with HH-type channels in it.
@@ -20,6 +18,7 @@ __status__           = "Development"
 import moose
 from moose import utils
 
+import time
 import os
 import numpy as np
 import matplotlib.pyplot as plt
@@ -192,12 +191,8 @@ def setupSolver( hsolveDt ):
 
 def simulate( runTime, dt):
     """ Simulate the cable """
-    moose.useClock(0, '/cable/##', 'process')
-    moose.useClock(0, '/cable/##', 'init')
-    moose.useClock(1, '/##', 'process')
     moose.reinit()
     setupSolver( hsolveDt = dt )
-    utils.verify()
     moose.start( runTime )
 
 def main(args):
@@ -205,10 +200,9 @@ def main(args):
     dt = args['dt']
     makeCable(args)
     setupDUT( dt )
-    table0 = utils.recordAt( '/table0', cable[0], 'vm')
-    table1 = utils.recordAt( '/table1', cable[-1], 'vm')
+    t = time.time() 
     simulate( args['run_time'], dt )
-    utils.plotTables( [ table0, table1 ], file = args['output'], xscale = dt )
+    print( 'Time to run %f seconds ' % ( time.time() - t ) )
 
 if __name__ == '__main__':
     import argparse
diff --git a/tests/python/genesis/kkit_objects_example.g b/tests/python/genesis/kkit_objects_example.g
new file mode 100644
index 0000000000000000000000000000000000000000..de66fc94e6ca12c24f0732f67d9fed0a08a4a558
--- /dev/null
+++ b/tests/python/genesis/kkit_objects_example.g
@@ -0,0 +1,195 @@
+//genesis
+// kkit Version 11 flat dumpfile
+ 
+// Saved on Wed Mar 19 11:08:42 2014
+ 
+include kkit {argv 1}
+ 
+FASTDT = 0.0001
+SIMDT = 0.01
+CONTROLDT = 5
+PLOTDT = 0.1
+MAXTIME = 20
+TRANSIENT_TIME = 2
+VARIABLE_DT_FLAG = 0
+DEFAULT_VOL = 1.6667e-21
+VERSION = 11.0
+setfield /file/modpath value /home2/bhalla/scripts/modules
+kparms
+ 
+//genesis
+
+initdump -version 3 -ignoreorphans 1
+simobjdump doqcsinfo filename accessname accesstype transcriber developer \
+  citation species tissue cellcompartment methodology sources \
+  model_implementation model_validation x y z
+simobjdump table input output alloced step_mode stepsize x y z
+simobjdump xtree path script namemode sizescale
+simobjdump xcoredraw xmin xmax ymin ymax
+simobjdump xtext editable
+simobjdump xgraph xmin xmax ymin ymax overlay
+simobjdump xplot pixflags script fg ysquish do_slope wy
+simobjdump group xtree_fg_req xtree_textfg_req plotfield expanded movealone \
+  link savename file version md5sum mod_save_flag x y z
+simobjdump geometry size dim shape outside xtree_fg_req xtree_textfg_req x y \
+  z
+simobjdump kpool DiffConst CoInit Co n nInit mwt nMin vol slave_enable \
+  geomname xtree_fg_req xtree_textfg_req x y z
+simobjdump kreac kf kb notes xtree_fg_req xtree_textfg_req x y z
+simobjdump kenz CoComplexInit CoComplex nComplexInit nComplex vol k1 k2 k3 \
+  keepconc usecomplex notes xtree_fg_req xtree_textfg_req link x y z
+simobjdump stim level1 width1 delay1 level2 width2 delay2 baselevel trig_time \
+  trig_mode notes xtree_fg_req xtree_textfg_req is_running x y z
+simobjdump xtab input output alloced step_mode stepsize notes editfunc \
+  xtree_fg_req xtree_textfg_req baselevel last_x last_y is_running x y z
+simobjdump kchan perm gmax Vm is_active use_nernst notes xtree_fg_req \
+  xtree_textfg_req x y z
+simobjdump transport input output alloced step_mode stepsize dt delay clock \
+  kf xtree_fg_req xtree_textfg_req x y z
+simobjdump proto x y z
+simobjdump text str
+simundump geometry /kinetics/geometry 0 1.6667e-21 3 sphere "" white black 3 \
+  -7 0
+simundump text /kinetics/notes 0 ""
+call /kinetics/notes LOAD \
+""
+simundump text /kinetics/geometry/notes 0 ""
+call /kinetics/geometry/notes LOAD \
+""
+simundump kpool /kinetics/B 0 0 0 0 0 0 0 0 1 0 /kinetics/geometry 62 black 1 \
+  1 0
+simundump text /kinetics/B/notes 0 ""
+call /kinetics/B/notes LOAD \
+""
+simundump kpool /kinetics/A 0 0 2 2 2 2 0 0 1 0 /kinetics/geometry blue black \
+  -3 1 0
+simundump text /kinetics/A/notes 0 ""
+call /kinetics/A/notes LOAD \
+""
+simundump kpool /kinetics/tot1 0 0 0 2 2 0 0 0 1 0 /kinetics/geometry 47 \
+  black -1 -2 0
+simundump text /kinetics/tot1/notes 0 ""
+call /kinetics/tot1/notes LOAD \
+""
+simundump kpool /kinetics/C 0 0 0 0 0 0 0 0 1 0 /kinetics/geometry 56 black 5 \
+  1 0
+simundump text /kinetics/C/notes 0 ""
+call /kinetics/C/notes LOAD \
+""
+simundump xtab /kinetics/xtab 0 0 0 1 1 0 "" edit_xtab "" red 0 0 0 1 -1 7 0
+loadtab /kinetics/xtab table 1 100 0 10 \
+ 1 1.0628 1.1253 1.1874 1.2487 1.309 1.3681 1.4258 1.4817 1.5358 1.5878 \
+ 1.6374 1.6845 1.729 1.7705 1.809 1.8443 1.8763 1.9048 1.9298 1.951 1.9686 \
+ 1.9823 1.9921 1.998 2 1.998 1.9921 1.9823 1.9686 1.951 1.9298 1.9048 1.8763 \
+ 1.8443 1.809 1.7705 1.729 1.6846 1.6375 1.5878 1.5358 1.4818 1.4258 1.3681 \
+ 1.309 1.2487 1.1874 1.1254 1.0628 0.99999 0.93723 0.87462 0.81261 0.75133 \
+ 0.69103 0.63186 0.57423 0.51829 0.46416 0.41222 0.36261 0.31543 0.27104 \
+ 0.22951 0.19097 0.15567 0.12371 0.095158 0.070223 0.048953 0.031407 0.017712 \
+ 0.0078885 0.0019706 0 0.001972 0.0078787 0.017716 0.031413 0.048929 0.070231 \
+ 0.095168 0.12367 0.15569 0.19098 0.22946 0.27105 0.31545 0.36255 0.41224 \
+ 0.46417 0.51822 0.57425 0.63188 0.69096 0.75135 0.81263 0.87465 0.93716 1
+simundump text /kinetics/xtab/notes 0 ""
+call /kinetics/xtab/notes LOAD \
+""
+simundump kpool /kinetics/D 0 0 0 0 0 0 0 0 1 2 /kinetics/geometry 25 black \
+  -3 5 0
+simundump text /kinetics/D/notes 0 ""
+call /kinetics/D/notes LOAD \
+""
+simundump kreac /kinetics/Reac1 0 0.2 0.1 "" white black -1 3 0
+simundump text /kinetics/Reac1/notes 0 ""
+call /kinetics/Reac1/notes LOAD \
+""
+simundump kreac /kinetics/Reac2 0 0.1 0 "" white black 3 3 0
+simundump text /kinetics/Reac2/notes 0 ""
+call /kinetics/Reac2/notes LOAD \
+""
+simundump kpool /kinetics/E 0 0 0 0 0 0 0 0 1 0 /kinetics/geometry 1 black 9 \
+  1 0
+simundump text /kinetics/E/notes 0 ""
+call /kinetics/E/notes LOAD \
+""
+simundump kpool /kinetics/MassActionEnz 0 0 1 1 1 1 0 0 1 0 \
+  /kinetics/geometry 28 black 7 5 0
+simundump text /kinetics/MassActionEnz/notes 0 ""
+call /kinetics/MassActionEnz/notes LOAD \
+""
+simundump kenz /kinetics/MassActionEnz/e1 0 0 0 0 0 1 1 4 1 0 0 "" red 28 "" \
+  7 3 0
+simundump text /kinetics/MassActionEnz/e1/notes 0 ""
+call /kinetics/MassActionEnz/e1/notes LOAD \
+""
+simundump kpool /kinetics/MM_Enz 0 0 1 1 1 1 0 0 1 0 /kinetics/geometry 22 \
+  black 6 -1 0
+simundump text /kinetics/MM_Enz/notes 0 ""
+call /kinetics/MM_Enz/notes LOAD \
+""
+simundump kenz /kinetics/MM_Enz/e2 0 0 0 0 0 1 1 4 1 0 1 "" red 22 "" 7 -1 0
+simundump text /kinetics/MM_Enz/e2/notes 0 ""
+call /kinetics/MM_Enz/e2/notes LOAD \
+""
+simundump kpool /kinetics/F 0 0 0 0 0 0 0 0 1 0 /kinetics/geometry blue black \
+  9 -3 0
+simundump text /kinetics/F/notes 0 ""
+call /kinetics/F/notes LOAD \
+""
+simundump xgraph /graphs/conc1 0 0 20 0 2 0
+simundump xgraph /graphs/conc2 0 0 20 0 2 0
+simundump xplot /graphs/conc1/A.Co 3 524288 \
+  "delete_plot.w <s> <d>; edit_plot.D <w>" blue 0 0 1
+simundump xplot /graphs/conc1/B.Co 3 524288 \
+  "delete_plot.w <s> <d>; edit_plot.D <w>" 62 0 0 1
+simundump xplot /graphs/conc2/tot1.Co 3 524288 \
+  "delete_plot.w <s> <d>; edit_plot.D <w>" 47 0 0 1
+simundump xplot /graphs/conc2/C.Co 3 524288 \
+  "delete_plot.w <s> <d>; edit_plot.D <w>" 56 0 0 1
+simundump xplot /graphs/conc2/D.Co 3 524288 \
+  "delete_plot.w <s> <d>; edit_plot.D <w>" 25 0 0 1
+simundump xplot /graphs/conc2/E.Co 3 524288 \
+  "delete_plot.w <s> <d>; edit_plot.D <w>" 1 0 0 1
+simundump xplot /graphs/conc2/F.Co 3 524288 \
+  "delete_plot.w <s> <d>; edit_plot.D <w>" blue 0 0 1
+simundump xgraph /moregraphs/conc3 0 0 20 0 1.2 0
+simundump xgraph /moregraphs/conc4 0 0 20 0 1.2 0
+simundump xcoredraw /edit/draw 0 -5 11 -9 9
+simundump xtree /edit/draw/tree 0 \
+  /kinetics/#[],/kinetics/#[]/#[],/kinetics/#[]/#[]/#[][TYPE!=proto],/kinetics/#[]/#[]/#[][TYPE!=linkinfo]/##[] \
+  "edit_elm.D <v>; drag_from_edit.w <d> <S> <x> <y> <z>" auto 0.6
+simundump xtext /file/notes 0 1
+addmsg /kinetics/Reac1 /kinetics/B REAC B A 
+addmsg /kinetics/Reac2 /kinetics/B REAC A B 
+addmsg /kinetics/Reac2 /kinetics/B REAC A B 
+addmsg /kinetics/Reac1 /kinetics/A REAC A B 
+addmsg /kinetics/A /kinetics/tot1 SUMTOTAL n nInit 
+addmsg /kinetics/B /kinetics/tot1 SUMTOTAL n nInit 
+addmsg /kinetics/Reac2 /kinetics/C REAC B A 
+addmsg /kinetics/MassActionEnz/e1 /kinetics/C REAC sA B 
+addmsg /kinetics/xtab /kinetics/D SLAVE output 
+addmsg /kinetics/Reac1 /kinetics/D REAC A B 
+addmsg /kinetics/A /kinetics/Reac1 SUBSTRATE n 
+addmsg /kinetics/B /kinetics/Reac1 PRODUCT n 
+addmsg /kinetics/D /kinetics/Reac1 SUBSTRATE n 
+addmsg /kinetics/C /kinetics/Reac2 PRODUCT n 
+addmsg /kinetics/B /kinetics/Reac2 SUBSTRATE n 
+addmsg /kinetics/B /kinetics/Reac2 SUBSTRATE n 
+addmsg /kinetics/MassActionEnz/e1 /kinetics/E MM_PRD pA 
+addmsg /kinetics/MM_Enz/e2 /kinetics/E REAC sA B 
+addmsg /kinetics/MassActionEnz/e1 /kinetics/MassActionEnz REAC eA B 
+addmsg /kinetics/MassActionEnz /kinetics/MassActionEnz/e1 ENZYME n 
+addmsg /kinetics/C /kinetics/MassActionEnz/e1 SUBSTRATE n 
+addmsg /kinetics/MM_Enz /kinetics/MM_Enz/e2 ENZYME n 
+addmsg /kinetics/E /kinetics/MM_Enz/e2 SUBSTRATE n 
+addmsg /kinetics/MM_Enz/e2 /kinetics/F MM_PRD pA 
+addmsg /kinetics/A /graphs/conc1/A.Co PLOT Co *A.Co *blue 
+addmsg /kinetics/B /graphs/conc1/B.Co PLOT Co *B.Co *62 
+addmsg /kinetics/tot1 /graphs/conc2/tot1.Co PLOT Co *tot1.Co *47 
+addmsg /kinetics/C /graphs/conc2/C.Co PLOT Co *C.Co *56 
+addmsg /kinetics/D /graphs/conc2/D.Co PLOT Co *D.Co *25 
+addmsg /kinetics/E /graphs/conc2/E.Co PLOT Co *E.Co *1 
+addmsg /kinetics/F /graphs/conc2/F.Co PLOT Co *F.Co *blue 
+enddump
+// End of dump
+
+setfield /kinetics/xtab table->dx 0.1
+setfield /kinetics/xtab table->invdx 10
+complete_loading
diff --git a/tests/python/test_kkit.py b/tests/python/test_kkit.py
index a87ede399ee8dde60916d8d832b77e69c4abab6d..b9bc6b81c1a0fd9d347cf05af053c31161e23754 100644
--- a/tests/python/test_kkit.py
+++ b/tests/python/test_kkit.py
@@ -1,69 +1,63 @@
-"""
-Test Kkit capabilities of PyMOOSE
-"""
-from __future__ import print_function
-    
-__author__           = "Dilawar Singh"
-__copyright__        = "Copyright 2015, Dilawar Singh and NCBS Bangalore"
-__credits__          = ["NCBS Bangalore"]
-__license__          = "GNU GPL"
-__version__          = "1.0.0"
-__maintainer__       = "Dilawar Singh"
-__email__            = "dilawars@ncbs.res.in"
-__status__           = "Development"
+import matplotlib
+# Tests may be run over ssh without -X e.g. on travis.
+matplotlib.use( 'Agg' )
 
+import matplotlib.pyplot as plt
+import numpy
 import sys
 import os
-
 import moose
-import moose.utils as mu
-
-# the model lives in the same directory as the test script
-modeldir = os.path.dirname(__file__)
 
-# All conc in micro-molar. MOOSE units are SI units.
-genesisReference = {
-        'MAPK_p.Co' : 0.00517021
-        , 'PKC_dash_active.Co' : 0.0923311
-        , 'nuc_MAPK_p.Co' : 2.3449e-6
-        , 'tot_MAPK.Co' : 0.00051749 
-        , 'MKP_dash_1.Co' : 0.00051749
-        , 'PDGFR.Co' : 0.10833
-        , 'PDGF.Co' : 0
-        , 'tot_MKP1.Co' : 0.000316181 
-        }
+scriptdir = os.path.dirname( os.path.realpath( __file__ ) )
+print( 'Script dir %s' % scriptdir )
 
 def main():
-    modelname = os.path.join(modeldir, 'chem_models/mkp1_feedback_effects_acc4.g')
-    model = moose.loadModel(modelname, '/model', 'gsl')
-    tables = moose.wildcardFind('/##[TYPE=Table2]')
-    records = {}
-    for t in tables: 
-        tabname = t.path.split('/')[-1].replace("[0]", "")
-        records[tabname] = t
-    moose.reinit()
-    moose.start(200)
-    check(records)
+        """ This example illustrates loading, running, and saving a kinetic model 
+        defined in kkit format. It uses a default kkit model but you can specify another using the command line ``python filename runtime solver``. We use the gsl solver here. The model already defines a couple of plots and sets the runtime to 20 seconds.
+        """
+        solver = "gsl"  # Pick any of gsl, gssa, ee..
+        mfile = os.path.join( scriptdir, 'genesis/kkit_objects_example.g' )
+        runtime = 20.0
+        if ( len( sys.argv ) >= 3 ):
+            if sys.argv[1][0] == '/':
+                mfile = sys.argv[1]
+            else:
+                mfile = './genesis/' + sys.argv[1]
+                runtime = float( sys.argv[2] )
+        if ( len( sys.argv ) == 4 ):
+                solver = sys.argv[3]
+        modelId = moose.loadModel( mfile, 'model', solver )
+        # Increase volume so that the stochastic solver gssa 
+        # gives an interesting output
+        #compt = moose.element( '/model/kinetics' )
+        #compt.volume = 1e-19 
+
+        moose.reinit()
+        moose.start( runtime ) 
+
+        # Report parameters
+        '''
+        for x in moose.wildcardFind( '/model/kinetics/##[ISA=PoolBase]' ):
+                print x.name, x.nInit, x.concInit
+        for x in moose.wildcardFind( '/model/kinetics/##[ISA=ReacBase]' ):
+                print x.name, 'num: (', x.numKf, ', ',  x.numKb, '), conc: (', x.Kf, ', ', x.Kb, ')'
+        for x in moose.wildcardFind('/model/kinetics/##[ISA=EnzBase]'):
+                print x.name, '(', x.Km, ', ',  x.numKm, ', ', x.kcat, ')'
+                '''
+
+        # Display all plots.
+        for x in moose.wildcardFind( '/model/#graphs/conc#/#' ):
+            t = numpy.arange( 0, x.vector.size, 1 ) * x.dt
+            plt.plot( t, x.vector, label=x.name )
 
-def check(records):
-    assert len(records) > 0, "No moose.Table2 created."
-    failed = False
-    for tabname in records:
-        if tabname in genesisReference:
-            genVal =  genesisReference[tabname]
-            mooseVal = 1e3 * records[tabname].vector[-1]
-            error = 100.0 % ( mooseVal - genVal ) / genVal
-            if abs(error) > 0.1:
-                failed = True
-            print("{:20}: Gensis/MOOSE: {:>10} {:>10}. %error: {}".format(
-                tabname, genVal, mooseVal, error)
-               )
-        else:
-            print("[WARN] %s not found in genesis reference" % tabname)
-    if failed:
-        quit(1)
-    else:
-        quit(0)
+        vals = x.vector
+        stats = [ vals.min(), vals.max( ), vals.mean(), vals.std( ) ]
+        expected = [ 0.0, 0.00040464 , 0.0001444 , 0.00013177 ]
+        assert numpy.allclose(stats, expected, rtol=1e-4) , 'Got %s expected %s' % (stats, expected ) 
+        plt.legend()
+        plt.savefig( '%s.png' % sys.argv[0] )
+        print( 'Wrote results to %s.png' % sys.argv[0] )
 
+# Run the 'main' if this script is executed standalone.
 if __name__ == '__main__':
-    main()
+        main()
diff --git a/tests/python/test_sbml.py b/tests/python/test_sbml.py
index 800d1e120de91052330b10554b3395c42c8c62e5..4a7163ecede113bfa555e78f91266c9108bcd400 100644
--- a/tests/python/test_sbml.py
+++ b/tests/python/test_sbml.py
@@ -16,26 +16,24 @@ import os
 
 import moose
 import moose.utils as mu
-from moose.SBML import *
+
 # the model lives in the same directory as the test script
-modeldir = os.path.dirname(__file__)
+modeldir = os.path.dirname( os.path.realpath( __file__ ) )
 
 def main():
-    modelname = os.path.join(modeldir, 'chem_models/00001-sbml-l3v1.xml')
-    model = mooseReadSBML(modelname, '/sbml')
-    tables = moose.wildcardFind('/sbml/##[TYPE=Table2]')
-    records = {}
-    for t in tables: records[t.path.split('/')[-1]] = t
+    modelname = os.path.join(modeldir, './chem_models/00001-sbml-l3v1.xml' )
+    model = moose.mooseReadSBML( modelname, '/sbml' )
+    print( model )
     c = moose.Clock('/clock')
     moose.reinit()
     moose.start(200)
-    #check(tables)
+    check(  )
 
-def check(tables):
-    assert len(tables) > 0, "No moose.Table2 created."
-    for t in tables:
-        assert len(t.vec) > 100
+def check( ):
     # TODO: Add more tests here.
+    p = moose.wildcardFind( '/sbml/##' )
+    for x in p:
+        print( x )
 
 if __name__ == '__main__':
     main()
diff --git a/tests/python/test_sbml_support.py b/tests/python/test_sbml_support.py
deleted file mode 100644
index 7d30a9d3b3bcb3a5ad501efcbde1232c20a22979..0000000000000000000000000000000000000000
--- a/tests/python/test_sbml_support.py
+++ /dev/null
@@ -1,96 +0,0 @@
-# -*- coding: utf-8 -*-
-# Filename: loadSbmlmodel.py
-# Description: 
-# Author: Harsha rani 
-# Maintainer: 
-# Created: Fri Jan 29 11:43:15 2016 (+0530)
-# Version: 
-# Last-Updated: 
-#           By: 
-#     Update #: 0
-# URL: 
-# Keywords: 
-# Compatibility: 
-# 
-# 
-
-# Commentary: 
-# 
-# 
-# 
-# 
-
-# Change log:
-# 
-# 
-# 
-# 
-# This program is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License as
-# published by the Free Software Foundation; either version 3, or
-# (at your option) any later version.
-# 
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-# General Public License for more details.
-# 
-# Thu 10 Mar 2016 10:52:27 AM IST
-#  Dilawar: Modified for turning it into a test script.
-# 
-
-import moose
-import sys
-import os
-from moose.SBML import *
-script_dir = os.path.dirname( os.path.realpath( __file__) )
-
-print( "Using moose from: %s" % moose.__file__ )
-
-def main():
-    """ This example illustrates loading, running of an SBML model defined in XML format.\n
-	The model 00001-sbml-l3v1.xml is taken from l3v1 SBML testcase.\n
-	Plots are setup.\n
-	Model is run for 20sec.\n
-	As a general rule we created model under '/path/model' and plots under '/path/graphs'.\n
-    """
-
-    mfile =  os.path.join( script_dir, 'chem_models/acc27.g')
-    runtime = 20.0
-    writefile =  os.path.join( script_dir, 'chem_models/acc27.xml')    
-    
-    #Load model to moose and write to SBML
-    moose.loadModel(mfile,'/acc27')
-    writeerror,message,sbmlId = moose.SBML.mooseWriteSBML('/acc27',writefile)
-    if writeerror == -2:
-        print ( "Could not save the Model" )
-    elif writeerror == -1:
-        print ( "\n This model is not valid SBML Model, failed in the consistency check ")
-    elif writeerror == 0:
-        print ("Could not save the Model ")
-    elif writeerror == 1:
-        print ( "Model is loaded using \'loadModel\' function to moose and using \'moose.SBML.mooseWriteSBML\' converted to SBML. \n Ran for 20 Sec" )
-        # Reset and Run
-        moose.reinit()
-        moose.start(runtime)
-    
-
-def displayPlots():
-    import matplotlib
-    import numpy as np
-    import matplotlib.pyplot as plt
-    import pylab
-
-    # Display all plots.
-    for x in moose.wildcardFind( '/sbml/graphs/#[TYPE=Table2]' ):
-        t = np.arange( 0, x.vector.size, 1 ) #sec
-        plt.plot( t, x.vector, label=x.name )
-    
-    pylab.legend()
-    pylab.show()
-
-    quit()
-if __name__=='__main__':
-    
-    main()
-    # displayPlots()
diff --git a/tests/python/test_streamer.py b/tests/python/test_streamer.py
index 3c16b76c97bac35d72e8a2ba1cfdf0c3eb4080f2..099b0cdb07c633ab963358eb8d1063c0e5003bc5 100644
--- a/tests/python/test_streamer.py
+++ b/tests/python/test_streamer.py
@@ -115,6 +115,7 @@ def test( ):
     print( time ) 
     assert data.shape >= (58,), data.shape
     print( '[INFO] Test 2 passed' )
+    return 0
 
 def main( ):
     sanity_test( )
diff --git a/utility/print_function.hpp b/utility/print_function.hpp
index 415d36ae6425d262e2df4955917230177f62dd23..885b88cde0298ca509a5b74f433e59930584cb36 100644
--- a/utility/print_function.hpp
+++ b/utility/print_function.hpp
@@ -224,7 +224,7 @@ namespace moose {
      */
 
 #ifdef  NDEBUG
-#define LOG(a, t ) ((void)0);
+#define LOG(t, a ) ((void)0);
 #else      /* -----  not NDEBUG  ----- */
 #define LOG(t, a) { stringstream __ss__;  __ss__ << a; moose::__dump__(__ss__.str(), t ); } 
 #endif     /* -----  not NDEBUG  ----- */