← Back to team overview

zorba-coders team mailing list archive

[Merge] lp:~zorba-coders/zorba/structuralrelationships2 into lp:~zorba-coders/zorba/zorba-experimental

 

Matthias Brantner has proposed merging lp:~zorba-coders/zorba/structuralrelationships2 into lp:~zorba-coders/zorba/zorba-experimental.

Requested reviews:
  Zorba Coders (zorba-coders)

For more details, see:
https://code.launchpad.net/~zorba-coders/zorba/structuralrelationships2/+merge/80620
-- 
https://code.launchpad.net/~zorba-coders/zorba/structuralrelationships2/+merge/80620
Your team Zorba Coders is requested to review the proposed merge of lp:~zorba-coders/zorba/structuralrelationships2 into lp:~zorba-coders/zorba/zorba-experimental.
=== modified file 'ChangeLog'
--- ChangeLog	2011-10-20 23:05:55 +0000
+++ ChangeLog	2011-10-27 20:59:25 +0000
@@ -53,6 +53,8 @@
   * Optimization for count(collection()) expressions
   * Fixed bug #872796  (validate-in-place can interfere with other update primitives)
   * Fixed bug #872799 (validate-in-place can set incorrect types)
+  * New node-position module. This module allows to obtain a representation of a node position, which
+    can be used to assess structural relationships with other nodes.   
   * Fixed bug #855715 (Invalid escaped characters in regex not caught)
 
 version 2.0.1

=== modified file 'modules/com/zorba-xquery/www/modules/CMakeLists.txt'
--- modules/com/zorba-xquery/www/modules/CMakeLists.txt	2011-09-30 08:08:13 +0000
+++ modules/com/zorba-xquery/www/modules/CMakeLists.txt	2011-10-27 20:59:25 +0000
@@ -46,6 +46,8 @@
   URI "http://www.zorba-xquery.com/modules/math";)
 DECLARE_ZORBA_MODULE(FILE node-reference.xq VERSION 2.0
   URI "http://www.zorba-xquery.com/modules/node-reference";)
+DECLARE_ZORBA_MODULE(FILE node-position.xq VERSION 2.0
+  URI "http://www.zorba-xquery.com/modules/node-position";)
 DECLARE_ZORBA_MODULE(FILE node.xq VERSION 2.0
   URI "http://www.zorba-xquery.com/modules/node";)
 DECLARE_ZORBA_MODULE(FILE project_xqdoc.xq VERSION 2.0

=== added file 'modules/com/zorba-xquery/www/modules/node-position.xq'
--- modules/com/zorba-xquery/www/modules/node-position.xq	1970-01-01 00:00:00 +0000
+++ modules/com/zorba-xquery/www/modules/node-position.xq	2011-10-27 20:59:25 +0000
@@ -0,0 +1,513 @@
+xquery version "1.0";
+(:
+ : Copyright 2006-2011 The FLWOR Foundation.
+ :
+ : Licensed under the Apache License, Version 2.0 (the "License");
+ : you may not use this file except in compliance with the License.
+ : You may obtain a copy of the License at
+ :
+ : http://www.apache.org/licenses/LICENSE-2.0
+ :
+ : Unless required by applicable law or agreed to in writing, software
+ : distributed under the License is distributed on an "AS IS" BASIS,
+ : WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ : See the License for the specific language governing permissions and
+ : limitations under the License.
+ :)
+
+(:~
+ : This module provides a function (np:node-position) that, given a node, 
+ : returns positional information about the node in the form of an xs:anyURI
+ : item. The module also defines functions that use such positional information
+ : to determine: (1) positional relationships between two nodes (e.g. if one 
+ : is the ancestor of another) and (2) positional properties of a single node
+ : (e.g. its level in the tree).
+ :
+ : Within this module, the term "node position" will be used to refer to an
+ : xs:anyURI item that is returned by the np:node-position function.
+ :
+ : @author Federico Cavalieri, Markos Zaharioudakis 
+ :)
+module namespace np = "http://www.zorba-xquery.com/modules/node-position";;
+
+declare namespace ver = "http://www.zorba-xquery.com/options/versioning";;
+declare option ver:module-version "2.0";
+
+(:~
+ : Compute a stable and opaque positional information representation 
+ : (with type xs:anyURI) for a given node.
+ : 
+ : <p>Each node in a snapshot has a different URI. Note however that
+ : different nodes in different snapshots might have the same URI.</p>  
+ :
+ : @param $arg the node for which the positional information URI
+ :  should be computed
+ :
+ : @return the opaque positional information URI of the node.
+ :)
+declare function np:node-position(
+  $arg as node()
+) as xs:anyURI external;
+
+(:~
+ : Determines whether the node position given as second argument is
+ : an ancestor of the node position given as first argument.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node is an ancestor of the first.
+ : Otherwise, the result of the function does not imply anything about the
+ : positional relationship of the two nodes.
+ :
+ : @param $n-pos1 the potential descendant node position
+ : @param $n-pos2 the potential ancestor node position
+ :
+ : @return true if the node position $n-pos2 is an ancestor of the node position
+ : $n-pos1; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function. 
+ :)
+declare function np:ancestor-of(
+  $n-pos1 as xs:anyURI,
+  $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether the node position given as second argument belongs
+ : to the subtree rooted at the node position given as first argument.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node belongs to the subtree rooted at the 
+ : first. Otherwise, the result of the function does not imply anything about 
+ : the positional relationship of the two nodes.
+ :
+ : @param $n-pos1 the potential subtree root node position
+ : @param $n-pos2 the potential node in the subtree node position
+ :
+ : @return true if the node position $n-pos2 belongs to the subtree rooted at 
+ : the node position $n-pos1; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:in-subtree-of(
+  $n-pos1 as xs:anyURI,
+  $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether the node position given as second argument is
+ : a descendant of the node position given as first argument.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node is a descendant of the first.
+ : Otherwise, the result of the function does not imply anything about the
+ : positional relationship of the two nodes.
+ :
+ : @param $n-pos1 the potential ancestor node position
+ : @param $n-pos2 the potential descendant node position
+ :
+ : @return true if the node position $n-pos2 is a descendant of the node 
+ : position $n-pos1; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:descendant-of(
+  $n-pos1 as xs:anyURI,
+  $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether the node position given as second argument is
+ : the parent of the node position given as first argument.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node is the parent of the first.
+ : Otherwise, the result of the function does not imply anything about the
+ : positional relationship of the two nodes.
+ :
+ : @param $n-pos1 the potential child node position
+ : @param $n-pos2 the potential parent node position
+ :
+ : @return true if the node position $n-pos2 is the parent of the node position 
+ : $n-pos1; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:parent-of(
+  $n-pos1 as xs:anyURI,
+  $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether the node position given as second argument is
+ : a child of the node position given as first argument.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node is a child of the first.
+ : Otherwise, the result of the function does not imply anything about the
+ : positional relationship of the two nodes.
+ :
+ : @param $n-pos1 the potential parent node position
+ : @param $n-pos2 the potential child node position
+ :
+ : @return true if the node position $n-pos2 is a child of the node position 
+ : $n-pos1; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:child-of(
+  $n-pos1 as xs:anyURI,
+  $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether the node position given as second argument is
+ : an attribute of the node position given as first argument.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node is an attribute of the first.
+ : Otherwise, the result of the function does not imply anything about the
+ : positional relationship of the two nodes.
+ :
+ : @param $n-pos1 the potential parent node position
+ : @param $n-pos2 the potential attribute node position
+ :
+ : @return true if the node position $n-pos2 is an attribute of the node 
+ : position $n-pos1; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:attribute-of(
+  $n-pos1 as xs:anyURI,
+  $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether the node position given as second argument is
+ : a following-sibling of the node position given as first argument.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node is a following-sibling of the first.
+ : Otherwise, the result of the function does not imply anything about the
+ : positional relationship of the two nodes.
+ :
+ : @param $n-pos1 the potential preceding-sibling node position
+ : @param $n-pos2 the potential following-sibling node position
+ :
+ : @return true if the node position $n-pos2 is a following-sibling of the node 
+ : position $n-pos1; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:following-sibling-of(
+  $n-pos1 as xs:anyURI,
+  $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether the node position given as second argument is
+ : a preceding-sibling of the node position given as first argument.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node is a preceding-sibling of the first.
+ : Otherwise, the result of the function does not imply anything about the
+ : positional relationship of the two nodes.
+ :
+ : @param $n-pos1 the potential following-sibling node position
+ : @param $n-pos2 the potential preceding-sibling node position
+ :
+ : @return true if the node position $n-pos2 is a preceding-sibling of the node 
+ : position $n-pos1; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:preceding-sibling-of(
+  $n-pos1 as xs:anyURI,
+  $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether two node positions are siblings.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node is a sibling of the first.
+ : Otherwise, the result of the function does not imply anything about the
+ : positional relationship of the two nodes.
+ :
+ : @param $n-pos1 a node position
+ : @param $n-pos2 a node position
+ :
+ : @return true if the two node positions $n-pos1 and $n-pos2 are siblings; 
+ : false otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)  
+declare function np:sibling-of(
+  $n-pos1 as xs:anyURI,
+  $n-pos2 as xs:anyURI) as xs:boolean external;
+  
+(:~
+ : Determines whether the node position given as second argument is
+ : following the node position given as first argument.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node is following the first.
+ : Otherwise, the result of the function does not imply anything about the
+ : positional relationship of the two nodes.
+ :
+ : @param $n-pos1 the potential preceding node position
+ : @param $n-pos2 the potential following node position
+ :
+ : @return true if the node position $n-pos2 is following the node position 
+ : $n-pos1; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:following-of(
+  $n-pos1 as xs:anyURI,
+  $n-pos2 as xs:anyURI) as xs:boolean external;
+  
+(:~
+ : Determines whether the node position given as second argument is
+ : following in document order the node position given as first argument.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node is following in document order the 
+ : first. Otherwise, the result of the function does not imply anything about 
+ : the positional relationship of the two nodes.
+ :
+ : @param $n-pos1 the potential preceding node position
+ : @param $n-pos2 the potential following node position
+ :
+ : @return true if the node position $n-pos2 is following in document order the
+ : node position $n-pos1; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:following-in-document-order-of(
+  $n-pos1 as xs:anyURI,
+  $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether the node position given as second argument is
+ : preceding the node position given as first argument.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node is preceding the first.
+ : Otherwise, the result of the function does not imply anything about the
+ : positional relationship of the two nodes.
+ :
+ : @param $n-pos1 the potential following node position
+ : @param $n-pos2 the potential preceding node position
+ :
+ : @return true if the node position $n-pos2 is preceding the node position 
+ : $n-pos1; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:preceding-of(
+  $n-pos1 as xs:anyURI,
+  $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether the node position given as second argument is
+ : preceding in document order the node position given as first argument.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node is preceding in document order the 
+ : first. Otherwise, the result of the function does not imply anything about 
+ : the positional relationship of the two nodes.
+ :
+ : @param $n-pos1 the potential following node position
+ : @param $n-pos2 the potential preceding node position
+ :
+ : @return true if the node position $n-pos2 is preceding in document order the 
+ : node position $n-pos1; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:preceding-in-document-order-of(
+  $n-pos1 as xs:anyURI,
+  $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Computes the level of a node position in its tree.
+ :
+ : Note: The first level has the number one.
+ :
+ : The result of the function applies to the corresponding node as well, 
+ : that is, within the snapshot in which the position was computed, the node 
+ : level is the returned one.
+ : The result of the function does not imply anything about the
+ : node level in other snapshots.
+ :
+ : @param $n-pos the node position of the node whose level should be 
+ : determined.
+ :
+ : @return the level in the tree of the node position $n-pos as xs:integer.
+ :
+ : @error zerr:ZAPI0028 if the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:level(
+  $n-pos as xs:anyURI) as xs:integer external;  
+
+(:~
+ : Determines whether a node position corresponds to an attribute node.
+ :
+ : @param $n-pos the potential attribute node position
+ :
+ : @return true if the node position $n-pos corresponds to an attribute; 
+ : false otherwise.
+ :
+ : @error zerr:ZAPI0028 if the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:is-attribute(
+  $n-pos1 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether a node position corresponds to a comment node.
+ :
+ : @param $n-pos the potential comment node position
+ :
+ : @return true if the node position $n-pos corresponds to an comment; 
+ : false otherwise.
+ :
+ : @error zerr:ZAPI0028 if the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:is-comment(
+  $n-pos1 as xs:anyURI) as xs:boolean external;
+  
+(:~
+ : Determines whether a node position corresponds to a document node.
+ :
+ : @param $n-pos the potential document node position
+ :
+ : @return true if the node position $n-pos corresponds to a document; 
+ : false otherwise.
+ :
+ : @error zerr:ZAPI0028 if the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:is-document(
+  $n-pos1 as xs:anyURI) as xs:boolean external;
+  
+(:~
+ : Determines whether a node position corresponds to an element node.
+ :
+ : @param $n-pos the potential element node position
+ :
+ : @return true if the node position $n-pos corresponds to an element; 
+ : false otherwise.
+ :
+ : @error zerr:ZAPI0028 if the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:is-element(
+  $n-pos1 as xs:anyURI) as xs:boolean external;
+  
+(:~
+ : Determines whether a node position corresponds to an processing-instruction
+ : node.
+ :
+ : @param $n-pos the potential processing-instruction node position
+ :
+ : @return true if the node position $n-pos corresponds to a processing 
+ : instruction; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:is-processing-instruction(
+  $n-pos1 as xs:anyURI) as xs:boolean external;
+  
+(:~
+ : Determines whether a node position corresponds to a text node.
+ :
+ : @param $n-pos the potential text node position
+ :
+ : @return true if the node position $n-pos corresponds to a text; 
+ : false otherwise.
+ :
+ : @error zerr:ZAPI0028 if the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:is-text(
+  $n-pos1 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether two node positions belong to the same tree.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the two nodes belong to the same tree. 
+ : Otherwise, the result of the function does not imply anything about 
+ : the positional relationship of the two nodes.
+ :
+ : @param $n-pos1 a node position
+ : @param $n-pos2 a node position
+ :
+ : @return true if the two nodes whose node positions are $n-pos1
+ : and $n-pos2 belong to the same tree.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)  
+declare function np:in-same-tree-of(
+  $n-pos1 as xs:anyURI,
+  $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether a node position belongs to a collection.
+ :
+ : @param $n-pos the node position
+ :
+ : @return true if the node position $n-pos 
+ : belongs to a collection; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:in-collection(
+  $n-pos as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether two node positions belong to the same collection.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the two nodes belong to the same collection. 
+ : Otherwise, the result of the function does not imply anything about 
+ : the positional relationship of the two nodes.
+ :
+ : @param $n-pos1 a node position
+ : @param $n-pos2 a node position
+ :
+ : @return true if the two nodes whose node positions are $n-pos1
+ : and $n-pos2 belong to the same collection.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)  
+declare function np:in-same-collection-of(
+  $n-pos1 as xs:anyURI,
+  $n-pos2 as xs:anyURI) as xs:boolean external;

=== modified file 'src/compiler/codegen/plan_visitor.cpp'
--- src/compiler/codegen/plan_visitor.cpp	2011-09-16 19:36:18 +0000
+++ src/compiler/codegen/plan_visitor.cpp	2011-10-27 20:59:25 +0000
@@ -199,7 +199,10 @@
 
 
 /*******************************************************************************
-
+  A FlworClauseVarMap is created for each flwor clause that defines variables.
+  If M is such a clause, then for each variable Vi defined by M, theVarExprs[i]
+  and theVarRebinds[i] contain an entry for Vi. theVarExprs[i] contains the
+  var_expr representing the Vi definition. 
 ********************************************************************************/
 class FlworClauseVarMap : public SimpleRCObject
 {
@@ -207,7 +210,7 @@
   bool                          theIsGeneral;
   const flwor_clause          * theClause;
 
-  std::vector<const var_expr*>  theVarExprs;
+  std::vector<var_expr*>        theVarExprs;
   std::vector<VarRebind_t>      theVarRebinds;
 
 public:
@@ -222,8 +225,8 @@
 
   long find_var(const var_expr* var) const
   {
-    ulong numVars = (ulong)theVarExprs.size();
-    for (ulong i = 0; i < numVars; ++i)
+    csize numVars = theVarExprs.size();
+    for (csize i = 0; i < numVars; ++i)
     {
       if (theVarExprs[i] == var)
         return i;
@@ -759,7 +762,7 @@
         {
           varRebind = new VarRebind;
 
-          clauseVarMap->theVarExprs.push_back(&var);
+          clauseVarMap->theVarExprs.push_back(const_cast<var_expr*>(&var));
           clauseVarMap->theVarRebinds.push_back(varRebind);
 
           varRebind->theInputVar = varIter;
@@ -1189,14 +1192,14 @@
     const group_clause::rebind_list_t& grouping_vars = gbc->get_grouping_vars();
     const group_clause::rebind_list_t& nongrouping_vars = gbc->get_nongrouping_vars();
 
-    for (unsigned i = 0; i < grouping_vars.size(); i++)
+    for (unsigned i = 0; i < grouping_vars.size(); ++i)
     {
       VarRebind_t varRebind = new VarRebind;
       clauseVarMap->theVarExprs.push_back(grouping_vars[i].second.getp());
       clauseVarMap->theVarRebinds.push_back(varRebind);
     }
 
-    for (unsigned i = 0; i < nongrouping_vars.size(); i++)
+    for (unsigned i = 0; i < nongrouping_vars.size(); ++i)
     {
       VarRebind_t varRebind = new VarRebind;
       clauseVarMap->theVarExprs.push_back(nongrouping_vars[i].second.getp());
@@ -1363,22 +1366,17 @@
 
   xqtref_t colType = colExpr->get_return_type();
 
-  if (TypeOps::is_subtype(tm, *colType, *rtm.STRING_TYPE_STAR, loc) ||
-      TypeOps::is_subtype(tm, *colType, *rtm.DOUBLE_TYPE_STAR, loc) ||
-      TypeOps::is_subtype(tm, *colType, *rtm.FLOAT_TYPE_STAR, loc) ||
-      TypeOps::is_subtype(tm, *colType, *rtm.LONG_TYPE_STAR, loc) ||
-      TypeOps::is_subtype(tm, *colType, *rtm.UNSIGNED_LONG_TYPE_STAR, loc) ||
-      TypeOps::is_equal(tm,
-                        *TypeOps::prime_type(tm, *colType),
-                        *rtm.DECIMAL_TYPE_ONE,
-                        loc) ||
-      TypeOps::is_equal(tm,
-                        *TypeOps::prime_type(tm, *colType),
-                        *rtm.INTEGER_TYPE_ONE,
-                        loc) ||
-      TypeOps::is_subtype(tm, *colType, *rtm.DATE_TYPE_STAR, loc) ||
-      TypeOps::is_subtype(tm, *colType, *rtm.TIME_TYPE_STAR, loc) ||
-      TypeOps::is_subtype(tm, *colType, *rtm.DATETIME_TYPE_STAR, loc))
+  if (colType->type_kind() == XQType::NODE_TYPE_KIND)
+  {
+    colType = static_cast<const NodeXQType*>(colType.getp())->get_content_type();
+  }
+
+  if (colType != NULL &&
+      TypeOps::is_subtype(tm, *colType, *rtm.ANY_ATOMIC_TYPE_STAR, loc) &&
+      !TypeOps::is_equal(tm, 
+                         *TypeOps::prime_type(tm, *colType),
+                         *rtm.ANY_ATOMIC_TYPE_ONE,
+                         loc))
   {
     return true;
   }
@@ -1669,7 +1667,7 @@
     if (c.get_kind() != flwor_clause::where_clause)
     {
       ZORBA_ASSERT(!theClauseStack.empty());
-      ulong stackSize = (ulong)theClauseStack.size();
+      csize stackSize = theClauseStack.size();
 
       clauseVarMap = theClauseStack[stackSize-1];
       theClauseStack.resize(stackSize - 1);
@@ -1878,9 +1876,12 @@
     std::vector<flwor::NonGroupingSpec>& ngspecs)
 {
   const group_clause* gbc = static_cast<const group_clause*>(clauseVarMap->theClause);
+
   const group_clause::rebind_list_t& gvars = gbc->get_grouping_vars();
   const group_clause::rebind_list_t& ngvars = gbc->get_nongrouping_vars();
+
   const std::vector<std::string>& collations = gbc->get_collations();
+
   long numVars = (long)(gvars.size() + ngvars.size());
   long numGroupVars = (long)gvars.size();
   long i = numVars - 1;
@@ -1900,7 +1901,12 @@
 
     const std::vector<PlanIter_t>& varRefs = varRebind->theOutputVarRefs;
 
-    gspecs.push_back(flwor::GroupingSpec(pop_itstack(), varRefs, collations[i]));
+    bool fastComparison = nativeColumnSort(clauseVarMap->theVarExprs[i]);
+
+    gspecs.push_back(flwor::GroupingSpec(pop_itstack(),
+                                         varRefs,
+                                         collations[i],
+                                         fastComparison));
   }
 }
 

=== modified file 'src/compiler/expression/flwor_expr.cpp'
--- src/compiler/expression/flwor_expr.cpp	2011-08-15 14:17:09 +0000
+++ src/compiler/expression/flwor_expr.cpp	2011-10-27 20:59:25 +0000
@@ -616,26 +616,26 @@
   theNonGroupVars(ngvars),
   theCollations(collations)
 {
-  ulong numGVars = (ulong)theGroupVars.size();
-  ulong numNGVars = (ulong)theNonGroupVars.size();
+  csize numGVars = theGroupVars.size();
+  csize numNGVars = theNonGroupVars.size();
 
-  for (ulong i = 0; i < numGVars; ++i)
+  for (csize i = 0; i < numGVars; ++i)
     theGroupVars[i].second->set_flwor_clause(this);
 
-  for (ulong i = 0; i < numNGVars; ++i)
+  for (csize i = 0; i < numNGVars; ++i)
     theNonGroupVars[i].second->set_flwor_clause(this);
 }
 
 
 group_clause::~group_clause()
 {
-  ulong numGVars = (ulong)theGroupVars.size();
-  ulong numNGVars = (ulong)theNonGroupVars.size();
+  csize numGVars = theGroupVars.size();
+  csize numNGVars = theNonGroupVars.size();
 
-  for (ulong i = 0; i < numGVars; ++i)
+  for (csize i = 0; i < numGVars; ++i)
     theGroupVars[i].second->set_flwor_clause(NULL);
 
-  for (ulong i = 0; i < numNGVars; ++i)
+  for (csize i = 0; i < numNGVars; ++i)
     theNonGroupVars[i].second->set_flwor_clause(NULL);
 }
 
@@ -651,8 +651,8 @@
 
 expr* group_clause::get_input_for_group_var(const var_expr* var)
 {
-  ulong numVars = (ulong)theGroupVars.size();
-  for (ulong i = 0; i < numVars; ++i)
+  csize numVars = theGroupVars.size();
+  for (csize i = 0; i < numVars; ++i)
   {
     if (theGroupVars[i].second.getp() == var)
       return theGroupVars[i].first.getp();
@@ -664,8 +664,8 @@
 
 expr* group_clause::get_input_for_nongroup_var(const var_expr* var)
 {
-  ulong numVars = (ulong)theNonGroupVars.size();
-  for (ulong i = 0; i < numVars; ++i)
+  csize numVars = theNonGroupVars.size();
+  for (csize i = 0; i < numVars; ++i)
   {
     if (theNonGroupVars[i].second.getp() == var)
       return theNonGroupVars[i].first.getp();
@@ -677,20 +677,20 @@
 
 flwor_clause_t group_clause::clone(expr::substitution_t& subst) const
 {
-  ulong numGroupVars = (ulong)theGroupVars.size();
-  ulong numNonGroupVars = (ulong)theNonGroupVars.size();
+  csize numGroupVars = theGroupVars.size();
+  csize numNonGroupVars = theNonGroupVars.size();
 
   rebind_list_t cloneGroupVars(numGroupVars);
   rebind_list_t cloneNonGroupVars(numNonGroupVars);
 
-  for (ulong i = 0; i < numGroupVars; ++i)
+  for (csize i = 0; i < numGroupVars; ++i)
   {
     cloneGroupVars[i].first = theGroupVars[i].first->clone(subst);
     cloneGroupVars[i].second = new var_expr(*theGroupVars[i].second);
     subst[theGroupVars[i].second.getp()] = cloneGroupVars[i].second.getp();
   }
 
-  for (ulong i = 0; i < numNonGroupVars; ++i)
+  for (csize i = 0; i < numNonGroupVars; ++i)
   {
     cloneNonGroupVars[i].first = theNonGroupVars[i].first->clone(subst);
     cloneNonGroupVars[i].second = new var_expr(*theNonGroupVars[i].second);

=== modified file 'src/compiler/translator/translator.cpp'
--- src/compiler/translator/translator.cpp	2011-10-18 21:29:50 +0000
+++ src/compiler/translator/translator.cpp	2011-10-27 20:59:25 +0000
@@ -1305,11 +1305,25 @@
     if (qname != NULL)
     {
       RAISE_ERROR(zerr::ZDDY0025_INDEX_WRONG_NUMBER_OF_PROBE_ARGS, loc,
-      ERROR_PARAMS(qname->getStringValue()));
+      ERROR_PARAMS(
+        qname->getStringValue(),
+        "index",
+        n-1,
+        "multiple of 6"
+      )
+      );
     }
     else
     {
-      RAISE_ERROR_NO_PARAMS(zerr::ZDDY0025_INDEX_WRONG_NUMBER_OF_PROBE_ARGS, loc);
+      RAISE_ERROR(
+          zerr::ZDDY0025_INDEX_WRONG_NUMBER_OF_PROBE_ARGS, loc,
+          ERROR_PARAMS(
+            "anonymous",
+            "index",
+            n-1,
+            "multiple of 6"
+          )
+      );
     }
   }
 

=== modified file 'src/context/static_context.cpp'
--- src/context/static_context.cpp	2011-10-18 19:06:06 +0000
+++ src/context/static_context.cpp	2011-10-27 20:59:25 +0000
@@ -280,6 +280,9 @@
 static_context::ZORBA_NODEREF_FN_NS = NS_PRE + "modules/node-reference";
 
 const zstring
+static_context::ZORBA_NODEPOS_FN_NS = NS_PRE + "modules/node-position";
+
+const zstring
 static_context::ZORBA_STORE_DYNAMIC_COLLECTIONS_DDL_FN_NS
   = NS_PRE + "modules/store/dynamic/collections/ddl";
 
@@ -373,6 +376,7 @@
     return (ns == ZORBA_MATH_FN_NS ||
             ns == ZORBA_BASE64_FN_NS ||
             ns == ZORBA_NODEREF_FN_NS ||
+            ns == ZORBA_NODEPOS_FN_NS ||
             ns == ZORBA_STORE_DYNAMIC_DOCUMENTS_FN_NS ||
             ns == ZORBA_STORE_DYNAMIC_UNORDERED_MAP_FN_NS ||
             ns == ZORBA_STORE_DYNAMIC_COLLECTIONS_DDL_FN_NS ||

=== modified file 'src/context/static_context.h'
--- src/context/static_context.h	2011-10-18 19:06:06 +0000
+++ src/context/static_context.h	2011-10-27 20:59:25 +0000
@@ -459,6 +459,7 @@
   static const zstring ZORBA_MATH_FN_NS;
   static const zstring ZORBA_BASE64_FN_NS;
   static const zstring ZORBA_NODEREF_FN_NS;
+  static const zstring ZORBA_NODEPOS_FN_NS;
   static const zstring ZORBA_STORE_DYNAMIC_COLLECTIONS_DDL_FN_NS;
   static const zstring ZORBA_STORE_DYNAMIC_COLLECTIONS_DML_FN_NS;
   static const zstring ZORBA_STORE_STATIC_COLLECTIONS_DDL_FN_NS;

=== modified file 'src/diagnostics/diagnostic_en.xml'
--- src/diagnostics/diagnostic_en.xml	2011-10-17 21:17:05 +0000
+++ src/diagnostics/diagnostic_en.xml	2011-10-27 20:59:25 +0000
@@ -1966,7 +1966,7 @@
     </diagnostic>
 
     <diagnostic code="ZDDY0025" name="INDEX_WRONG_NUMBER_OF_PROBE_ARGS">
-      <value>${"1": }invalid number of arguments in probe</value>
+      <value>"$1": invalid number of arguments to $2 operation; given $3 expected $4</value>
     </diagnostic>
 
     <diagnostic code="ZDDY0026" name="INDEX_RANGE_PROBE_NOT_ALLOWED">

=== modified file 'src/diagnostics/pregenerated/dict_en.cpp'
--- src/diagnostics/pregenerated/dict_en.cpp	2011-10-20 23:05:55 +0000
+++ src/diagnostics/pregenerated/dict_en.cpp	2011-10-27 20:59:25 +0000
@@ -286,7 +286,7 @@
   { "ZDDY0022", "\"$1\": index already exists" },
   { "ZDDY0023", "\"$1\": index does not exist" },
   { "ZDDY0024", "\"$1\": index uniqueness violation" },
-  { "ZDDY0025", "${\"1\": }invalid number of arguments in probe" },
+  { "ZDDY0025", "\"$1\": invalid number of arguments to $2 operation; given $3 expected $4" },
   { "ZDDY0026", "\"$1\": index range probe not allowed" },
   { "ZDDY0027", "\"$1\": index multiple creates" },
   { "ZDDY0028", "\"$1\": index domain has duplicate nodes" },

=== modified file 'src/functions/library.cpp'
--- src/functions/library.cpp	2011-09-27 16:01:34 +0000
+++ src/functions/library.cpp	2011-10-27 20:59:25 +0000
@@ -44,6 +44,7 @@
 #include "functions/func_ic_ddl.h"
 #include "functions/func_maths.h"
 #include "functions/func_nodes.h"
+#include "functions/func_node_position.h"
 #include "functions/func_node_sort_distinct.h"
 #include "functions/func_numerics.h"
 #include "functions/func_numerics_impl.h"
@@ -108,6 +109,7 @@
   populate_context_ic_ddl(sctx);
   populate_context_maths(sctx);
   populate_context_nodes(sctx);
+  populate_context_node_position(sctx);
   populate_context_numerics(sctx);
   populate_context_other_diagnostics(sctx);
   populate_context_parsing_and_serializing(sctx);

=== added file 'src/functions/pregenerated/func_node_position.cpp'
--- src/functions/pregenerated/func_node_position.cpp	1970-01-01 00:00:00 +0000
+++ src/functions/pregenerated/func_node_position.cpp	2011-10-27 20:59:25 +0000
@@ -0,0 +1,584 @@
+/*
+ * Copyright 2006-2008 The FLWOR Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+ 
+// ******************************************
+// *                                        *
+// * THIS IS A GENERATED FILE. DO NOT EDIT! *
+// * SEE .xml FILE WITH SAME NAME           *
+// *                                        *
+// ******************************************
+
+
+#include "stdafx.h"
+#include "runtime/nodes/node_position.h"
+#include "functions/func_node_position.h"
+
+
+namespace zorba{
+
+
+
+PlanIter_t fn_zorba_pos_node_position::codegen(
+  CompilerCB*,
+  static_context* sctx,
+  const QueryLoc& loc,
+  std::vector<PlanIter_t>& argv,
+  AnnotationHolder& ann) const
+{
+  return new NodePositionIterator(sctx, loc, argv);
+}
+
+PlanIter_t fn_zorba_pos_ancestor_of::codegen(
+  CompilerCB*,
+  static_context* sctx,
+  const QueryLoc& loc,
+  std::vector<PlanIter_t>& argv,
+  AnnotationHolder& ann) const
+{
+  return new IsAncestorPositionIterator(sctx, loc, argv);
+}
+
+PlanIter_t fn_zorba_pos_following_sibling_of::codegen(
+  CompilerCB*,
+  static_context* sctx,
+  const QueryLoc& loc,
+  std::vector<PlanIter_t>& argv,
+  AnnotationHolder& ann) const
+{
+  return new IsFollowingSiblingPositionIterator(sctx, loc, argv);
+}
+
+PlanIter_t fn_zorba_pos_following_of::codegen(
+  CompilerCB*,
+  static_context* sctx,
+  const QueryLoc& loc,
+  std::vector<PlanIter_t>& argv,
+  AnnotationHolder& ann) const
+{
+  return new IsFollowingPositionIterator(sctx, loc, argv);
+}
+
+PlanIter_t fn_zorba_pos_in_subtree_of::codegen(
+  CompilerCB*,
+  static_context* sctx,
+  const QueryLoc& loc,
+  std::vector<PlanIter_t>& argv,
+  AnnotationHolder& ann) const
+{
+  return new IsInSubtreeOfPositionIterator(sctx, loc, argv);
+}
+
+PlanIter_t fn_zorba_pos_descendant_of::codegen(
+  CompilerCB*,
+  static_context* sctx,
+  const QueryLoc& loc,
+  std::vector<PlanIter_t>& argv,
+  AnnotationHolder& ann) const
+{
+  return new IsDescendantPositionIterator(sctx, loc, argv);
+}
+
+PlanIter_t fn_zorba_pos_preceding_sibling_of::codegen(
+  CompilerCB*,
+  static_context* sctx,
+  const QueryLoc& loc,
+  std::vector<PlanIter_t>& argv,
+  AnnotationHolder& ann) const
+{
+  return new IsPrecedingSiblingPositionIterator(sctx, loc, argv);
+}
+
+PlanIter_t fn_zorba_pos_preceding_of::codegen(
+  CompilerCB*,
+  static_context* sctx,
+  const QueryLoc& loc,
+  std::vector<PlanIter_t>& argv,
+  AnnotationHolder& ann) const
+{
+  return new IsPrecedingPositionIterator(sctx, loc, argv);
+}
+
+PlanIter_t fn_zorba_pos_child_of::codegen(
+  CompilerCB*,
+  static_context* sctx,
+  const QueryLoc& loc,
+  std::vector<PlanIter_t>& argv,
+  AnnotationHolder& ann) const
+{
+  return new IsChildPositionIterator(sctx, loc, argv);
+}
+
+PlanIter_t fn_zorba_pos_attribute_of::codegen(
+  CompilerCB*,
+  static_context* sctx,
+  const QueryLoc& loc,
+  std::vector<PlanIter_t>& argv,
+  AnnotationHolder& ann) const
+{
+  return new IsAttributeOfPositionIterator(sctx, loc, argv);
+}
+
+PlanIter_t fn_zorba_pos_parent_of::codegen(
+  CompilerCB*,
+  static_context* sctx,
+  const QueryLoc& loc,
+  std::vector<PlanIter_t>& argv,
+  AnnotationHolder& ann) const
+{
+  return new IsParentPositionIterator(sctx, loc, argv);
+}
+
+PlanIter_t fn_zorba_pos_preceding_in_document_order_of::codegen(
+  CompilerCB*,
+  static_context* sctx,
+  const QueryLoc& loc,
+  std::vector<PlanIter_t>& argv,
+  AnnotationHolder& ann) const
+{
+  return new IsPrecedingInDocumentOrderPositionIterator(sctx, loc, argv);
+}
+
+PlanIter_t fn_zorba_pos_following_in_document_order_of::codegen(
+  CompilerCB*,
+  static_context* sctx,
+  const QueryLoc& loc,
+  std::vector<PlanIter_t>& argv,
+  AnnotationHolder& ann) const
+{
+  return new IsFollowingInDocumentOrderPositionIterator(sctx, loc, argv);
+}
+
+PlanIter_t fn_zorba_pos_level::codegen(
+  CompilerCB*,
+  static_context* sctx,
+  const QueryLoc& loc,
+  std::vector<PlanIter_t>& argv,
+  AnnotationHolder& ann) const
+{
+  return new LevelPositionIterator(sctx, loc, argv);
+}
+
+PlanIter_t fn_zorba_pos_is_attribute::codegen(
+  CompilerCB*,
+  static_context* sctx,
+  const QueryLoc& loc,
+  std::vector<PlanIter_t>& argv,
+  AnnotationHolder& ann) const
+{
+  return new IsAttributePositionIterator(sctx, loc, argv);
+}
+
+PlanIter_t fn_zorba_pos_is_comment::codegen(
+  CompilerCB*,
+  static_context* sctx,
+  const QueryLoc& loc,
+  std::vector<PlanIter_t>& argv,
+  AnnotationHolder& ann) const
+{
+  return new IsCommentPositionIterator(sctx, loc, argv);
+}
+
+PlanIter_t fn_zorba_pos_is_document::codegen(
+  CompilerCB*,
+  static_context* sctx,
+  const QueryLoc& loc,
+  std::vector<PlanIter_t>& argv,
+  AnnotationHolder& ann) const
+{
+  return new IsDocumentPositionIterator(sctx, loc, argv);
+}
+
+PlanIter_t fn_zorba_pos_is_element::codegen(
+  CompilerCB*,
+  static_context* sctx,
+  const QueryLoc& loc,
+  std::vector<PlanIter_t>& argv,
+  AnnotationHolder& ann) const
+{
+  return new IsElementPositionIterator(sctx, loc, argv);
+}
+
+PlanIter_t fn_zorba_pos_is_processing_instruction::codegen(
+  CompilerCB*,
+  static_context* sctx,
+  const QueryLoc& loc,
+  std::vector<PlanIter_t>& argv,
+  AnnotationHolder& ann) const
+{
+  return new IsProcessingInstructionPositionIterator(sctx, loc, argv);
+}
+
+PlanIter_t fn_zorba_pos_is_text::codegen(
+  CompilerCB*,
+  static_context* sctx,
+  const QueryLoc& loc,
+  std::vector<PlanIter_t>& argv,
+  AnnotationHolder& ann) const
+{
+  return new IsTextPositionIterator(sctx, loc, argv);
+}
+
+PlanIter_t fn_zorba_pos_sibling_of::codegen(
+  CompilerCB*,
+  static_context* sctx,
+  const QueryLoc& loc,
+  std::vector<PlanIter_t>& argv,
+  AnnotationHolder& ann) const
+{
+  return new IsSiblingPositionIterator(sctx, loc, argv);
+}
+
+PlanIter_t fn_zorba_pos_in_same_tree_of::codegen(
+  CompilerCB*,
+  static_context* sctx,
+  const QueryLoc& loc,
+  std::vector<PlanIter_t>& argv,
+  AnnotationHolder& ann) const
+{
+  return new InSameTreePositionIterator(sctx, loc, argv);
+}
+
+PlanIter_t fn_zorba_pos_in_collection::codegen(
+  CompilerCB*,
+  static_context* sctx,
+  const QueryLoc& loc,
+  std::vector<PlanIter_t>& argv,
+  AnnotationHolder& ann) const
+{
+  return new InCollectionPositionIterator(sctx, loc, argv);
+}
+
+PlanIter_t fn_zorba_pos_in_same_collection_of::codegen(
+  CompilerCB*,
+  static_context* sctx,
+  const QueryLoc& loc,
+  std::vector<PlanIter_t>& argv,
+  AnnotationHolder& ann) const
+{
+  return new InSameCollectionPositionIterator(sctx, loc, argv);
+}
+
+void populate_context_node_position(static_context* sctx)
+{
+  {
+    
+
+    DECL_WITH_KIND(sctx, fn_zorba_pos_node_position,
+        (createQName("http://www.zorba-xquery.com/modules/node-position","","node-position";), 
+        GENV_TYPESYSTEM.ANY_NODE_TYPE_ONE, 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE),
+        FunctionConsts::FN_ZORBA_POS_NODE_POSITION_1);
+
+  }
+
+
+  {
+    
+
+    DECL_WITH_KIND(sctx, fn_zorba_pos_ancestor_of,
+        (createQName("http://www.zorba-xquery.com/modules/node-position","","ancestor-of";), 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE),
+        FunctionConsts::FN_ZORBA_POS_ANCESTOR_OF_2);
+
+  }
+
+
+  {
+    
+
+    DECL_WITH_KIND(sctx, fn_zorba_pos_following_sibling_of,
+        (createQName("http://www.zorba-xquery.com/modules/node-position","","following-sibling-of";), 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE),
+        FunctionConsts::FN_ZORBA_POS_FOLLOWING_SIBLING_OF_2);
+
+  }
+
+
+  {
+    
+
+    DECL_WITH_KIND(sctx, fn_zorba_pos_following_of,
+        (createQName("http://www.zorba-xquery.com/modules/node-position","","following-of";), 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE),
+        FunctionConsts::FN_ZORBA_POS_FOLLOWING_OF_2);
+
+  }
+
+
+  {
+    
+
+    DECL_WITH_KIND(sctx, fn_zorba_pos_in_subtree_of,
+        (createQName("http://www.zorba-xquery.com/modules/node-position","","in-subtree-of";), 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE),
+        FunctionConsts::FN_ZORBA_POS_IN_SUBTREE_OF_2);
+
+  }
+
+
+  {
+    
+
+    DECL_WITH_KIND(sctx, fn_zorba_pos_descendant_of,
+        (createQName("http://www.zorba-xquery.com/modules/node-position","","descendant-of";), 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE),
+        FunctionConsts::FN_ZORBA_POS_DESCENDANT_OF_2);
+
+  }
+
+
+  {
+    
+
+    DECL_WITH_KIND(sctx, fn_zorba_pos_preceding_sibling_of,
+        (createQName("http://www.zorba-xquery.com/modules/node-position","","preceding-sibling-of";), 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE),
+        FunctionConsts::FN_ZORBA_POS_PRECEDING_SIBLING_OF_2);
+
+  }
+
+
+  {
+    
+
+    DECL_WITH_KIND(sctx, fn_zorba_pos_preceding_of,
+        (createQName("http://www.zorba-xquery.com/modules/node-position","","preceding-of";), 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE),
+        FunctionConsts::FN_ZORBA_POS_PRECEDING_OF_2);
+
+  }
+
+
+  {
+    
+
+    DECL_WITH_KIND(sctx, fn_zorba_pos_child_of,
+        (createQName("http://www.zorba-xquery.com/modules/node-position","","child-of";), 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE),
+        FunctionConsts::FN_ZORBA_POS_CHILD_OF_2);
+
+  }
+
+
+  {
+    
+
+    DECL_WITH_KIND(sctx, fn_zorba_pos_attribute_of,
+        (createQName("http://www.zorba-xquery.com/modules/node-position","","attribute-of";), 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE),
+        FunctionConsts::FN_ZORBA_POS_ATTRIBUTE_OF_2);
+
+  }
+
+
+  {
+    
+
+    DECL_WITH_KIND(sctx, fn_zorba_pos_parent_of,
+        (createQName("http://www.zorba-xquery.com/modules/node-position","","parent-of";), 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE),
+        FunctionConsts::FN_ZORBA_POS_PARENT_OF_2);
+
+  }
+
+
+  {
+    
+
+    DECL_WITH_KIND(sctx, fn_zorba_pos_preceding_in_document_order_of,
+        (createQName("http://www.zorba-xquery.com/modules/node-position","","preceding-in-document-order-of";), 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE),
+        FunctionConsts::FN_ZORBA_POS_PRECEDING_IN_DOCUMENT_ORDER_OF_2);
+
+  }
+
+
+  {
+    
+
+    DECL_WITH_KIND(sctx, fn_zorba_pos_following_in_document_order_of,
+        (createQName("http://www.zorba-xquery.com/modules/node-position","","following-in-document-order-of";), 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE),
+        FunctionConsts::FN_ZORBA_POS_FOLLOWING_IN_DOCUMENT_ORDER_OF_2);
+
+  }
+
+
+  {
+    
+
+    DECL_WITH_KIND(sctx, fn_zorba_pos_level,
+        (createQName("http://www.zorba-xquery.com/modules/node-position","","level";), 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.INTEGER_TYPE_ONE),
+        FunctionConsts::FN_ZORBA_POS_LEVEL_1);
+
+  }
+
+
+  {
+    
+
+    DECL_WITH_KIND(sctx, fn_zorba_pos_is_attribute,
+        (createQName("http://www.zorba-xquery.com/modules/node-position","","is-attribute";), 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE),
+        FunctionConsts::FN_ZORBA_POS_IS_ATTRIBUTE_1);
+
+  }
+
+
+  {
+    
+
+    DECL_WITH_KIND(sctx, fn_zorba_pos_is_comment,
+        (createQName("http://www.zorba-xquery.com/modules/node-position","","is-comment";), 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE),
+        FunctionConsts::FN_ZORBA_POS_IS_COMMENT_1);
+
+  }
+
+
+  {
+    
+
+    DECL_WITH_KIND(sctx, fn_zorba_pos_is_document,
+        (createQName("http://www.zorba-xquery.com/modules/node-position","","is-document";), 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE),
+        FunctionConsts::FN_ZORBA_POS_IS_DOCUMENT_1);
+
+  }
+
+
+  {
+    
+
+    DECL_WITH_KIND(sctx, fn_zorba_pos_is_element,
+        (createQName("http://www.zorba-xquery.com/modules/node-position","","is-element";), 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE),
+        FunctionConsts::FN_ZORBA_POS_IS_ELEMENT_1);
+
+  }
+
+
+  {
+    
+
+    DECL_WITH_KIND(sctx, fn_zorba_pos_is_processing_instruction,
+        (createQName("http://www.zorba-xquery.com/modules/node-position","","is-processing-instruction";), 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE),
+        FunctionConsts::FN_ZORBA_POS_IS_PROCESSING_INSTRUCTION_1);
+
+  }
+
+
+  {
+    
+
+    DECL_WITH_KIND(sctx, fn_zorba_pos_is_text,
+        (createQName("http://www.zorba-xquery.com/modules/node-position","","is-text";), 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE),
+        FunctionConsts::FN_ZORBA_POS_IS_TEXT_1);
+
+  }
+
+
+  {
+    
+
+    DECL_WITH_KIND(sctx, fn_zorba_pos_sibling_of,
+        (createQName("http://www.zorba-xquery.com/modules/node-position","","sibling-of";), 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE),
+        FunctionConsts::FN_ZORBA_POS_SIBLING_OF_2);
+
+  }
+
+
+  {
+    
+
+    DECL_WITH_KIND(sctx, fn_zorba_pos_in_same_tree_of,
+        (createQName("http://www.zorba-xquery.com/modules/node-position","","in-same-tree-of";), 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE),
+        FunctionConsts::FN_ZORBA_POS_IN_SAME_TREE_OF_2);
+
+  }
+
+
+  {
+    
+
+    DECL_WITH_KIND(sctx, fn_zorba_pos_in_collection,
+        (createQName("http://www.zorba-xquery.com/modules/node-position","","in-collection";), 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE),
+        FunctionConsts::FN_ZORBA_POS_IN_COLLECTION_1);
+
+  }
+
+
+  {
+    
+
+    DECL_WITH_KIND(sctx, fn_zorba_pos_in_same_collection_of,
+        (createQName("http://www.zorba-xquery.com/modules/node-position","","in-same-collection-of";), 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.ANY_URI_TYPE_ONE, 
+        GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE),
+        FunctionConsts::FN_ZORBA_POS_IN_SAME_COLLECTION_OF_2);
+
+  }
+
+}
+
+
+}
+
+
+

=== added file 'src/functions/pregenerated/func_node_position.h'
--- src/functions/pregenerated/func_node_position.h	1970-01-01 00:00:00 +0000
+++ src/functions/pregenerated/func_node_position.h	2011-10-27 20:59:25 +0000
@@ -0,0 +1,361 @@
+/*
+ * Copyright 2006-2008 The FLWOR Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+ 
+// ******************************************
+// *                                        *
+// * THIS IS A GENERATED FILE. DO NOT EDIT! *
+// * SEE .xml FILE WITH SAME NAME           *
+// *                                        *
+// ******************************************
+
+
+#ifndef ZORBA_FUNCTIONS_NODE_POSITION_H
+#define ZORBA_FUNCTIONS_NODE_POSITION_H
+
+
+#include "common/shared_types.h"
+#include "functions/function_impl.h"
+
+
+namespace zorba {
+
+
+void populate_context_node_position(static_context* sctx);
+
+
+
+
+//fn-zorba-pos:node-position
+class fn_zorba_pos_node_position : public function
+{
+public:
+  fn_zorba_pos_node_position(const signature& sig, FunctionConsts::FunctionKind kind)
+    : function(sig, kind) {
+
+}
+
+  CODEGEN_DECL();
+};
+
+
+//fn-zorba-pos:ancestor-of
+class fn_zorba_pos_ancestor_of : public function
+{
+public:
+  fn_zorba_pos_ancestor_of(const signature& sig, FunctionConsts::FunctionKind kind)
+    : function(sig, kind) {
+
+}
+
+  CODEGEN_DECL();
+};
+
+
+//fn-zorba-pos:following-sibling-of
+class fn_zorba_pos_following_sibling_of : public function
+{
+public:
+  fn_zorba_pos_following_sibling_of(const signature& sig, FunctionConsts::FunctionKind kind)
+    : function(sig, kind) {
+
+}
+
+  CODEGEN_DECL();
+};
+
+
+//fn-zorba-pos:following-of
+class fn_zorba_pos_following_of : public function
+{
+public:
+  fn_zorba_pos_following_of(const signature& sig, FunctionConsts::FunctionKind kind)
+    : function(sig, kind) {
+
+}
+
+  CODEGEN_DECL();
+};
+
+
+//fn-zorba-pos:in-subtree-of
+class fn_zorba_pos_in_subtree_of : public function
+{
+public:
+  fn_zorba_pos_in_subtree_of(const signature& sig, FunctionConsts::FunctionKind kind)
+    : function(sig, kind) {
+
+}
+
+  CODEGEN_DECL();
+};
+
+
+//fn-zorba-pos:descendant-of
+class fn_zorba_pos_descendant_of : public function
+{
+public:
+  fn_zorba_pos_descendant_of(const signature& sig, FunctionConsts::FunctionKind kind)
+    : function(sig, kind) {
+
+}
+
+  CODEGEN_DECL();
+};
+
+
+//fn-zorba-pos:preceding-sibling-of
+class fn_zorba_pos_preceding_sibling_of : public function
+{
+public:
+  fn_zorba_pos_preceding_sibling_of(const signature& sig, FunctionConsts::FunctionKind kind)
+    : function(sig, kind) {
+
+}
+
+  CODEGEN_DECL();
+};
+
+
+//fn-zorba-pos:preceding-of
+class fn_zorba_pos_preceding_of : public function
+{
+public:
+  fn_zorba_pos_preceding_of(const signature& sig, FunctionConsts::FunctionKind kind)
+    : function(sig, kind) {
+
+}
+
+  CODEGEN_DECL();
+};
+
+
+//fn-zorba-pos:child-of
+class fn_zorba_pos_child_of : public function
+{
+public:
+  fn_zorba_pos_child_of(const signature& sig, FunctionConsts::FunctionKind kind)
+    : function(sig, kind) {
+
+}
+
+  CODEGEN_DECL();
+};
+
+
+//fn-zorba-pos:attribute-of
+class fn_zorba_pos_attribute_of : public function
+{
+public:
+  fn_zorba_pos_attribute_of(const signature& sig, FunctionConsts::FunctionKind kind)
+    : function(sig, kind) {
+
+}
+
+  CODEGEN_DECL();
+};
+
+
+//fn-zorba-pos:parent-of
+class fn_zorba_pos_parent_of : public function
+{
+public:
+  fn_zorba_pos_parent_of(const signature& sig, FunctionConsts::FunctionKind kind)
+    : function(sig, kind) {
+
+}
+
+  CODEGEN_DECL();
+};
+
+
+//fn-zorba-pos:preceding-in-document-order-of
+class fn_zorba_pos_preceding_in_document_order_of : public function
+{
+public:
+  fn_zorba_pos_preceding_in_document_order_of(const signature& sig, FunctionConsts::FunctionKind kind)
+    : function(sig, kind) {
+
+}
+
+  CODEGEN_DECL();
+};
+
+
+//fn-zorba-pos:following-in-document-order-of
+class fn_zorba_pos_following_in_document_order_of : public function
+{
+public:
+  fn_zorba_pos_following_in_document_order_of(const signature& sig, FunctionConsts::FunctionKind kind)
+    : function(sig, kind) {
+
+}
+
+  CODEGEN_DECL();
+};
+
+
+//fn-zorba-pos:level
+class fn_zorba_pos_level : public function
+{
+public:
+  fn_zorba_pos_level(const signature& sig, FunctionConsts::FunctionKind kind)
+    : function(sig, kind) {
+
+}
+
+  CODEGEN_DECL();
+};
+
+
+//fn-zorba-pos:is-attribute
+class fn_zorba_pos_is_attribute : public function
+{
+public:
+  fn_zorba_pos_is_attribute(const signature& sig, FunctionConsts::FunctionKind kind)
+    : function(sig, kind) {
+
+}
+
+  CODEGEN_DECL();
+};
+
+
+//fn-zorba-pos:is-comment
+class fn_zorba_pos_is_comment : public function
+{
+public:
+  fn_zorba_pos_is_comment(const signature& sig, FunctionConsts::FunctionKind kind)
+    : function(sig, kind) {
+
+}
+
+  CODEGEN_DECL();
+};
+
+
+//fn-zorba-pos:is-document
+class fn_zorba_pos_is_document : public function
+{
+public:
+  fn_zorba_pos_is_document(const signature& sig, FunctionConsts::FunctionKind kind)
+    : function(sig, kind) {
+
+}
+
+  CODEGEN_DECL();
+};
+
+
+//fn-zorba-pos:is-element
+class fn_zorba_pos_is_element : public function
+{
+public:
+  fn_zorba_pos_is_element(const signature& sig, FunctionConsts::FunctionKind kind)
+    : function(sig, kind) {
+
+}
+
+  CODEGEN_DECL();
+};
+
+
+//fn-zorba-pos:is-processing-instruction
+class fn_zorba_pos_is_processing_instruction : public function
+{
+public:
+  fn_zorba_pos_is_processing_instruction(const signature& sig, FunctionConsts::FunctionKind kind)
+    : function(sig, kind) {
+
+}
+
+  CODEGEN_DECL();
+};
+
+
+//fn-zorba-pos:is-text
+class fn_zorba_pos_is_text : public function
+{
+public:
+  fn_zorba_pos_is_text(const signature& sig, FunctionConsts::FunctionKind kind)
+    : function(sig, kind) {
+
+}
+
+  CODEGEN_DECL();
+};
+
+
+//fn-zorba-pos:sibling-of
+class fn_zorba_pos_sibling_of : public function
+{
+public:
+  fn_zorba_pos_sibling_of(const signature& sig, FunctionConsts::FunctionKind kind)
+    : function(sig, kind) {
+
+}
+
+  CODEGEN_DECL();
+};
+
+
+//fn-zorba-pos:in-same-tree-of
+class fn_zorba_pos_in_same_tree_of : public function
+{
+public:
+  fn_zorba_pos_in_same_tree_of(const signature& sig, FunctionConsts::FunctionKind kind)
+    : function(sig, kind) {
+
+}
+
+  CODEGEN_DECL();
+};
+
+
+//fn-zorba-pos:in-collection
+class fn_zorba_pos_in_collection : public function
+{
+public:
+  fn_zorba_pos_in_collection(const signature& sig, FunctionConsts::FunctionKind kind)
+    : function(sig, kind) {
+
+}
+
+  CODEGEN_DECL();
+};
+
+
+//fn-zorba-pos:in-same-collection-of
+class fn_zorba_pos_in_same_collection_of : public function
+{
+public:
+  fn_zorba_pos_in_same_collection_of(const signature& sig, FunctionConsts::FunctionKind kind)
+    : function(sig, kind) {
+
+}
+
+  CODEGEN_DECL();
+};
+
+
+} //namespace zorba
+
+
+#endif
+/*
+ * Local variables:
+ * mode: c++
+ * End:
+ */ 

=== modified file 'src/functions/pregenerated/function_enum.h'
--- src/functions/pregenerated/function_enum.h	2011-10-19 15:28:51 +0000
+++ src/functions/pregenerated/function_enum.h	2011-10-27 20:59:25 +0000
@@ -193,6 +193,30 @@
   FN_ZORBA_MATH_IS_NAN_1,
   FN_ZORBA_MATH_MODF_1,
   FN_ZORBA_MATH_FREXP_1,
+  FN_ZORBA_POS_NODE_POSITION_1,
+  FN_ZORBA_POS_ANCESTOR_OF_2,
+  FN_ZORBA_POS_FOLLOWING_SIBLING_OF_2,
+  FN_ZORBA_POS_FOLLOWING_OF_2,
+  FN_ZORBA_POS_IN_SUBTREE_OF_2,
+  FN_ZORBA_POS_DESCENDANT_OF_2,
+  FN_ZORBA_POS_PRECEDING_SIBLING_OF_2,
+  FN_ZORBA_POS_PRECEDING_OF_2,
+  FN_ZORBA_POS_CHILD_OF_2,
+  FN_ZORBA_POS_ATTRIBUTE_OF_2,
+  FN_ZORBA_POS_PARENT_OF_2,
+  FN_ZORBA_POS_PRECEDING_IN_DOCUMENT_ORDER_OF_2,
+  FN_ZORBA_POS_FOLLOWING_IN_DOCUMENT_ORDER_OF_2,
+  FN_ZORBA_POS_LEVEL_1,
+  FN_ZORBA_POS_IS_ATTRIBUTE_1,
+  FN_ZORBA_POS_IS_COMMENT_1,
+  FN_ZORBA_POS_IS_DOCUMENT_1,
+  FN_ZORBA_POS_IS_ELEMENT_1,
+  FN_ZORBA_POS_IS_PROCESSING_INSTRUCTION_1,
+  FN_ZORBA_POS_IS_TEXT_1,
+  FN_ZORBA_POS_SIBLING_OF_2,
+  FN_ZORBA_POS_IN_SAME_TREE_OF_2,
+  FN_ZORBA_POS_IN_COLLECTION_1,
+  FN_ZORBA_POS_IN_SAME_COLLECTION_OF_2,
   FN_ZORBA_REF_NODE_REFERENCE_1,
   FN_ZORBA_REF_NODE_BY_REFERENCE_1,
   FN_LOCAL_NAME_0,

=== modified file 'src/runtime/core/flwor_iterator.cpp'
--- src/runtime/core/flwor_iterator.cpp	2011-06-28 15:07:06 +0000
+++ src/runtime/core/flwor_iterator.cpp	2011-10-27 20:59:25 +0000
@@ -18,6 +18,7 @@
 #include "zorbautils/fatal.h"
 #include "diagnostics/assert.h"
 #include "diagnostics/xquery_diagnostics.h"
+#include "diagnostics/util_macros.h"
 
 #include "context/static_context.h"
 
@@ -1474,9 +1475,9 @@
           store::Item_t temp;
           if (typedValueIter->next(temp))
           {
-            throw XQUERY_EXCEPTION(err::XPTY0004,
-                                   ERROR_PARAMS(ZED(SingletonExpected_2o),
-                                                ZED(AtomizationHasMoreThanOneValue)));
+            RAISE_ERROR(err::XPTY0004, loc,
+            ERROR_PARAMS(ZED(SingletonExpected_2o),
+                         ZED(AtomizationHasMoreThanOneValue)));
           }
         }
       }
@@ -1485,9 +1486,7 @@
       store::Item_t temp;
       if (consumeNext(temp, specIter->theInput, planState))
       {
-        throw XQUERY_EXCEPTION(
-          err::XPTY0004, ERROR_PARAMS(ZED(SingletonExpected_2o))
-        );
+        RAISE_ERROR(err::XPTY0004, loc, ERROR_PARAMS(ZED(SingletonExpected_2o)));
       }
     }
 

=== modified file 'src/runtime/core/gflwor/common.cpp'
--- src/runtime/core/gflwor/common.cpp	2011-06-14 17:26:33 +0000
+++ src/runtime/core/gflwor/common.cpp	2011-10-27 20:59:25 +0000
@@ -43,11 +43,13 @@
 GroupingSpec::GroupingSpec(
     PlanIter_t inputVar,
     const std::vector<PlanIter_t>& varRefs,
-    const std::string& collation)
+    const std::string& collation,
+    bool doFastComparison)
   :
   theInput(inputVar),
   theCollation(collation),
-  theCollator(NULL)
+  theCollator(NULL),
+  theDoFastComparison(doFastComparison)
 {
   castIterVector<ForVarIterator>(theVarRefs, varRefs);
 }
@@ -59,6 +61,7 @@
   ar & theVarRefs;
   ar & theCollation;
   ar & theCollator;
+  ar & theDoFastComparison;
 }
 
 
@@ -170,7 +173,7 @@
     const QueryLoc& loc,
     dynamic_context* dctx,
     const TypeManager* tm,
-    std::vector<GroupingSpec>* groupingSpecs) 
+    std::vector<GroupingSpec>* groupingSpecs)
   :
   theLocation(loc),
   theGroupingSpecs(groupingSpecs),
@@ -184,9 +187,9 @@
 {
   uint32_t hash = 0;
 
-  ulong numCols = (ulong)theGroupingSpecs->size();
+  csize numCols = theGroupingSpecs->size();
 
-  for (ulong i = 0; i < numCols; i++)
+  for (csize i = 0; i < numCols; i++)
   {
     if (t->theTypedValues[i] != NULL)
     {
@@ -229,19 +232,30 @@
 
       try
       {
-        if (!CompareIterator::valueEqual(theLocation,
-                                         item1,
-                                         item2,
-                                         theTypeManager,
-                                         theTimezone,
-                                         (*theGroupingSpecs)[i].theCollator))
-        {
-          return false;                                 
+        if ((*theGroupingSpecs)[i].theDoFastComparison)
+        {
+          if (!item1->equals(item2, theTimezone, (*theGroupingSpecs)[i].theCollator))
+          {
+            return false;
+          }
+        }
+        else
+        {
+          if (!CompareIterator::valueEqual(theLocation,
+                                           item1,
+                                           item2,
+                                           theTypeManager,
+                                           theTimezone,
+                                           (*theGroupingSpecs)[i].theCollator))
+          {
+            return false;                                 
+          }
         }
       }
       catch (ZorbaException const& e)
       {
-        if (e.diagnostic() == err::XPTY0004)
+        if (e.diagnostic() == err::XPTY0004 ||
+            e.diagnostic() == zerr::ZSTR0040_TYPE_ERROR)
           return false;
         else
           throw;

=== modified file 'src/runtime/core/gflwor/common.h'
--- src/runtime/core/gflwor/common.h	2011-06-14 17:26:33 +0000
+++ src/runtime/core/gflwor/common.h	2011-10-27 20:59:25 +0000
@@ -107,6 +107,7 @@
   std::vector<ForVarIter_t> theVarRefs;
   std::string               theCollation;
   XQPCollator             * theCollator;
+  bool                      theDoFastComparison;
 
 public:
   SERIALIZABLE_CLASS(GroupingSpec)
@@ -119,7 +120,8 @@
   GroupingSpec(
         PlanIter_t inputVar,
         const std::vector<PlanIter_t>& varRefs,
-        const std::string& aCollation);
+        const std::string& aCollation,
+        bool doFastComparison);
 
   virtual ~GroupingSpec() {}
 

=== modified file 'src/runtime/core/gflwor/groupby_iterator.cpp'
--- src/runtime/core/gflwor/groupby_iterator.cpp	2011-06-14 17:26:33 +0000
+++ src/runtime/core/gflwor/groupby_iterator.cpp	2011-10-27 20:59:25 +0000
@@ -18,6 +18,7 @@
 #include "zorbautils/fatal.h"
 #include "diagnostics/assert.h"
 #include "diagnostics/xquery_diagnostics.h"
+#include "diagnostics/util_macros.h"
 
 #include "context/static_context.h"
 
@@ -358,10 +359,10 @@
   std::vector<store::Item_t>& groupTupleItems = groupTuple->theItems;
   std::vector<store::Item_t>& groupTupleValues = groupTuple->theTypedValues;
 
-  ulong numVars = (ulong)theGroupingSpecs.size();
+  csize numVars = theGroupingSpecs.size();
 
   // For each grouping variable
-  for (ulong i = 0; i < numVars; ++i)
+  for (csize i = 0; i < numVars; ++i)
   {
     groupTupleItems.push_back(NULL);
     groupTupleValues.push_back(NULL);
@@ -379,11 +380,8 @@
       // than 1 item.
       if (consumeNext(temp, theGroupingSpecs[i].theInput.getp(), aPlanState)) 
       {
-        throw XQUERY_EXCEPTION(
-          err::XPTY0004,
-          ERROR_PARAMS( ZED( GroupByVarHasMoreThanOneItem_2 ) ),
-          ERROR_LOC( loc )
-        );
+        RAISE_ERROR(err::XPTY0004, loc,
+        ERROR_PARAMS(ZED(GroupByVarHasMoreThanOneItem_2)));
       }
 
       store::Iterator_t typedValueIter;
@@ -405,11 +403,8 @@
             
             if (typedValueIter->next(temp))
             {
-              throw XQUERY_EXCEPTION(
-                err::XPTY0004,
-                ERROR_PARAMS( ZED( AtomizationOfGroupByMakesMoreThanOneItem ) ),
-                ERROR_LOC( loc )
-              );
+              RAISE_ERROR(err::XPTY0004, loc,
+              ERROR_PARAMS(ZED(AtomizationOfGroupByMakesMoreThanOneItem)));
             }
           }
         }

=== modified file 'src/runtime/indexing/index_ddl.cpp'
--- src/runtime/indexing/index_ddl.cpp	2011-10-05 17:49:48 +0000
+++ src/runtime/indexing/index_ddl.cpp	2011-10-27 20:59:25 +0000
@@ -634,7 +634,12 @@
       if (state->theIndexDecl->getKeyExpressions().size() != numChildren-1)
       {
         RAISE_ERROR(zerr::ZDDY0025_INDEX_WRONG_NUMBER_OF_PROBE_ARGS, loc,
-        ERROR_PARAMS(qnameItem->getStringValue()));
+        ERROR_PARAMS(
+          qnameItem->getStringValue(),
+          "index",
+          numChildren-1,
+          state->theIndexDecl->getKeyExpressions().size())
+        );
       }
 
       state->theIndex = (state->theIndexDecl->isTemp() ?
@@ -800,7 +805,12 @@
           numChildren != 2)
       {
         RAISE_ERROR(zerr::ZDDY0025_INDEX_WRONG_NUMBER_OF_PROBE_ARGS, loc,
-        ERROR_PARAMS(qnameItem->getStringValue()));
+        ERROR_PARAMS(
+          qnameItem->getStringValue(),
+          "index",
+          numChildren-1,
+          state->theIndexDecl->getKeyExpressions().size())
+        );
       }
 
       state->theIndex = (state->theIndexDecl->isTemp() ?
@@ -973,13 +983,23 @@
     if ((numChildren-1) % 6 != 0)
     {
       RAISE_ERROR(zerr::ZDDY0025_INDEX_WRONG_NUMBER_OF_PROBE_ARGS, loc,
-      ERROR_PARAMS(qname->getStringValue()));
+      ERROR_PARAMS(
+        qname->getStringValue(),
+        "index",
+        numChildren-1,
+        "multiple of 6"
+      ));
     }
 
     if (indexDecl->getKeyExpressions().size() * 6 > numChildren-1)
     {
       RAISE_ERROR(zerr::ZDDY0025_INDEX_WRONG_NUMBER_OF_PROBE_ARGS, loc,
-      ERROR_PARAMS(qname->getStringValue()));
+      ERROR_PARAMS(
+        qname->getStringValue(),
+        "index",
+        numChildren-1,
+        indexDecl->getKeyExpressions().size() * 6
+      ));
     }
 
     state->theIndex = (indexDecl->isTemp() ?

=== added file 'src/runtime/nodes/node_position_impl.cpp'
--- src/runtime/nodes/node_position_impl.cpp	1970-01-01 00:00:00 +0000
+++ src/runtime/nodes/node_position_impl.cpp	2011-10-27 20:59:25 +0000
@@ -0,0 +1,756 @@
+/*
+ * Copyright 2006-2008 The FLWOR Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include "stdafx.h"
+
+#include "runtime/nodes/node_position.h"
+#include "zorbamisc/ns_consts.h"
+
+#include "system/globalenv.h"
+
+#include "store/api/item.h"
+#include "store/api/iterator.h"
+#include "store/api/item_factory.h"
+#include "store/api/store.h"
+#include "store/naive/atomic_items.h"
+#include "store/naive/ordpath.h"
+
+#include "util/string_util.h"
+#include "util/uri_util.h"
+#include "zorbautils/string_util.h"
+
+using namespace std;
+
+namespace zorba {
+
+/*******************************************************************************
+
+********************************************************************************/
+bool NodePositionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
+{
+  bool valid;
+  store::Item_t inNode;
+
+  PlanIteratorState* state;
+  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
+
+  valid = consumeNext(inNode, theChildren[0], planState);
+  assert(valid);
+
+  STACK_PUSH(GENV_STORE.getStructuralInformation(result, inNode), state);
+  STACK_END(state);
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+bool
+IsAncestorPositionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
+{
+  store::Item_t lUriA;
+  store::Item_t lUriB;
+
+  PlanIteratorState* state;
+  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
+
+  consumeNext(lUriA, theChildren[0].getp(), planState);
+  consumeNext(lUriB, theChildren[1].getp(), planState);
+
+  try
+  {
+    GENV_ITEMFACTORY->createBoolean(result, lUriA->isAncestor(lUriB));
+  }
+  catch (ZorbaException& e)
+  {
+    set_source(e, loc);
+    throw;
+  }
+
+  STACK_PUSH(true,state);
+
+  STACK_END (state);
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+bool
+IsFollowingSiblingPositionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
+{
+  store::Item_t lUriA;
+  store::Item_t lUriB;
+
+  PlanIteratorState* state;
+  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
+
+  consumeNext(lUriA, theChildren[0].getp(), planState);
+  consumeNext(lUriB, theChildren[1].getp(), planState);
+
+  try
+  {
+    GENV_ITEMFACTORY->createBoolean(result, lUriA->isFollowingSibling(lUriB));
+  }
+  catch (ZorbaException& e)
+  {
+    set_source(e, loc);
+    throw;
+  }
+
+  STACK_PUSH(true,state);
+
+  STACK_END (state);
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+bool
+IsFollowingPositionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
+{
+  store::Item_t lUriA;
+  store::Item_t lUriB;
+
+  PlanIteratorState* state;
+  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
+
+  consumeNext(lUriA, theChildren[0].getp(), planState);
+  consumeNext(lUriB, theChildren[1].getp(), planState);
+
+  try
+  {
+    GENV_ITEMFACTORY->createBoolean(result, lUriA->isFollowing(lUriB));
+  }
+  catch (ZorbaException& e)
+  {
+    set_source(e, loc);
+    throw;
+  }
+
+  STACK_PUSH(true,state);
+
+  STACK_END (state);
+}
+
+
+/*******************************************************************************
+ 
+********************************************************************************/
+bool
+IsInSubtreeOfPositionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
+{
+  store::Item_t lUriA;
+  store::Item_t lUriB;
+
+  PlanIteratorState *state;
+  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
+
+  consumeNext(lUriA, theChildren[0].getp(), planState);
+  consumeNext(lUriB, theChildren[1].getp(), planState);
+
+  try
+  {
+    GENV_ITEMFACTORY->createBoolean(result, lUriA->isInSubtreeOf(lUriB));
+  }
+  catch (ZorbaException& e)
+  {
+    set_source(e, loc);
+    throw;
+  }
+
+  STACK_PUSH(true,state);
+
+  STACK_END (state);
+}
+
+
+/*******************************************************************************
+ 
+********************************************************************************/
+bool
+IsDescendantPositionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
+{
+  store::Item_t lUriA;
+  store::Item_t lUriB;
+
+  PlanIteratorState *state;
+  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
+
+  consumeNext(lUriA, theChildren[0].getp(), planState);
+  consumeNext(lUriB, theChildren[1].getp(), planState);
+
+  try
+  {
+    GENV_ITEMFACTORY->createBoolean(result, lUriA->isDescendant(lUriB));
+  }
+  catch (ZorbaException& e)
+  {
+    set_source(e, loc);
+    throw;
+  }
+
+  STACK_PUSH(true,state);
+
+  STACK_END (state);
+}
+
+
+/*******************************************************************************
+ 
+********************************************************************************/
+bool
+IsPrecedingSiblingPositionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
+{
+  store::Item_t lUriA;
+  store::Item_t lUriB;
+
+  PlanIteratorState *state;
+  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
+
+  consumeNext(lUriA, theChildren[0].getp(), planState);
+  consumeNext(lUriB, theChildren[1].getp(), planState);
+
+  try
+  {
+    GENV_ITEMFACTORY->createBoolean(result, lUriA->isPrecedingSibling(lUriB));
+
+  }
+  catch (ZorbaException& e)
+  {
+    set_source(e, loc);
+    throw;
+  }
+
+  STACK_PUSH(true,state);
+
+  STACK_END (state);
+}
+
+
+/*******************************************************************************
+ 
+********************************************************************************/
+bool
+IsPrecedingPositionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
+{
+  store::Item_t lUriA;
+  store::Item_t lUriB;
+
+  PlanIteratorState *state;
+  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
+
+  consumeNext(lUriA, theChildren[0].getp(), planState);
+  consumeNext(lUriB, theChildren[1].getp(), planState);
+
+  try
+  {
+    GENV_ITEMFACTORY->createBoolean(result, lUriA->isPreceding(lUriB));
+  }
+  catch (ZorbaException& e)
+  {
+    set_source(e, loc);
+    throw;
+  }
+
+  STACK_PUSH(true,state);
+
+  STACK_END (state);
+}
+
+
+/*******************************************************************************
+ 
+********************************************************************************/
+bool
+IsChildPositionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
+{
+  store::Item_t lUriA;
+  store::Item_t lUriB;
+
+  PlanIteratorState *state;
+  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
+
+  consumeNext(lUriA, theChildren[0].getp(), planState);
+  consumeNext(lUriB, theChildren[1].getp(), planState);
+
+  try
+  {
+    GENV_ITEMFACTORY->createBoolean(result, lUriA->isChild(lUriB));
+  }
+  catch (ZorbaException& e)
+  {
+    set_source(e, loc);
+    throw;
+  }
+
+  STACK_PUSH(true,state);
+
+  STACK_END (state);
+}
+
+
+/*******************************************************************************
+ 
+********************************************************************************/
+bool
+IsAttributeOfPositionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
+{
+  store::Item_t lUriA;
+  store::Item_t lUriB;
+
+  PlanIteratorState *state;
+  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
+
+  consumeNext(lUriA, theChildren[0].getp(), planState);
+  consumeNext(lUriB, theChildren[1].getp(), planState);
+
+  try
+  {
+    GENV_ITEMFACTORY->createBoolean(result, lUriA->isAttribute(lUriB));
+  }
+  catch (ZorbaException& e)
+  {
+    set_source(e, loc);
+    throw;
+  }
+
+  STACK_PUSH(true,state);
+
+  STACK_END (state);
+}
+
+
+/*******************************************************************************
+ 
+********************************************************************************/
+bool
+IsParentPositionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
+{
+  store::Item_t lUriA;
+  store::Item_t lUriB;
+
+  PlanIteratorState *state;
+  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
+
+  consumeNext(lUriA, theChildren[0].getp(), planState);
+  consumeNext(lUriB, theChildren[1].getp(), planState);
+
+  try
+  {
+    GENV_ITEMFACTORY->createBoolean(result, lUriA->isParent(lUriB));
+  }
+  catch (ZorbaException& e)
+  {
+    set_source(e, loc);
+    throw;
+  }
+
+  STACK_PUSH(true,state);
+
+  STACK_END (state);
+}
+
+
+/*******************************************************************************
+ 
+********************************************************************************/
+bool
+IsPrecedingInDocumentOrderPositionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
+{
+  store::Item_t lUriA;
+  store::Item_t lUriB;
+
+  PlanIteratorState *state;
+  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
+
+  consumeNext(lUriA, theChildren[0].getp(), planState);
+  consumeNext(lUriB, theChildren[1].getp(), planState);
+
+  try
+  {
+    GENV_ITEMFACTORY->createBoolean(result, lUriA->isPrecedingInDocumentOrder(lUriB));
+  }
+  catch (ZorbaException& e)
+  {
+    set_source(e, loc);
+    throw;
+  }
+
+  STACK_PUSH(true,state);
+
+  STACK_END (state);
+}
+
+
+/*******************************************************************************
+ 
+********************************************************************************/
+bool
+IsFollowingInDocumentOrderPositionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
+{
+  store::Item_t lUriA;
+  store::Item_t lUriB;
+
+  PlanIteratorState *state;
+  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
+
+  consumeNext(lUriA, theChildren[0].getp(), planState);
+  consumeNext(lUriB, theChildren[1].getp(), planState);
+
+  try
+  {
+    GENV_ITEMFACTORY->createBoolean(result, lUriA->isFollowingInDocumentOrder(lUriB));
+  }
+  catch (ZorbaException& e)
+  {
+    set_source(e, loc);
+    throw;
+  }
+
+  STACK_PUSH(true,state);
+
+  STACK_END (state);
+}
+
+
+/*******************************************************************************
+ 
+********************************************************************************/
+bool
+LevelPositionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
+{
+  store::Item_t lUri;
+
+  PlanIteratorState *state;
+  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
+
+  consumeNext(lUri, theChildren[0].getp(), planState);
+
+  try
+  {
+    result = lUri->getLevel();
+  }
+  catch (ZorbaException& e)
+  {
+    set_source(e, loc);
+    throw;
+  }
+
+  STACK_PUSH(true, state);
+
+  STACK_END (state);
+}
+
+
+/*******************************************************************************
+ 
+********************************************************************************/
+bool
+IsAttributePositionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
+{
+  store::Item_t lUri;
+
+  PlanIteratorState *state;
+  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
+
+  consumeNext(lUri, theChildren[0].getp(), planState);
+
+  try
+  {
+    GENV_ITEMFACTORY->createBoolean(result, lUri->isAttribute());
+  }
+  catch (ZorbaException& e)
+  {
+    set_source(e, loc);
+    throw;
+  }
+
+  STACK_PUSH(true,state);
+
+  STACK_END (state);
+}
+
+
+/*******************************************************************************
+ 
+********************************************************************************/
+bool
+IsCommentPositionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
+{
+  store::Item_t lUri;
+
+  PlanIteratorState *state;
+  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
+
+  consumeNext(lUri, theChildren[0].getp(), planState);
+
+  try
+  {
+    GENV_ITEMFACTORY->createBoolean(result, lUri->isComment());
+  }
+  catch (ZorbaException& e)
+  {
+    set_source(e, loc);
+    throw;
+  }
+
+  STACK_PUSH(true,state);
+
+  STACK_END (state);
+}
+
+
+/*******************************************************************************
+ 
+********************************************************************************/
+bool
+IsDocumentPositionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
+{
+  store::Item_t lUri;
+
+  PlanIteratorState *state;
+  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
+
+  consumeNext(lUri, theChildren[0].getp(), planState);
+
+  try
+  {
+    GENV_ITEMFACTORY->createBoolean(result, lUri->isDocument());
+  }
+  catch (ZorbaException& e)
+  {
+    set_source(e, loc);
+    throw;
+  }
+
+  STACK_PUSH(true,state);
+
+  STACK_END (state);
+}
+
+
+/*******************************************************************************
+ 
+********************************************************************************/
+bool
+IsElementPositionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
+{
+  store::Item_t lUri;
+
+  PlanIteratorState *state;
+  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
+
+  consumeNext(lUri, theChildren[0].getp(), planState);
+
+  try
+  {
+    GENV_ITEMFACTORY->createBoolean(result, lUri->isElement());
+  }
+  catch (ZorbaException& e)
+  {
+    set_source(e, loc);
+    throw;
+  }
+
+  STACK_PUSH(true,state);
+
+  STACK_END (state);
+}
+
+
+/*******************************************************************************
+ 
+********************************************************************************/
+bool
+IsProcessingInstructionPositionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
+{
+  store::Item_t lUri;
+
+  PlanIteratorState *state;
+  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
+
+  consumeNext(lUri, theChildren[0].getp(), planState);
+
+  try
+  {
+    GENV_ITEMFACTORY->createBoolean(result, lUri->isProcessingInstruction());
+  }
+  catch (ZorbaException& e)
+  {
+    set_source(e, loc);
+    throw;
+  }
+
+  STACK_PUSH(true,state);
+
+  STACK_END (state);
+}
+
+
+/*******************************************************************************
+ 
+********************************************************************************/
+bool
+IsTextPositionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
+{
+  store::Item_t lUri;
+
+  PlanIteratorState *state;
+  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
+
+  consumeNext(lUri, theChildren[0].getp(), planState);
+
+  try
+  {
+    GENV_ITEMFACTORY->createBoolean(result, lUri->isText());
+  }
+  catch (ZorbaException& e)
+  {
+    set_source(e, loc);
+    throw;
+  }
+
+  STACK_PUSH(true,state);
+
+  STACK_END (state);
+}
+
+
+/*******************************************************************************
+ 
+********************************************************************************/
+bool
+IsSiblingPositionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
+{
+  store::Item_t lUriA;
+  store::Item_t lUriB;
+
+  PlanIteratorState *state;
+  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
+
+  consumeNext(lUriA, theChildren[0].getp(), planState);
+  consumeNext(lUriB, theChildren[1].getp(), planState);
+
+  try
+  {
+    GENV_ITEMFACTORY->createBoolean(result, lUriA->isSibling(lUriB));
+  }
+  catch (ZorbaException& e)
+  {
+    set_source(e, loc);
+    throw;
+  }
+
+  STACK_PUSH(true,state);
+
+  STACK_END (state);
+}
+
+
+/*******************************************************************************
+ 
+********************************************************************************/
+bool
+InSameTreePositionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
+{
+  store::Item_t lUriA;
+  store::Item_t lUriB;
+
+  PlanIteratorState *state;
+  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
+
+  consumeNext(lUriA, theChildren[0].getp(), planState);
+  consumeNext(lUriB, theChildren[1].getp(), planState);
+
+  try
+  {
+    GENV_ITEMFACTORY->createBoolean(result, lUriA->inSameTree(lUriB));
+  }
+  catch (ZorbaException& e)
+  {
+    set_source(e, loc);
+    throw;
+  }
+
+  STACK_PUSH(true,state);
+
+  STACK_END (state);
+}
+
+
+/*******************************************************************************
+ 
+********************************************************************************/
+bool
+InCollectionPositionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
+{
+  store::Item_t lUri;
+
+  PlanIteratorState *state;
+  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
+
+  consumeNext(lUri, theChildren[0].getp(), planState);
+
+  try
+  {
+    GENV_ITEMFACTORY->createBoolean(result, lUri->inCollection());
+  }
+  catch (ZorbaException& e)
+  {
+    set_source(e, loc);
+    throw;
+  }
+
+  STACK_PUSH(true,state);
+
+  STACK_END (state);
+}
+
+
+/*******************************************************************************
+ 
+********************************************************************************/
+bool
+InSameCollectionPositionIterator::nextImpl(store::Item_t& result, PlanState& planState) const
+{
+  store::Item_t lUriA;
+  store::Item_t lUriB;
+
+  PlanIteratorState *state;
+  DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
+
+  consumeNext(lUriA, theChildren[0].getp(), planState);
+  consumeNext(lUriB, theChildren[1].getp(), planState);
+
+  try
+  {
+    GENV_ITEMFACTORY->createBoolean(result, lUriA->inSameCollection(lUriB));
+  }
+  catch (ZorbaException& e)
+  {
+    set_source(e, loc);
+    throw;
+  }
+
+  STACK_PUSH(true,state);
+
+  STACK_END (state);
+}
+
+} // namespace zorba
+/* vim:set et sw=2 ts=2: */
+

=== added file 'src/runtime/nodes/pregenerated/node_position.cpp'
--- src/runtime/nodes/pregenerated/node_position.cpp	1970-01-01 00:00:00 +0000
+++ src/runtime/nodes/pregenerated/node_position.cpp	2011-10-27 20:59:25 +0000
@@ -0,0 +1,710 @@
+/*
+ * Copyright 2006-2008 The FLWOR Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+ 
+// ******************************************
+// *                                        *
+// * THIS IS A GENERATED FILE. DO NOT EDIT! *
+// * SEE .xml FILE WITH SAME NAME           *
+// *                                        *
+// ******************************************
+
+#include "stdafx.h"
+#include "zorbatypes/rchandle.h"
+#include "zorbatypes/zstring.h"
+#include "runtime/visitors/planiter_visitor.h"
+#include "runtime/nodes/node_position.h"
+#include "system/globalenv.h"
+
+
+
+namespace zorba {
+
+// <NodePositionIterator>
+const char* NodePositionIterator::class_name_str = "NodePositionIterator";
+NodePositionIterator::class_factory<NodePositionIterator>
+NodePositionIterator::g_class_factory;
+
+const serialization::ClassVersion 
+NodePositionIterator::class_versions[] ={{ 1, 0x000905, false}};
+
+const int NodePositionIterator::class_versions_count =
+sizeof(NodePositionIterator::class_versions)/sizeof(struct serialization::ClassVersion);
+
+void NodePositionIterator::accept(PlanIterVisitor& v) const {
+  v.beginVisit(*this);
+
+  std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin();
+  std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
+  for ( ; lIter != lEnd; ++lIter ){
+    (*lIter)->accept(v);
+  }
+
+  v.endVisit(*this);
+}
+
+NodePositionIterator::~NodePositionIterator() {}
+
+// </NodePositionIterator>
+
+
+// <IsAncestorPositionIterator>
+const char* IsAncestorPositionIterator::class_name_str = "IsAncestorPositionIterator";
+IsAncestorPositionIterator::class_factory<IsAncestorPositionIterator>
+IsAncestorPositionIterator::g_class_factory;
+
+const serialization::ClassVersion 
+IsAncestorPositionIterator::class_versions[] ={{ 1, 0x000905, false}};
+
+const int IsAncestorPositionIterator::class_versions_count =
+sizeof(IsAncestorPositionIterator::class_versions)/sizeof(struct serialization::ClassVersion);
+
+void IsAncestorPositionIterator::accept(PlanIterVisitor& v) const {
+  v.beginVisit(*this);
+
+  std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin();
+  std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
+  for ( ; lIter != lEnd; ++lIter ){
+    (*lIter)->accept(v);
+  }
+
+  v.endVisit(*this);
+}
+
+IsAncestorPositionIterator::~IsAncestorPositionIterator() {}
+
+// </IsAncestorPositionIterator>
+
+
+// <IsFollowingSiblingPositionIterator>
+const char* IsFollowingSiblingPositionIterator::class_name_str = "IsFollowingSiblingPositionIterator";
+IsFollowingSiblingPositionIterator::class_factory<IsFollowingSiblingPositionIterator>
+IsFollowingSiblingPositionIterator::g_class_factory;
+
+const serialization::ClassVersion 
+IsFollowingSiblingPositionIterator::class_versions[] ={{ 1, 0x000905, false}};
+
+const int IsFollowingSiblingPositionIterator::class_versions_count =
+sizeof(IsFollowingSiblingPositionIterator::class_versions)/sizeof(struct serialization::ClassVersion);
+
+void IsFollowingSiblingPositionIterator::accept(PlanIterVisitor& v) const {
+  v.beginVisit(*this);
+
+  std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin();
+  std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
+  for ( ; lIter != lEnd; ++lIter ){
+    (*lIter)->accept(v);
+  }
+
+  v.endVisit(*this);
+}
+
+IsFollowingSiblingPositionIterator::~IsFollowingSiblingPositionIterator() {}
+
+// </IsFollowingSiblingPositionIterator>
+
+
+// <IsFollowingPositionIterator>
+const char* IsFollowingPositionIterator::class_name_str = "IsFollowingPositionIterator";
+IsFollowingPositionIterator::class_factory<IsFollowingPositionIterator>
+IsFollowingPositionIterator::g_class_factory;
+
+const serialization::ClassVersion 
+IsFollowingPositionIterator::class_versions[] ={{ 1, 0x000905, false}};
+
+const int IsFollowingPositionIterator::class_versions_count =
+sizeof(IsFollowingPositionIterator::class_versions)/sizeof(struct serialization::ClassVersion);
+
+void IsFollowingPositionIterator::accept(PlanIterVisitor& v) const {
+  v.beginVisit(*this);
+
+  std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin();
+  std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
+  for ( ; lIter != lEnd; ++lIter ){
+    (*lIter)->accept(v);
+  }
+
+  v.endVisit(*this);
+}
+
+IsFollowingPositionIterator::~IsFollowingPositionIterator() {}
+
+// </IsFollowingPositionIterator>
+
+
+// <IsInSubtreeOfPositionIterator>
+const char* IsInSubtreeOfPositionIterator::class_name_str = "IsInSubtreeOfPositionIterator";
+IsInSubtreeOfPositionIterator::class_factory<IsInSubtreeOfPositionIterator>
+IsInSubtreeOfPositionIterator::g_class_factory;
+
+const serialization::ClassVersion 
+IsInSubtreeOfPositionIterator::class_versions[] ={{ 1, 0x000905, false}};
+
+const int IsInSubtreeOfPositionIterator::class_versions_count =
+sizeof(IsInSubtreeOfPositionIterator::class_versions)/sizeof(struct serialization::ClassVersion);
+
+void IsInSubtreeOfPositionIterator::accept(PlanIterVisitor& v) const {
+  v.beginVisit(*this);
+
+  std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin();
+  std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
+  for ( ; lIter != lEnd; ++lIter ){
+    (*lIter)->accept(v);
+  }
+
+  v.endVisit(*this);
+}
+
+IsInSubtreeOfPositionIterator::~IsInSubtreeOfPositionIterator() {}
+
+// </IsInSubtreeOfPositionIterator>
+
+
+// <IsDescendantPositionIterator>
+const char* IsDescendantPositionIterator::class_name_str = "IsDescendantPositionIterator";
+IsDescendantPositionIterator::class_factory<IsDescendantPositionIterator>
+IsDescendantPositionIterator::g_class_factory;
+
+const serialization::ClassVersion 
+IsDescendantPositionIterator::class_versions[] ={{ 1, 0x000905, false}};
+
+const int IsDescendantPositionIterator::class_versions_count =
+sizeof(IsDescendantPositionIterator::class_versions)/sizeof(struct serialization::ClassVersion);
+
+void IsDescendantPositionIterator::accept(PlanIterVisitor& v) const {
+  v.beginVisit(*this);
+
+  std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin();
+  std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
+  for ( ; lIter != lEnd; ++lIter ){
+    (*lIter)->accept(v);
+  }
+
+  v.endVisit(*this);
+}
+
+IsDescendantPositionIterator::~IsDescendantPositionIterator() {}
+
+// </IsDescendantPositionIterator>
+
+
+// <IsPrecedingSiblingPositionIterator>
+const char* IsPrecedingSiblingPositionIterator::class_name_str = "IsPrecedingSiblingPositionIterator";
+IsPrecedingSiblingPositionIterator::class_factory<IsPrecedingSiblingPositionIterator>
+IsPrecedingSiblingPositionIterator::g_class_factory;
+
+const serialization::ClassVersion 
+IsPrecedingSiblingPositionIterator::class_versions[] ={{ 1, 0x000905, false}};
+
+const int IsPrecedingSiblingPositionIterator::class_versions_count =
+sizeof(IsPrecedingSiblingPositionIterator::class_versions)/sizeof(struct serialization::ClassVersion);
+
+void IsPrecedingSiblingPositionIterator::accept(PlanIterVisitor& v) const {
+  v.beginVisit(*this);
+
+  std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin();
+  std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
+  for ( ; lIter != lEnd; ++lIter ){
+    (*lIter)->accept(v);
+  }
+
+  v.endVisit(*this);
+}
+
+IsPrecedingSiblingPositionIterator::~IsPrecedingSiblingPositionIterator() {}
+
+// </IsPrecedingSiblingPositionIterator>
+
+
+// <IsPrecedingPositionIterator>
+const char* IsPrecedingPositionIterator::class_name_str = "IsPrecedingPositionIterator";
+IsPrecedingPositionIterator::class_factory<IsPrecedingPositionIterator>
+IsPrecedingPositionIterator::g_class_factory;
+
+const serialization::ClassVersion 
+IsPrecedingPositionIterator::class_versions[] ={{ 1, 0x000905, false}};
+
+const int IsPrecedingPositionIterator::class_versions_count =
+sizeof(IsPrecedingPositionIterator::class_versions)/sizeof(struct serialization::ClassVersion);
+
+void IsPrecedingPositionIterator::accept(PlanIterVisitor& v) const {
+  v.beginVisit(*this);
+
+  std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin();
+  std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
+  for ( ; lIter != lEnd; ++lIter ){
+    (*lIter)->accept(v);
+  }
+
+  v.endVisit(*this);
+}
+
+IsPrecedingPositionIterator::~IsPrecedingPositionIterator() {}
+
+// </IsPrecedingPositionIterator>
+
+
+// <IsChildPositionIterator>
+const char* IsChildPositionIterator::class_name_str = "IsChildPositionIterator";
+IsChildPositionIterator::class_factory<IsChildPositionIterator>
+IsChildPositionIterator::g_class_factory;
+
+const serialization::ClassVersion 
+IsChildPositionIterator::class_versions[] ={{ 1, 0x000905, false}};
+
+const int IsChildPositionIterator::class_versions_count =
+sizeof(IsChildPositionIterator::class_versions)/sizeof(struct serialization::ClassVersion);
+
+void IsChildPositionIterator::accept(PlanIterVisitor& v) const {
+  v.beginVisit(*this);
+
+  std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin();
+  std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
+  for ( ; lIter != lEnd; ++lIter ){
+    (*lIter)->accept(v);
+  }
+
+  v.endVisit(*this);
+}
+
+IsChildPositionIterator::~IsChildPositionIterator() {}
+
+// </IsChildPositionIterator>
+
+
+// <IsAttributeOfPositionIterator>
+const char* IsAttributeOfPositionIterator::class_name_str = "IsAttributeOfPositionIterator";
+IsAttributeOfPositionIterator::class_factory<IsAttributeOfPositionIterator>
+IsAttributeOfPositionIterator::g_class_factory;
+
+const serialization::ClassVersion 
+IsAttributeOfPositionIterator::class_versions[] ={{ 1, 0x000905, false}};
+
+const int IsAttributeOfPositionIterator::class_versions_count =
+sizeof(IsAttributeOfPositionIterator::class_versions)/sizeof(struct serialization::ClassVersion);
+
+void IsAttributeOfPositionIterator::accept(PlanIterVisitor& v) const {
+  v.beginVisit(*this);
+
+  std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin();
+  std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
+  for ( ; lIter != lEnd; ++lIter ){
+    (*lIter)->accept(v);
+  }
+
+  v.endVisit(*this);
+}
+
+IsAttributeOfPositionIterator::~IsAttributeOfPositionIterator() {}
+
+// </IsAttributeOfPositionIterator>
+
+
+// <IsParentPositionIterator>
+const char* IsParentPositionIterator::class_name_str = "IsParentPositionIterator";
+IsParentPositionIterator::class_factory<IsParentPositionIterator>
+IsParentPositionIterator::g_class_factory;
+
+const serialization::ClassVersion 
+IsParentPositionIterator::class_versions[] ={{ 1, 0x000905, false}};
+
+const int IsParentPositionIterator::class_versions_count =
+sizeof(IsParentPositionIterator::class_versions)/sizeof(struct serialization::ClassVersion);
+
+void IsParentPositionIterator::accept(PlanIterVisitor& v) const {
+  v.beginVisit(*this);
+
+  std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin();
+  std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
+  for ( ; lIter != lEnd; ++lIter ){
+    (*lIter)->accept(v);
+  }
+
+  v.endVisit(*this);
+}
+
+IsParentPositionIterator::~IsParentPositionIterator() {}
+
+// </IsParentPositionIterator>
+
+
+// <IsPrecedingInDocumentOrderPositionIterator>
+const char* IsPrecedingInDocumentOrderPositionIterator::class_name_str = "IsPrecedingInDocumentOrderPositionIterator";
+IsPrecedingInDocumentOrderPositionIterator::class_factory<IsPrecedingInDocumentOrderPositionIterator>
+IsPrecedingInDocumentOrderPositionIterator::g_class_factory;
+
+const serialization::ClassVersion 
+IsPrecedingInDocumentOrderPositionIterator::class_versions[] ={{ 1, 0x000905, false}};
+
+const int IsPrecedingInDocumentOrderPositionIterator::class_versions_count =
+sizeof(IsPrecedingInDocumentOrderPositionIterator::class_versions)/sizeof(struct serialization::ClassVersion);
+
+void IsPrecedingInDocumentOrderPositionIterator::accept(PlanIterVisitor& v) const {
+  v.beginVisit(*this);
+
+  std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin();
+  std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
+  for ( ; lIter != lEnd; ++lIter ){
+    (*lIter)->accept(v);
+  }
+
+  v.endVisit(*this);
+}
+
+IsPrecedingInDocumentOrderPositionIterator::~IsPrecedingInDocumentOrderPositionIterator() {}
+
+// </IsPrecedingInDocumentOrderPositionIterator>
+
+
+// <IsFollowingInDocumentOrderPositionIterator>
+const char* IsFollowingInDocumentOrderPositionIterator::class_name_str = "IsFollowingInDocumentOrderPositionIterator";
+IsFollowingInDocumentOrderPositionIterator::class_factory<IsFollowingInDocumentOrderPositionIterator>
+IsFollowingInDocumentOrderPositionIterator::g_class_factory;
+
+const serialization::ClassVersion 
+IsFollowingInDocumentOrderPositionIterator::class_versions[] ={{ 1, 0x000905, false}};
+
+const int IsFollowingInDocumentOrderPositionIterator::class_versions_count =
+sizeof(IsFollowingInDocumentOrderPositionIterator::class_versions)/sizeof(struct serialization::ClassVersion);
+
+void IsFollowingInDocumentOrderPositionIterator::accept(PlanIterVisitor& v) const {
+  v.beginVisit(*this);
+
+  std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin();
+  std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
+  for ( ; lIter != lEnd; ++lIter ){
+    (*lIter)->accept(v);
+  }
+
+  v.endVisit(*this);
+}
+
+IsFollowingInDocumentOrderPositionIterator::~IsFollowingInDocumentOrderPositionIterator() {}
+
+// </IsFollowingInDocumentOrderPositionIterator>
+
+
+// <LevelPositionIterator>
+const char* LevelPositionIterator::class_name_str = "LevelPositionIterator";
+LevelPositionIterator::class_factory<LevelPositionIterator>
+LevelPositionIterator::g_class_factory;
+
+const serialization::ClassVersion 
+LevelPositionIterator::class_versions[] ={{ 1, 0x000905, false}};
+
+const int LevelPositionIterator::class_versions_count =
+sizeof(LevelPositionIterator::class_versions)/sizeof(struct serialization::ClassVersion);
+
+void LevelPositionIterator::accept(PlanIterVisitor& v) const {
+  v.beginVisit(*this);
+
+  std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin();
+  std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
+  for ( ; lIter != lEnd; ++lIter ){
+    (*lIter)->accept(v);
+  }
+
+  v.endVisit(*this);
+}
+
+LevelPositionIterator::~LevelPositionIterator() {}
+
+// </LevelPositionIterator>
+
+
+// <IsAttributePositionIterator>
+const char* IsAttributePositionIterator::class_name_str = "IsAttributePositionIterator";
+IsAttributePositionIterator::class_factory<IsAttributePositionIterator>
+IsAttributePositionIterator::g_class_factory;
+
+const serialization::ClassVersion 
+IsAttributePositionIterator::class_versions[] ={{ 1, 0x000905, false}};
+
+const int IsAttributePositionIterator::class_versions_count =
+sizeof(IsAttributePositionIterator::class_versions)/sizeof(struct serialization::ClassVersion);
+
+void IsAttributePositionIterator::accept(PlanIterVisitor& v) const {
+  v.beginVisit(*this);
+
+  std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin();
+  std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
+  for ( ; lIter != lEnd; ++lIter ){
+    (*lIter)->accept(v);
+  }
+
+  v.endVisit(*this);
+}
+
+IsAttributePositionIterator::~IsAttributePositionIterator() {}
+
+// </IsAttributePositionIterator>
+
+
+// <IsCommentPositionIterator>
+const char* IsCommentPositionIterator::class_name_str = "IsCommentPositionIterator";
+IsCommentPositionIterator::class_factory<IsCommentPositionIterator>
+IsCommentPositionIterator::g_class_factory;
+
+const serialization::ClassVersion 
+IsCommentPositionIterator::class_versions[] ={{ 1, 0x000905, false}};
+
+const int IsCommentPositionIterator::class_versions_count =
+sizeof(IsCommentPositionIterator::class_versions)/sizeof(struct serialization::ClassVersion);
+
+void IsCommentPositionIterator::accept(PlanIterVisitor& v) const {
+  v.beginVisit(*this);
+
+  std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin();
+  std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
+  for ( ; lIter != lEnd; ++lIter ){
+    (*lIter)->accept(v);
+  }
+
+  v.endVisit(*this);
+}
+
+IsCommentPositionIterator::~IsCommentPositionIterator() {}
+
+// </IsCommentPositionIterator>
+
+
+// <IsDocumentPositionIterator>
+const char* IsDocumentPositionIterator::class_name_str = "IsDocumentPositionIterator";
+IsDocumentPositionIterator::class_factory<IsDocumentPositionIterator>
+IsDocumentPositionIterator::g_class_factory;
+
+const serialization::ClassVersion 
+IsDocumentPositionIterator::class_versions[] ={{ 1, 0x000905, false}};
+
+const int IsDocumentPositionIterator::class_versions_count =
+sizeof(IsDocumentPositionIterator::class_versions)/sizeof(struct serialization::ClassVersion);
+
+void IsDocumentPositionIterator::accept(PlanIterVisitor& v) const {
+  v.beginVisit(*this);
+
+  std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin();
+  std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
+  for ( ; lIter != lEnd; ++lIter ){
+    (*lIter)->accept(v);
+  }
+
+  v.endVisit(*this);
+}
+
+IsDocumentPositionIterator::~IsDocumentPositionIterator() {}
+
+// </IsDocumentPositionIterator>
+
+
+// <IsElementPositionIterator>
+const char* IsElementPositionIterator::class_name_str = "IsElementPositionIterator";
+IsElementPositionIterator::class_factory<IsElementPositionIterator>
+IsElementPositionIterator::g_class_factory;
+
+const serialization::ClassVersion 
+IsElementPositionIterator::class_versions[] ={{ 1, 0x000905, false}};
+
+const int IsElementPositionIterator::class_versions_count =
+sizeof(IsElementPositionIterator::class_versions)/sizeof(struct serialization::ClassVersion);
+
+void IsElementPositionIterator::accept(PlanIterVisitor& v) const {
+  v.beginVisit(*this);
+
+  std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin();
+  std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
+  for ( ; lIter != lEnd; ++lIter ){
+    (*lIter)->accept(v);
+  }
+
+  v.endVisit(*this);
+}
+
+IsElementPositionIterator::~IsElementPositionIterator() {}
+
+// </IsElementPositionIterator>
+
+
+// <IsProcessingInstructionPositionIterator>
+const char* IsProcessingInstructionPositionIterator::class_name_str = "IsProcessingInstructionPositionIterator";
+IsProcessingInstructionPositionIterator::class_factory<IsProcessingInstructionPositionIterator>
+IsProcessingInstructionPositionIterator::g_class_factory;
+
+const serialization::ClassVersion 
+IsProcessingInstructionPositionIterator::class_versions[] ={{ 1, 0x000905, false}};
+
+const int IsProcessingInstructionPositionIterator::class_versions_count =
+sizeof(IsProcessingInstructionPositionIterator::class_versions)/sizeof(struct serialization::ClassVersion);
+
+void IsProcessingInstructionPositionIterator::accept(PlanIterVisitor& v) const {
+  v.beginVisit(*this);
+
+  std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin();
+  std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
+  for ( ; lIter != lEnd; ++lIter ){
+    (*lIter)->accept(v);
+  }
+
+  v.endVisit(*this);
+}
+
+IsProcessingInstructionPositionIterator::~IsProcessingInstructionPositionIterator() {}
+
+// </IsProcessingInstructionPositionIterator>
+
+
+// <IsTextPositionIterator>
+const char* IsTextPositionIterator::class_name_str = "IsTextPositionIterator";
+IsTextPositionIterator::class_factory<IsTextPositionIterator>
+IsTextPositionIterator::g_class_factory;
+
+const serialization::ClassVersion 
+IsTextPositionIterator::class_versions[] ={{ 1, 0x000905, false}};
+
+const int IsTextPositionIterator::class_versions_count =
+sizeof(IsTextPositionIterator::class_versions)/sizeof(struct serialization::ClassVersion);
+
+void IsTextPositionIterator::accept(PlanIterVisitor& v) const {
+  v.beginVisit(*this);
+
+  std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin();
+  std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
+  for ( ; lIter != lEnd; ++lIter ){
+    (*lIter)->accept(v);
+  }
+
+  v.endVisit(*this);
+}
+
+IsTextPositionIterator::~IsTextPositionIterator() {}
+
+// </IsTextPositionIterator>
+
+
+// <IsSiblingPositionIterator>
+const char* IsSiblingPositionIterator::class_name_str = "IsSiblingPositionIterator";
+IsSiblingPositionIterator::class_factory<IsSiblingPositionIterator>
+IsSiblingPositionIterator::g_class_factory;
+
+const serialization::ClassVersion 
+IsSiblingPositionIterator::class_versions[] ={{ 1, 0x000905, false}};
+
+const int IsSiblingPositionIterator::class_versions_count =
+sizeof(IsSiblingPositionIterator::class_versions)/sizeof(struct serialization::ClassVersion);
+
+void IsSiblingPositionIterator::accept(PlanIterVisitor& v) const {
+  v.beginVisit(*this);
+
+  std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin();
+  std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
+  for ( ; lIter != lEnd; ++lIter ){
+    (*lIter)->accept(v);
+  }
+
+  v.endVisit(*this);
+}
+
+IsSiblingPositionIterator::~IsSiblingPositionIterator() {}
+
+// </IsSiblingPositionIterator>
+
+
+// <InSameTreePositionIterator>
+const char* InSameTreePositionIterator::class_name_str = "InSameTreePositionIterator";
+InSameTreePositionIterator::class_factory<InSameTreePositionIterator>
+InSameTreePositionIterator::g_class_factory;
+
+const serialization::ClassVersion 
+InSameTreePositionIterator::class_versions[] ={{ 1, 0x000905, false}};
+
+const int InSameTreePositionIterator::class_versions_count =
+sizeof(InSameTreePositionIterator::class_versions)/sizeof(struct serialization::ClassVersion);
+
+void InSameTreePositionIterator::accept(PlanIterVisitor& v) const {
+  v.beginVisit(*this);
+
+  std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin();
+  std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
+  for ( ; lIter != lEnd; ++lIter ){
+    (*lIter)->accept(v);
+  }
+
+  v.endVisit(*this);
+}
+
+InSameTreePositionIterator::~InSameTreePositionIterator() {}
+
+// </InSameTreePositionIterator>
+
+
+// <InCollectionPositionIterator>
+const char* InCollectionPositionIterator::class_name_str = "InCollectionPositionIterator";
+InCollectionPositionIterator::class_factory<InCollectionPositionIterator>
+InCollectionPositionIterator::g_class_factory;
+
+const serialization::ClassVersion 
+InCollectionPositionIterator::class_versions[] ={{ 1, 0x000905, false}};
+
+const int InCollectionPositionIterator::class_versions_count =
+sizeof(InCollectionPositionIterator::class_versions)/sizeof(struct serialization::ClassVersion);
+
+void InCollectionPositionIterator::accept(PlanIterVisitor& v) const {
+  v.beginVisit(*this);
+
+  std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin();
+  std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
+  for ( ; lIter != lEnd; ++lIter ){
+    (*lIter)->accept(v);
+  }
+
+  v.endVisit(*this);
+}
+
+InCollectionPositionIterator::~InCollectionPositionIterator() {}
+
+// </InCollectionPositionIterator>
+
+
+// <InSameCollectionPositionIterator>
+const char* InSameCollectionPositionIterator::class_name_str = "InSameCollectionPositionIterator";
+InSameCollectionPositionIterator::class_factory<InSameCollectionPositionIterator>
+InSameCollectionPositionIterator::g_class_factory;
+
+const serialization::ClassVersion 
+InSameCollectionPositionIterator::class_versions[] ={{ 1, 0x000905, false}};
+
+const int InSameCollectionPositionIterator::class_versions_count =
+sizeof(InSameCollectionPositionIterator::class_versions)/sizeof(struct serialization::ClassVersion);
+
+void InSameCollectionPositionIterator::accept(PlanIterVisitor& v) const {
+  v.beginVisit(*this);
+
+  std::vector<PlanIter_t>::const_iterator lIter = theChildren.begin();
+  std::vector<PlanIter_t>::const_iterator lEnd = theChildren.end();
+  for ( ; lIter != lEnd; ++lIter ){
+    (*lIter)->accept(v);
+  }
+
+  v.endVisit(*this);
+}
+
+InSameCollectionPositionIterator::~InSameCollectionPositionIterator() {}
+
+// </InSameCollectionPositionIterator>
+
+
+
+}
+
+

=== added file 'src/runtime/nodes/pregenerated/node_position.h'
--- src/runtime/nodes/pregenerated/node_position.h	1970-01-01 00:00:00 +0000
+++ src/runtime/nodes/pregenerated/node_position.h	2011-10-27 20:59:25 +0000
@@ -0,0 +1,858 @@
+/*
+ * Copyright 2006-2008 The FLWOR Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+ 
+// ******************************************
+// *                                        *
+// * THIS IS A GENERATED FILE. DO NOT EDIT! *
+// * SEE .xml FILE WITH SAME NAME           *
+// *                                        *
+// ******************************************
+#ifndef ZORBA_RUNTIME_NODES_NODE_POSITION_H
+#define ZORBA_RUNTIME_NODES_NODE_POSITION_H
+
+
+#include "common/shared_types.h"
+
+
+
+#include "runtime/base/narybase.h"
+
+
+namespace zorba {
+
+/**
+ * 
+ * Author: Federico Cavalieri
+ */
+class NodePositionIterator : public NaryBaseIterator<NodePositionIterator, PlanIteratorState>
+{ 
+public:
+  SERIALIZABLE_CLASS(NodePositionIterator);
+
+  SERIALIZABLE_CLASS_CONSTRUCTOR2T(NodePositionIterator,
+    NaryBaseIterator<NodePositionIterator, PlanIteratorState>);
+
+  void serialize( ::zorba::serialization::Archiver& ar)
+  {
+    serialize_baseclass(ar,
+    (NaryBaseIterator<NodePositionIterator, PlanIteratorState>*)this);
+  }
+
+  NodePositionIterator(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& children)
+    : 
+    NaryBaseIterator<NodePositionIterator, PlanIteratorState>(sctx, loc, children)
+  {}
+
+  virtual ~NodePositionIterator();
+
+  void accept(PlanIterVisitor& v) const;
+
+  bool nextImpl(store::Item_t& result, PlanState& aPlanState) const;
+};
+
+
+/**
+ * 
+ * Author: Federico Cavalieri
+ */
+class IsAncestorPositionIterator : public NaryBaseIterator<IsAncestorPositionIterator, PlanIteratorState>
+{ 
+public:
+  SERIALIZABLE_CLASS(IsAncestorPositionIterator);
+
+  SERIALIZABLE_CLASS_CONSTRUCTOR2T(IsAncestorPositionIterator,
+    NaryBaseIterator<IsAncestorPositionIterator, PlanIteratorState>);
+
+  void serialize( ::zorba::serialization::Archiver& ar)
+  {
+    serialize_baseclass(ar,
+    (NaryBaseIterator<IsAncestorPositionIterator, PlanIteratorState>*)this);
+  }
+
+  IsAncestorPositionIterator(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& children)
+    : 
+    NaryBaseIterator<IsAncestorPositionIterator, PlanIteratorState>(sctx, loc, children)
+  {}
+
+  virtual ~IsAncestorPositionIterator();
+
+  void accept(PlanIterVisitor& v) const;
+
+  bool nextImpl(store::Item_t& result, PlanState& aPlanState) const;
+};
+
+
+/**
+ * 
+ * Author: Federico Cavalieri
+ */
+class IsFollowingSiblingPositionIterator : public NaryBaseIterator<IsFollowingSiblingPositionIterator, PlanIteratorState>
+{ 
+public:
+  SERIALIZABLE_CLASS(IsFollowingSiblingPositionIterator);
+
+  SERIALIZABLE_CLASS_CONSTRUCTOR2T(IsFollowingSiblingPositionIterator,
+    NaryBaseIterator<IsFollowingSiblingPositionIterator, PlanIteratorState>);
+
+  void serialize( ::zorba::serialization::Archiver& ar)
+  {
+    serialize_baseclass(ar,
+    (NaryBaseIterator<IsFollowingSiblingPositionIterator, PlanIteratorState>*)this);
+  }
+
+  IsFollowingSiblingPositionIterator(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& children)
+    : 
+    NaryBaseIterator<IsFollowingSiblingPositionIterator, PlanIteratorState>(sctx, loc, children)
+  {}
+
+  virtual ~IsFollowingSiblingPositionIterator();
+
+  void accept(PlanIterVisitor& v) const;
+
+  bool nextImpl(store::Item_t& result, PlanState& aPlanState) const;
+};
+
+
+/**
+ * 
+ * Author: Federico Cavalieri
+ */
+class IsFollowingPositionIterator : public NaryBaseIterator<IsFollowingPositionIterator, PlanIteratorState>
+{ 
+public:
+  SERIALIZABLE_CLASS(IsFollowingPositionIterator);
+
+  SERIALIZABLE_CLASS_CONSTRUCTOR2T(IsFollowingPositionIterator,
+    NaryBaseIterator<IsFollowingPositionIterator, PlanIteratorState>);
+
+  void serialize( ::zorba::serialization::Archiver& ar)
+  {
+    serialize_baseclass(ar,
+    (NaryBaseIterator<IsFollowingPositionIterator, PlanIteratorState>*)this);
+  }
+
+  IsFollowingPositionIterator(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& children)
+    : 
+    NaryBaseIterator<IsFollowingPositionIterator, PlanIteratorState>(sctx, loc, children)
+  {}
+
+  virtual ~IsFollowingPositionIterator();
+
+  void accept(PlanIterVisitor& v) const;
+
+  bool nextImpl(store::Item_t& result, PlanState& aPlanState) const;
+};
+
+
+/**
+ * 
+ * Author: Federico Cavalieri
+ */
+class IsInSubtreeOfPositionIterator : public NaryBaseIterator<IsInSubtreeOfPositionIterator, PlanIteratorState>
+{ 
+public:
+  SERIALIZABLE_CLASS(IsInSubtreeOfPositionIterator);
+
+  SERIALIZABLE_CLASS_CONSTRUCTOR2T(IsInSubtreeOfPositionIterator,
+    NaryBaseIterator<IsInSubtreeOfPositionIterator, PlanIteratorState>);
+
+  void serialize( ::zorba::serialization::Archiver& ar)
+  {
+    serialize_baseclass(ar,
+    (NaryBaseIterator<IsInSubtreeOfPositionIterator, PlanIteratorState>*)this);
+  }
+
+  IsInSubtreeOfPositionIterator(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& children)
+    : 
+    NaryBaseIterator<IsInSubtreeOfPositionIterator, PlanIteratorState>(sctx, loc, children)
+  {}
+
+  virtual ~IsInSubtreeOfPositionIterator();
+
+  void accept(PlanIterVisitor& v) const;
+
+  bool nextImpl(store::Item_t& result, PlanState& aPlanState) const;
+};
+
+
+/**
+ * 
+ * Author: Federico Cavalieri
+ */
+class IsDescendantPositionIterator : public NaryBaseIterator<IsDescendantPositionIterator, PlanIteratorState>
+{ 
+public:
+  SERIALIZABLE_CLASS(IsDescendantPositionIterator);
+
+  SERIALIZABLE_CLASS_CONSTRUCTOR2T(IsDescendantPositionIterator,
+    NaryBaseIterator<IsDescendantPositionIterator, PlanIteratorState>);
+
+  void serialize( ::zorba::serialization::Archiver& ar)
+  {
+    serialize_baseclass(ar,
+    (NaryBaseIterator<IsDescendantPositionIterator, PlanIteratorState>*)this);
+  }
+
+  IsDescendantPositionIterator(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& children)
+    : 
+    NaryBaseIterator<IsDescendantPositionIterator, PlanIteratorState>(sctx, loc, children)
+  {}
+
+  virtual ~IsDescendantPositionIterator();
+
+  void accept(PlanIterVisitor& v) const;
+
+  bool nextImpl(store::Item_t& result, PlanState& aPlanState) const;
+};
+
+
+/**
+ * 
+ * Author: Federico Cavalieri
+ */
+class IsPrecedingSiblingPositionIterator : public NaryBaseIterator<IsPrecedingSiblingPositionIterator, PlanIteratorState>
+{ 
+public:
+  SERIALIZABLE_CLASS(IsPrecedingSiblingPositionIterator);
+
+  SERIALIZABLE_CLASS_CONSTRUCTOR2T(IsPrecedingSiblingPositionIterator,
+    NaryBaseIterator<IsPrecedingSiblingPositionIterator, PlanIteratorState>);
+
+  void serialize( ::zorba::serialization::Archiver& ar)
+  {
+    serialize_baseclass(ar,
+    (NaryBaseIterator<IsPrecedingSiblingPositionIterator, PlanIteratorState>*)this);
+  }
+
+  IsPrecedingSiblingPositionIterator(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& children)
+    : 
+    NaryBaseIterator<IsPrecedingSiblingPositionIterator, PlanIteratorState>(sctx, loc, children)
+  {}
+
+  virtual ~IsPrecedingSiblingPositionIterator();
+
+  void accept(PlanIterVisitor& v) const;
+
+  bool nextImpl(store::Item_t& result, PlanState& aPlanState) const;
+};
+
+
+/**
+ * 
+ * Author: Federico Cavalieri
+ */
+class IsPrecedingPositionIterator : public NaryBaseIterator<IsPrecedingPositionIterator, PlanIteratorState>
+{ 
+public:
+  SERIALIZABLE_CLASS(IsPrecedingPositionIterator);
+
+  SERIALIZABLE_CLASS_CONSTRUCTOR2T(IsPrecedingPositionIterator,
+    NaryBaseIterator<IsPrecedingPositionIterator, PlanIteratorState>);
+
+  void serialize( ::zorba::serialization::Archiver& ar)
+  {
+    serialize_baseclass(ar,
+    (NaryBaseIterator<IsPrecedingPositionIterator, PlanIteratorState>*)this);
+  }
+
+  IsPrecedingPositionIterator(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& children)
+    : 
+    NaryBaseIterator<IsPrecedingPositionIterator, PlanIteratorState>(sctx, loc, children)
+  {}
+
+  virtual ~IsPrecedingPositionIterator();
+
+  void accept(PlanIterVisitor& v) const;
+
+  bool nextImpl(store::Item_t& result, PlanState& aPlanState) const;
+};
+
+
+/**
+ * 
+ * Author: Federico Cavalieri
+ */
+class IsChildPositionIterator : public NaryBaseIterator<IsChildPositionIterator, PlanIteratorState>
+{ 
+public:
+  SERIALIZABLE_CLASS(IsChildPositionIterator);
+
+  SERIALIZABLE_CLASS_CONSTRUCTOR2T(IsChildPositionIterator,
+    NaryBaseIterator<IsChildPositionIterator, PlanIteratorState>);
+
+  void serialize( ::zorba::serialization::Archiver& ar)
+  {
+    serialize_baseclass(ar,
+    (NaryBaseIterator<IsChildPositionIterator, PlanIteratorState>*)this);
+  }
+
+  IsChildPositionIterator(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& children)
+    : 
+    NaryBaseIterator<IsChildPositionIterator, PlanIteratorState>(sctx, loc, children)
+  {}
+
+  virtual ~IsChildPositionIterator();
+
+  void accept(PlanIterVisitor& v) const;
+
+  bool nextImpl(store::Item_t& result, PlanState& aPlanState) const;
+};
+
+
+/**
+ * 
+ * Author: Federico Cavalieri
+ */
+class IsAttributeOfPositionIterator : public NaryBaseIterator<IsAttributeOfPositionIterator, PlanIteratorState>
+{ 
+public:
+  SERIALIZABLE_CLASS(IsAttributeOfPositionIterator);
+
+  SERIALIZABLE_CLASS_CONSTRUCTOR2T(IsAttributeOfPositionIterator,
+    NaryBaseIterator<IsAttributeOfPositionIterator, PlanIteratorState>);
+
+  void serialize( ::zorba::serialization::Archiver& ar)
+  {
+    serialize_baseclass(ar,
+    (NaryBaseIterator<IsAttributeOfPositionIterator, PlanIteratorState>*)this);
+  }
+
+  IsAttributeOfPositionIterator(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& children)
+    : 
+    NaryBaseIterator<IsAttributeOfPositionIterator, PlanIteratorState>(sctx, loc, children)
+  {}
+
+  virtual ~IsAttributeOfPositionIterator();
+
+  void accept(PlanIterVisitor& v) const;
+
+  bool nextImpl(store::Item_t& result, PlanState& aPlanState) const;
+};
+
+
+/**
+ * 
+ * Author: Federico Cavalieri
+ */
+class IsParentPositionIterator : public NaryBaseIterator<IsParentPositionIterator, PlanIteratorState>
+{ 
+public:
+  SERIALIZABLE_CLASS(IsParentPositionIterator);
+
+  SERIALIZABLE_CLASS_CONSTRUCTOR2T(IsParentPositionIterator,
+    NaryBaseIterator<IsParentPositionIterator, PlanIteratorState>);
+
+  void serialize( ::zorba::serialization::Archiver& ar)
+  {
+    serialize_baseclass(ar,
+    (NaryBaseIterator<IsParentPositionIterator, PlanIteratorState>*)this);
+  }
+
+  IsParentPositionIterator(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& children)
+    : 
+    NaryBaseIterator<IsParentPositionIterator, PlanIteratorState>(sctx, loc, children)
+  {}
+
+  virtual ~IsParentPositionIterator();
+
+  void accept(PlanIterVisitor& v) const;
+
+  bool nextImpl(store::Item_t& result, PlanState& aPlanState) const;
+};
+
+
+/**
+ * 
+ * Author: Federico Cavalieri
+ */
+class IsPrecedingInDocumentOrderPositionIterator : public NaryBaseIterator<IsPrecedingInDocumentOrderPositionIterator, PlanIteratorState>
+{ 
+public:
+  SERIALIZABLE_CLASS(IsPrecedingInDocumentOrderPositionIterator);
+
+  SERIALIZABLE_CLASS_CONSTRUCTOR2T(IsPrecedingInDocumentOrderPositionIterator,
+    NaryBaseIterator<IsPrecedingInDocumentOrderPositionIterator, PlanIteratorState>);
+
+  void serialize( ::zorba::serialization::Archiver& ar)
+  {
+    serialize_baseclass(ar,
+    (NaryBaseIterator<IsPrecedingInDocumentOrderPositionIterator, PlanIteratorState>*)this);
+  }
+
+  IsPrecedingInDocumentOrderPositionIterator(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& children)
+    : 
+    NaryBaseIterator<IsPrecedingInDocumentOrderPositionIterator, PlanIteratorState>(sctx, loc, children)
+  {}
+
+  virtual ~IsPrecedingInDocumentOrderPositionIterator();
+
+  void accept(PlanIterVisitor& v) const;
+
+  bool nextImpl(store::Item_t& result, PlanState& aPlanState) const;
+};
+
+
+/**
+ * 
+ * Author: Federico Cavalieri
+ */
+class IsFollowingInDocumentOrderPositionIterator : public NaryBaseIterator<IsFollowingInDocumentOrderPositionIterator, PlanIteratorState>
+{ 
+public:
+  SERIALIZABLE_CLASS(IsFollowingInDocumentOrderPositionIterator);
+
+  SERIALIZABLE_CLASS_CONSTRUCTOR2T(IsFollowingInDocumentOrderPositionIterator,
+    NaryBaseIterator<IsFollowingInDocumentOrderPositionIterator, PlanIteratorState>);
+
+  void serialize( ::zorba::serialization::Archiver& ar)
+  {
+    serialize_baseclass(ar,
+    (NaryBaseIterator<IsFollowingInDocumentOrderPositionIterator, PlanIteratorState>*)this);
+  }
+
+  IsFollowingInDocumentOrderPositionIterator(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& children)
+    : 
+    NaryBaseIterator<IsFollowingInDocumentOrderPositionIterator, PlanIteratorState>(sctx, loc, children)
+  {}
+
+  virtual ~IsFollowingInDocumentOrderPositionIterator();
+
+  void accept(PlanIterVisitor& v) const;
+
+  bool nextImpl(store::Item_t& result, PlanState& aPlanState) const;
+};
+
+
+/**
+ * 
+ * Author: Federico Cavalieri
+ */
+class LevelPositionIterator : public NaryBaseIterator<LevelPositionIterator, PlanIteratorState>
+{ 
+public:
+  SERIALIZABLE_CLASS(LevelPositionIterator);
+
+  SERIALIZABLE_CLASS_CONSTRUCTOR2T(LevelPositionIterator,
+    NaryBaseIterator<LevelPositionIterator, PlanIteratorState>);
+
+  void serialize( ::zorba::serialization::Archiver& ar)
+  {
+    serialize_baseclass(ar,
+    (NaryBaseIterator<LevelPositionIterator, PlanIteratorState>*)this);
+  }
+
+  LevelPositionIterator(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& children)
+    : 
+    NaryBaseIterator<LevelPositionIterator, PlanIteratorState>(sctx, loc, children)
+  {}
+
+  virtual ~LevelPositionIterator();
+
+  void accept(PlanIterVisitor& v) const;
+
+  bool nextImpl(store::Item_t& result, PlanState& aPlanState) const;
+};
+
+
+/**
+ * 
+ * Author: Federico Cavalieri
+ */
+class IsAttributePositionIterator : public NaryBaseIterator<IsAttributePositionIterator, PlanIteratorState>
+{ 
+public:
+  SERIALIZABLE_CLASS(IsAttributePositionIterator);
+
+  SERIALIZABLE_CLASS_CONSTRUCTOR2T(IsAttributePositionIterator,
+    NaryBaseIterator<IsAttributePositionIterator, PlanIteratorState>);
+
+  void serialize( ::zorba::serialization::Archiver& ar)
+  {
+    serialize_baseclass(ar,
+    (NaryBaseIterator<IsAttributePositionIterator, PlanIteratorState>*)this);
+  }
+
+  IsAttributePositionIterator(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& children)
+    : 
+    NaryBaseIterator<IsAttributePositionIterator, PlanIteratorState>(sctx, loc, children)
+  {}
+
+  virtual ~IsAttributePositionIterator();
+
+  void accept(PlanIterVisitor& v) const;
+
+  bool nextImpl(store::Item_t& result, PlanState& aPlanState) const;
+};
+
+
+/**
+ * 
+ * Author: Federico Cavalieri
+ */
+class IsCommentPositionIterator : public NaryBaseIterator<IsCommentPositionIterator, PlanIteratorState>
+{ 
+public:
+  SERIALIZABLE_CLASS(IsCommentPositionIterator);
+
+  SERIALIZABLE_CLASS_CONSTRUCTOR2T(IsCommentPositionIterator,
+    NaryBaseIterator<IsCommentPositionIterator, PlanIteratorState>);
+
+  void serialize( ::zorba::serialization::Archiver& ar)
+  {
+    serialize_baseclass(ar,
+    (NaryBaseIterator<IsCommentPositionIterator, PlanIteratorState>*)this);
+  }
+
+  IsCommentPositionIterator(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& children)
+    : 
+    NaryBaseIterator<IsCommentPositionIterator, PlanIteratorState>(sctx, loc, children)
+  {}
+
+  virtual ~IsCommentPositionIterator();
+
+  void accept(PlanIterVisitor& v) const;
+
+  bool nextImpl(store::Item_t& result, PlanState& aPlanState) const;
+};
+
+
+/**
+ * 
+ * Author: Federico Cavalieri
+ */
+class IsDocumentPositionIterator : public NaryBaseIterator<IsDocumentPositionIterator, PlanIteratorState>
+{ 
+public:
+  SERIALIZABLE_CLASS(IsDocumentPositionIterator);
+
+  SERIALIZABLE_CLASS_CONSTRUCTOR2T(IsDocumentPositionIterator,
+    NaryBaseIterator<IsDocumentPositionIterator, PlanIteratorState>);
+
+  void serialize( ::zorba::serialization::Archiver& ar)
+  {
+    serialize_baseclass(ar,
+    (NaryBaseIterator<IsDocumentPositionIterator, PlanIteratorState>*)this);
+  }
+
+  IsDocumentPositionIterator(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& children)
+    : 
+    NaryBaseIterator<IsDocumentPositionIterator, PlanIteratorState>(sctx, loc, children)
+  {}
+
+  virtual ~IsDocumentPositionIterator();
+
+  void accept(PlanIterVisitor& v) const;
+
+  bool nextImpl(store::Item_t& result, PlanState& aPlanState) const;
+};
+
+
+/**
+ * 
+ * Author: Federico Cavalieri
+ */
+class IsElementPositionIterator : public NaryBaseIterator<IsElementPositionIterator, PlanIteratorState>
+{ 
+public:
+  SERIALIZABLE_CLASS(IsElementPositionIterator);
+
+  SERIALIZABLE_CLASS_CONSTRUCTOR2T(IsElementPositionIterator,
+    NaryBaseIterator<IsElementPositionIterator, PlanIteratorState>);
+
+  void serialize( ::zorba::serialization::Archiver& ar)
+  {
+    serialize_baseclass(ar,
+    (NaryBaseIterator<IsElementPositionIterator, PlanIteratorState>*)this);
+  }
+
+  IsElementPositionIterator(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& children)
+    : 
+    NaryBaseIterator<IsElementPositionIterator, PlanIteratorState>(sctx, loc, children)
+  {}
+
+  virtual ~IsElementPositionIterator();
+
+  void accept(PlanIterVisitor& v) const;
+
+  bool nextImpl(store::Item_t& result, PlanState& aPlanState) const;
+};
+
+
+/**
+ * 
+ * Author: Federico Cavalieri
+ */
+class IsProcessingInstructionPositionIterator : public NaryBaseIterator<IsProcessingInstructionPositionIterator, PlanIteratorState>
+{ 
+public:
+  SERIALIZABLE_CLASS(IsProcessingInstructionPositionIterator);
+
+  SERIALIZABLE_CLASS_CONSTRUCTOR2T(IsProcessingInstructionPositionIterator,
+    NaryBaseIterator<IsProcessingInstructionPositionIterator, PlanIteratorState>);
+
+  void serialize( ::zorba::serialization::Archiver& ar)
+  {
+    serialize_baseclass(ar,
+    (NaryBaseIterator<IsProcessingInstructionPositionIterator, PlanIteratorState>*)this);
+  }
+
+  IsProcessingInstructionPositionIterator(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& children)
+    : 
+    NaryBaseIterator<IsProcessingInstructionPositionIterator, PlanIteratorState>(sctx, loc, children)
+  {}
+
+  virtual ~IsProcessingInstructionPositionIterator();
+
+  void accept(PlanIterVisitor& v) const;
+
+  bool nextImpl(store::Item_t& result, PlanState& aPlanState) const;
+};
+
+
+/**
+ * 
+ * Author: Federico Cavalieri
+ */
+class IsTextPositionIterator : public NaryBaseIterator<IsTextPositionIterator, PlanIteratorState>
+{ 
+public:
+  SERIALIZABLE_CLASS(IsTextPositionIterator);
+
+  SERIALIZABLE_CLASS_CONSTRUCTOR2T(IsTextPositionIterator,
+    NaryBaseIterator<IsTextPositionIterator, PlanIteratorState>);
+
+  void serialize( ::zorba::serialization::Archiver& ar)
+  {
+    serialize_baseclass(ar,
+    (NaryBaseIterator<IsTextPositionIterator, PlanIteratorState>*)this);
+  }
+
+  IsTextPositionIterator(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& children)
+    : 
+    NaryBaseIterator<IsTextPositionIterator, PlanIteratorState>(sctx, loc, children)
+  {}
+
+  virtual ~IsTextPositionIterator();
+
+  void accept(PlanIterVisitor& v) const;
+
+  bool nextImpl(store::Item_t& result, PlanState& aPlanState) const;
+};
+
+
+/**
+ * 
+ * Author: Federico Cavalieri
+ */
+class IsSiblingPositionIterator : public NaryBaseIterator<IsSiblingPositionIterator, PlanIteratorState>
+{ 
+public:
+  SERIALIZABLE_CLASS(IsSiblingPositionIterator);
+
+  SERIALIZABLE_CLASS_CONSTRUCTOR2T(IsSiblingPositionIterator,
+    NaryBaseIterator<IsSiblingPositionIterator, PlanIteratorState>);
+
+  void serialize( ::zorba::serialization::Archiver& ar)
+  {
+    serialize_baseclass(ar,
+    (NaryBaseIterator<IsSiblingPositionIterator, PlanIteratorState>*)this);
+  }
+
+  IsSiblingPositionIterator(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& children)
+    : 
+    NaryBaseIterator<IsSiblingPositionIterator, PlanIteratorState>(sctx, loc, children)
+  {}
+
+  virtual ~IsSiblingPositionIterator();
+
+  void accept(PlanIterVisitor& v) const;
+
+  bool nextImpl(store::Item_t& result, PlanState& aPlanState) const;
+};
+
+
+/**
+ * 
+ * Author: Federico Cavalieri
+ */
+class InSameTreePositionIterator : public NaryBaseIterator<InSameTreePositionIterator, PlanIteratorState>
+{ 
+public:
+  SERIALIZABLE_CLASS(InSameTreePositionIterator);
+
+  SERIALIZABLE_CLASS_CONSTRUCTOR2T(InSameTreePositionIterator,
+    NaryBaseIterator<InSameTreePositionIterator, PlanIteratorState>);
+
+  void serialize( ::zorba::serialization::Archiver& ar)
+  {
+    serialize_baseclass(ar,
+    (NaryBaseIterator<InSameTreePositionIterator, PlanIteratorState>*)this);
+  }
+
+  InSameTreePositionIterator(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& children)
+    : 
+    NaryBaseIterator<InSameTreePositionIterator, PlanIteratorState>(sctx, loc, children)
+  {}
+
+  virtual ~InSameTreePositionIterator();
+
+  void accept(PlanIterVisitor& v) const;
+
+  bool nextImpl(store::Item_t& result, PlanState& aPlanState) const;
+};
+
+
+/**
+ * 
+ * Author: Federico Cavalieri
+ */
+class InCollectionPositionIterator : public NaryBaseIterator<InCollectionPositionIterator, PlanIteratorState>
+{ 
+public:
+  SERIALIZABLE_CLASS(InCollectionPositionIterator);
+
+  SERIALIZABLE_CLASS_CONSTRUCTOR2T(InCollectionPositionIterator,
+    NaryBaseIterator<InCollectionPositionIterator, PlanIteratorState>);
+
+  void serialize( ::zorba::serialization::Archiver& ar)
+  {
+    serialize_baseclass(ar,
+    (NaryBaseIterator<InCollectionPositionIterator, PlanIteratorState>*)this);
+  }
+
+  InCollectionPositionIterator(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& children)
+    : 
+    NaryBaseIterator<InCollectionPositionIterator, PlanIteratorState>(sctx, loc, children)
+  {}
+
+  virtual ~InCollectionPositionIterator();
+
+  void accept(PlanIterVisitor& v) const;
+
+  bool nextImpl(store::Item_t& result, PlanState& aPlanState) const;
+};
+
+
+/**
+ * 
+ * Author: Federico Cavalieri
+ */
+class InSameCollectionPositionIterator : public NaryBaseIterator<InSameCollectionPositionIterator, PlanIteratorState>
+{ 
+public:
+  SERIALIZABLE_CLASS(InSameCollectionPositionIterator);
+
+  SERIALIZABLE_CLASS_CONSTRUCTOR2T(InSameCollectionPositionIterator,
+    NaryBaseIterator<InSameCollectionPositionIterator, PlanIteratorState>);
+
+  void serialize( ::zorba::serialization::Archiver& ar)
+  {
+    serialize_baseclass(ar,
+    (NaryBaseIterator<InSameCollectionPositionIterator, PlanIteratorState>*)this);
+  }
+
+  InSameCollectionPositionIterator(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& children)
+    : 
+    NaryBaseIterator<InSameCollectionPositionIterator, PlanIteratorState>(sctx, loc, children)
+  {}
+
+  virtual ~InSameCollectionPositionIterator();
+
+  void accept(PlanIterVisitor& v) const;
+
+  bool nextImpl(store::Item_t& result, PlanState& aPlanState) const;
+};
+
+
+}
+#endif
+/*
+ * Local variables:
+ * mode: c++
+ * End:
+ */ 

=== modified file 'src/runtime/qnames/qnames_impl.cpp'
--- src/runtime/qnames/qnames_impl.cpp	2011-07-19 19:35:04 +0000
+++ src/runtime/qnames/qnames_impl.cpp	2011-10-27 20:59:25 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -52,7 +52,7 @@
   PlanIteratorState* state;
   DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
 
-  if (consumeNext(itemQName, theChild0.getp(), planState )) 
+  if (consumeNext(itemQName, theChild0.getp(), planState ))
   {
     itemQName->getStringValue2(qname);
 
@@ -60,7 +60,7 @@
 
     index = qname.find(":", 0, 1);
 
-    if (index != zstring::npos) 
+    if (index != zstring::npos)
     {
       resPre = qname.substr(0, index);
       resLocal = qname.substr(index+1, qname.size() - index);
@@ -70,7 +70,7 @@
         throw XQUERY_EXCEPTION(
           err::FOCA0002, ERROR_PARAMS( qname ), ERROR_LOC(loc)
         );
-    } 
+    }
     else
     {
       resLocal = qname;
@@ -80,8 +80,8 @@
           err::FOCA0002, ERROR_PARAMS( qname ), ERROR_LOC(loc)
         );
     }
-      
-    if (consumeNext(itemElem, theChild1, planState )) 
+
+    if (consumeNext(itemElem, theChild1, planState ))
     {
       itemElem->getNamespaceBindings(NamespaceBindings);
 
@@ -104,7 +104,7 @@
           err::FONS0004, ERROR_PARAMS( resPre ), ERROR_LOC( loc )
         );
     }
-    
+
     GENV_ITEMFACTORY->createQName(result, resNs, resPre, resLocal);
 
     STACK_PUSH(true, state);
@@ -128,7 +128,7 @@
   PlanIteratorState* state;
   DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
 
-  if (consumeNext(itemURI, theChild0.getp(), planState )) 
+  if (consumeNext(itemURI, theChild0.getp(), planState ))
   {
     itemURI->getStringValue2(resNs);
 
@@ -138,12 +138,12 @@
   consumeNext(itemQName, theChild1.getp(), planState );
 
   itemQName->getStringValue2(qname);
-  
+
   ascii::trim_whitespace(qname);
 
   index = qname.find(":", 0, 1);
 
-  if (index != zstring::npos) 
+  if (index != zstring::npos)
   {
     if (resNs.empty())
       throw XQUERY_EXCEPTION(
@@ -152,12 +152,12 @@
 
     resPre = qname.substr(0, index);
     resLocal = qname.substr(index+1, qname.size() - index);
-  } 
+  }
   else
   {
     resLocal = qname;
   }
-  
+
   if ((index != zstring::npos && ! GENV_GCAST.castableToNCName(resPre)) ||
       ! GENV_GCAST.castableToNCName(resLocal))
   {
@@ -209,7 +209,7 @@
 
 //11.2.2 fn:prefix-from-QName
 bool PrefixFromQNameIterator::nextImpl(
-    store::Item_t& result, 
+    store::Item_t& result,
     PlanState& planState) const
 {
   store::Item_t item;
@@ -232,8 +232,8 @@
 
 //11.2.3 fn:local-name-from-QName
 bool LocalNameFromQNameIterator::nextImpl(
-    store::Item_t& result, 
-    PlanState& planState) const 
+    store::Item_t& result,
+    PlanState& planState) const
 {
   store::Item_t item;
   zstring localName;
@@ -253,7 +253,7 @@
 //11.2.4 fn:namespace-uri-from-QName
 bool NamespaceUriFromQNameIterator::nextImpl(
     store::Item_t& result,
-    PlanState& planState) const 
+    PlanState& planState) const
 {
   store::Item_t item;
   zstring ns;
@@ -277,6 +277,7 @@
 {
   store::Item_t itemPrefix, itemElem;
   zstring resNs;
+  zstring prefix;
   bool found = false;
   store::NsBindings NamespaceBindings;
   store::NsBindings::const_iterator iter;
@@ -284,43 +285,35 @@
   PlanIteratorState* state;
   DEFAULT_STACK_INIT(PlanIteratorState, state, planState);
 
-//  According to W3C bug #11590 comment #9
-//  http://www.w3.org/Bugs/Public/show_bug.cgi?id=11590#c9
-//  namespace-uri-for-prefix('', <a/>)
-//  and
-//  namespace-uri-for-prefix((), <a/>)
-//  should return the empty sequence
   if (!consumeNext(itemPrefix, theChildren[0].getp(), planState ))
   {
-    resNs = theSctx->default_elem_type_ns();
-    found = true;
-  }
-  else
-  {
-    if (!consumeNext(itemElem, theChildren[1].getp(), planState ))
-    {
-      ZORBA_ASSERT(false);
-    }
-    else 
-    {
-      itemElem->getNamespaceBindings(NamespaceBindings);
-
-      for (iter = NamespaceBindings.begin();
-           iter != NamespaceBindings.end();
-           ++iter)
-      {
-        zstring pre;
-        itemPrefix->getStringValue2(pre);
-
-        ascii::trim_whitespace(pre);
-
-        if ((*iter).first == pre)
+    prefix = "";
+  }
+  else
+  {
+    itemPrefix->getStringValue2(prefix);
+    ascii::trim_whitespace(prefix);
+  }
+
+  if (!consumeNext(itemElem, theChildren[1].getp(), planState ))
+  {
+    ZORBA_ASSERT(false);
+  }
+  else
+  {
+    itemElem->getNamespaceBindings(NamespaceBindings);
+
+    for (iter = NamespaceBindings.begin();
+         iter != NamespaceBindings.end();
+         ++iter)
+    {
+      if (((*iter).first == prefix) &&
+          !(*iter).second.empty())
         {
           resNs = (*iter).second;
           found = true;
           break;
         }
-      }
     }
   }
 

=== modified file 'src/runtime/spec/mappings.xml'
--- src/runtime/spec/mappings.xml	2011-09-30 08:08:13 +0000
+++ src/runtime/spec/mappings.xml	2011-10-27 20:59:25 +0000
@@ -22,7 +22,11 @@
 
     <zorba:namespace uri="http://www.zorba-xquery.com/modules/node-reference";
                      define="ZORBA_NODEREF_FN_NS"
-                     prefix="fn-zorba-ref"/> 
+                     prefix="fn-zorba-ref"/>
+    
+    <zorba:namespace uri="http://www.zorba-xquery.com/modules/node-position";
+                     define="ZORBA_NODEPOS_FN_NS"
+                     prefix="fn-zorba-pos"/> 
 
     <zorba:namespace uri="http://www.zorba-xquery.com/modules/schema";
                      define="ZORBA_SCHEMA_FN_NS"

=== added file 'src/runtime/spec/nodes/node_position.xml'
--- src/runtime/spec/nodes/node_position.xml	1970-01-01 00:00:00 +0000
+++ src/runtime/spec/nodes/node_position.xml	2011-10-27 20:59:25 +0000
@@ -0,0 +1,439 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+/////////////////////////////////////////////////////////////////////////////////
+//                                                                             //
+/////////////////////////////////////////////////////////////////////////////////
+-->
+<zorba:iterators
+  xmlns:zorba="http://www.zorba-xquery.com";
+  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
+  xsi:schemaLocation="http://www.zorba-xquery.com ../runtime.xsd">
+
+  <!--
+/*******************************************************************************
+********************************************************************************/
+-->
+<zorba:iterator name="NodePositionIterator">
+
+  <zorba:description author="Federico Cavalieri"></zorba:description>
+
+  <zorba:function>
+    <zorba:signature localname="node-position" prefix="fn-zorba-pos">
+      <zorba:param>node()</zorba:param>
+      <zorba:output>xs:anyURI</zorba:output>
+    </zorba:signature>
+  </zorba:function>
+
+</zorba:iterator>
+   
+  <!--
+/*******************************************************************************
+********************************************************************************/
+-->
+  <zorba:iterator name="IsAncestorPositionIterator">
+
+    <zorba:description author="Federico Cavalieri"></zorba:description>
+
+    <zorba:function>
+      <zorba:signature localname="ancestor-of" prefix="fn-zorba-pos">
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:output>xs:boolean</zorba:output>
+      </zorba:signature>
+    </zorba:function>
+
+  </zorba:iterator>
+
+  <!--
+/*******************************************************************************
+********************************************************************************/
+-->
+  <zorba:iterator name="IsFollowingSiblingPositionIterator">
+
+    <zorba:description author="Federico Cavalieri"></zorba:description>
+
+    <zorba:function>
+      <zorba:signature localname="following-sibling-of" prefix="fn-zorba-pos">
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:output>xs:boolean</zorba:output>
+      </zorba:signature>
+    </zorba:function>
+
+  </zorba:iterator>
+
+<!--
+/*******************************************************************************
+********************************************************************************/
+-->
+  <zorba:iterator name="IsFollowingPositionIterator">
+
+    <zorba:description author="Federico Cavalieri"></zorba:description>
+
+    <zorba:function>
+      <zorba:signature localname="following-of" prefix="fn-zorba-pos">
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:output>xs:boolean</zorba:output>
+      </zorba:signature>
+    </zorba:function>
+
+  </zorba:iterator>
+
+
+  <!--
+/*******************************************************************************
+********************************************************************************/
+-->
+  <zorba:iterator name="IsInSubtreeOfPositionIterator">
+
+    <zorba:description author="Federico Cavalieri"></zorba:description>
+
+    <zorba:function>
+      <zorba:signature localname="in-subtree-of" prefix="fn-zorba-pos">
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:output>xs:boolean</zorba:output>
+      </zorba:signature>
+    </zorba:function>
+
+  </zorba:iterator>
+
+
+  <!--
+/*******************************************************************************
+********************************************************************************/
+-->
+  <zorba:iterator name="IsDescendantPositionIterator">
+
+    <zorba:description author="Federico Cavalieri"></zorba:description>
+
+    <zorba:function>
+      <zorba:signature localname="descendant-of" prefix="fn-zorba-pos">
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:output>xs:boolean</zorba:output>
+      </zorba:signature>
+    </zorba:function>
+
+  </zorba:iterator>
+
+  <!--
+/*******************************************************************************
+********************************************************************************/
+-->
+  <zorba:iterator name="IsPrecedingSiblingPositionIterator">
+
+    <zorba:description author="Federico Cavalieri"></zorba:description>
+
+    <zorba:function>
+      <zorba:signature localname="preceding-sibling-of" prefix="fn-zorba-pos">
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:output>xs:boolean</zorba:output>
+      </zorba:signature>
+    </zorba:function>
+
+  </zorba:iterator>
+
+  <!--
+/*******************************************************************************
+********************************************************************************/
+-->
+  <zorba:iterator name="IsPrecedingPositionIterator">
+
+    <zorba:description author="Federico Cavalieri"></zorba:description>
+
+    <zorba:function>
+      <zorba:signature localname="preceding-of" prefix="fn-zorba-pos">
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:output>xs:boolean</zorba:output>
+      </zorba:signature>
+    </zorba:function>
+
+  </zorba:iterator>
+
+  <!--
+/*******************************************************************************
+********************************************************************************/
+-->
+  <zorba:iterator name="IsChildPositionIterator">
+
+    <zorba:description author="Federico Cavalieri"></zorba:description>
+
+    <zorba:function>
+      <zorba:signature localname="child-of" prefix="fn-zorba-pos">
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:output>xs:boolean</zorba:output>
+      </zorba:signature>
+    </zorba:function>
+
+  </zorba:iterator>
+
+  <!--
+/*******************************************************************************
+********************************************************************************/
+-->
+  <zorba:iterator name="IsAttributeOfPositionIterator">
+
+    <zorba:description author="Federico Cavalieri"></zorba:description>
+
+    <zorba:function>
+      <zorba:signature localname="attribute-of" prefix="fn-zorba-pos">
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:output>xs:boolean</zorba:output>
+      </zorba:signature>
+    </zorba:function>
+
+  </zorba:iterator>
+
+
+  <!--
+/*******************************************************************************
+********************************************************************************/
+-->
+  <zorba:iterator name="IsParentPositionIterator">
+
+    <zorba:description author="Federico Cavalieri"></zorba:description>
+
+    <zorba:function>
+      <zorba:signature localname="parent-of" prefix="fn-zorba-pos">
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:output>xs:boolean</zorba:output>
+      </zorba:signature>
+    </zorba:function>
+
+  </zorba:iterator>
+
+  <!--
+/*******************************************************************************
+********************************************************************************/
+-->
+  <zorba:iterator name="IsPrecedingInDocumentOrderPositionIterator">
+
+    <zorba:description author="Federico Cavalieri"></zorba:description>
+
+    <zorba:function>
+      <zorba:signature localname="preceding-in-document-order-of" prefix="fn-zorba-pos">
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:output>xs:boolean</zorba:output>
+      </zorba:signature>
+    </zorba:function>
+
+  </zorba:iterator>
+
+  <!--
+/*******************************************************************************
+********************************************************************************/
+-->
+  <zorba:iterator name="IsFollowingInDocumentOrderPositionIterator">
+
+    <zorba:description author="Federico Cavalieri"></zorba:description>
+
+    <zorba:function>
+      <zorba:signature localname="following-in-document-order-of" prefix="fn-zorba-pos">
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:output>xs:boolean</zorba:output>
+      </zorba:signature>
+    </zorba:function>
+
+  </zorba:iterator>
+
+  <!--
+/*******************************************************************************
+********************************************************************************/
+-->
+  <zorba:iterator name="LevelPositionIterator">
+
+    <zorba:description author="Federico Cavalieri"></zorba:description>
+
+    <zorba:function>
+      <zorba:signature localname="level" prefix="fn-zorba-pos">
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:output>xs:integer</zorba:output>
+      </zorba:signature>
+    </zorba:function>
+
+  </zorba:iterator>
+
+  <!--
+/*******************************************************************************
+********************************************************************************/
+-->
+  <zorba:iterator name="IsAttributePositionIterator">
+
+    <zorba:description author="Federico Cavalieri"></zorba:description>
+
+    <zorba:function>
+      <zorba:signature localname="is-attribute" prefix="fn-zorba-pos">
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:output>xs:boolean</zorba:output>
+      </zorba:signature>
+    </zorba:function>
+
+  </zorba:iterator>
+
+  <!--
+/*******************************************************************************
+********************************************************************************/
+-->
+  <zorba:iterator name="IsCommentPositionIterator">
+
+    <zorba:description author="Federico Cavalieri"></zorba:description>
+
+    <zorba:function>
+      <zorba:signature localname="is-comment" prefix="fn-zorba-pos">
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:output>xs:boolean</zorba:output>
+      </zorba:signature>
+    </zorba:function>
+
+  </zorba:iterator>
+  
+    <!--
+/*******************************************************************************
+********************************************************************************/
+-->
+  <zorba:iterator name="IsDocumentPositionIterator">
+
+    <zorba:description author="Federico Cavalieri"></zorba:description>
+
+    <zorba:function>
+      <zorba:signature localname="is-document" prefix="fn-zorba-pos">
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:output>xs:boolean</zorba:output>
+      </zorba:signature>
+    </zorba:function>
+
+  </zorba:iterator>
+  
+    <!--
+/*******************************************************************************
+********************************************************************************/
+-->
+  <zorba:iterator name="IsElementPositionIterator">
+
+    <zorba:description author="Federico Cavalieri"></zorba:description>
+
+    <zorba:function>
+      <zorba:signature localname="is-element" prefix="fn-zorba-pos">
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:output>xs:boolean</zorba:output>
+      </zorba:signature>
+    </zorba:function>
+
+  </zorba:iterator>
+  
+    <!--
+/*******************************************************************************
+********************************************************************************/
+-->
+  <zorba:iterator name="IsProcessingInstructionPositionIterator">
+
+    <zorba:description author="Federico Cavalieri"></zorba:description>
+
+    <zorba:function>
+      <zorba:signature localname="is-processing-instruction" prefix="fn-zorba-pos">
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:output>xs:boolean</zorba:output>
+      </zorba:signature>
+    </zorba:function>
+
+  </zorba:iterator>
+  
+    <!--
+/*******************************************************************************
+********************************************************************************/
+-->
+  <zorba:iterator name="IsTextPositionIterator">
+
+    <zorba:description author="Federico Cavalieri"></zorba:description>
+
+    <zorba:function>
+      <zorba:signature localname="is-text" prefix="fn-zorba-pos">
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:output>xs:boolean</zorba:output>
+      </zorba:signature>
+    </zorba:function>
+
+  </zorba:iterator>
+
+  <!--
+/*******************************************************************************
+********************************************************************************/
+-->
+  <zorba:iterator name="IsSiblingPositionIterator">
+
+    <zorba:description author="Federico Cavalieri"></zorba:description>
+
+    <zorba:function>
+      <zorba:signature localname="sibling-of" prefix="fn-zorba-pos">
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:output>xs:boolean</zorba:output>
+      </zorba:signature>
+    </zorba:function>
+
+  </zorba:iterator>
+
+  <!--
+/*******************************************************************************
+********************************************************************************/
+-->
+  <zorba:iterator name="InSameTreePositionIterator">
+
+    <zorba:description author="Federico Cavalieri"></zorba:description>
+
+    <zorba:function>
+      <zorba:signature localname="in-same-tree-of" prefix="fn-zorba-pos">
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:output>xs:boolean</zorba:output>
+      </zorba:signature>
+    </zorba:function>
+
+  </zorba:iterator>
+  
+  <!--
+/*******************************************************************************
+********************************************************************************/
+-->
+  <zorba:iterator name="InCollectionPositionIterator">
+
+    <zorba:description author="Federico Cavalieri"></zorba:description>
+
+    <zorba:function>
+      <zorba:signature localname="in-collection" prefix="fn-zorba-pos">
+        <zorba:param>xs:anyURI</zorba:param>        
+        <zorba:output>xs:boolean</zorba:output>
+      </zorba:signature>
+    </zorba:function>
+
+  </zorba:iterator>
+  
+  <!--
+/*******************************************************************************
+********************************************************************************/
+-->
+  <zorba:iterator name="InSameCollectionPositionIterator">
+
+    <zorba:description author="Federico Cavalieri"></zorba:description>
+
+    <zorba:function>
+      <zorba:signature localname="in-same-collection-of" prefix="fn-zorba-pos">
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:param>xs:anyURI</zorba:param>
+        <zorba:output>xs:boolean</zorba:output>
+      </zorba:signature>
+    </zorba:function>
+
+  </zorba:iterator>
+  
+</zorba:iterators>

=== modified file 'src/runtime/store/maps_impl.cpp'
--- src/runtime/store/maps_impl.cpp	2011-08-17 23:04:48 +0000
+++ src/runtime/store/maps_impl.cpp	2011-10-27 20:59:25 +0000
@@ -241,7 +241,11 @@
   {
     throw XQUERY_EXCEPTION(
       zerr::ZDDY0025_INDEX_WRONG_NUMBER_OF_PROBE_ARGS,
-      ERROR_PARAMS( lQName->getStringValue() ),
+      ERROR_PARAMS(
+        lQName->getStringValue(),
+        "map",
+        theChildren.size() - 1,
+        lSpec.getNumColumns() ),
       ERROR_LOC( loc )
     );
   }
@@ -316,7 +320,11 @@
   {
     throw XQUERY_EXCEPTION(
       zerr::ZDDY0025_INDEX_WRONG_NUMBER_OF_PROBE_ARGS,
-      ERROR_PARAMS( lQName->getStringValue() ),
+      ERROR_PARAMS(
+        lQName->getStringValue(),
+        "map",
+        theChildren.size() - 2,
+        lSpec.getNumColumns() ),
       ERROR_LOC( loc )
     );
   }
@@ -386,7 +394,12 @@
   {
     throw XQUERY_EXCEPTION(
       zerr::ZDDY0025_INDEX_WRONG_NUMBER_OF_PROBE_ARGS,
-      ERROR_PARAMS( lQName->getStringValue() ),
+      ERROR_PARAMS(
+        lQName->getStringValue(),
+        "map",
+        theChildren.size() - 1,
+        lSpec.getNumColumns()
+      ),
       ERROR_LOC( loc )
     );
   }

=== modified file 'src/runtime/visitors/pregenerated/planiter_visitor.h'
--- src/runtime/visitors/pregenerated/planiter_visitor.h	2011-10-19 15:28:51 +0000
+++ src/runtime/visitors/pregenerated/planiter_visitor.h	2011-10-27 20:59:25 +0000
@@ -303,6 +303,54 @@
 
     class FrexpIterator;
 
+    class NodePositionIterator;
+
+    class IsAncestorPositionIterator;
+
+    class IsFollowingSiblingPositionIterator;
+
+    class IsFollowingPositionIterator;
+
+    class IsInSubtreeOfPositionIterator;
+
+    class IsDescendantPositionIterator;
+
+    class IsPrecedingSiblingPositionIterator;
+
+    class IsPrecedingPositionIterator;
+
+    class IsChildPositionIterator;
+
+    class IsAttributeOfPositionIterator;
+
+    class IsParentPositionIterator;
+
+    class IsPrecedingInDocumentOrderPositionIterator;
+
+    class IsFollowingInDocumentOrderPositionIterator;
+
+    class LevelPositionIterator;
+
+    class IsAttributePositionIterator;
+
+    class IsCommentPositionIterator;
+
+    class IsDocumentPositionIterator;
+
+    class IsElementPositionIterator;
+
+    class IsProcessingInstructionPositionIterator;
+
+    class IsTextPositionIterator;
+
+    class IsSiblingPositionIterator;
+
+    class InSameTreePositionIterator;
+
+    class InCollectionPositionIterator;
+
+    class InSameCollectionPositionIterator;
+
     class NodeReferenceIterator;
 
     class NodeByReferenceIterator;
@@ -955,6 +1003,78 @@
     virtual void beginVisit ( const FrexpIterator& ) = 0;
     virtual void endVisit   ( const FrexpIterator& ) = 0;
 
+    virtual void beginVisit ( const NodePositionIterator& ) = 0;
+    virtual void endVisit   ( const NodePositionIterator& ) = 0;
+
+    virtual void beginVisit ( const IsAncestorPositionIterator& ) = 0;
+    virtual void endVisit   ( const IsAncestorPositionIterator& ) = 0;
+
+    virtual void beginVisit ( const IsFollowingSiblingPositionIterator& ) = 0;
+    virtual void endVisit   ( const IsFollowingSiblingPositionIterator& ) = 0;
+
+    virtual void beginVisit ( const IsFollowingPositionIterator& ) = 0;
+    virtual void endVisit   ( const IsFollowingPositionIterator& ) = 0;
+
+    virtual void beginVisit ( const IsInSubtreeOfPositionIterator& ) = 0;
+    virtual void endVisit   ( const IsInSubtreeOfPositionIterator& ) = 0;
+
+    virtual void beginVisit ( const IsDescendantPositionIterator& ) = 0;
+    virtual void endVisit   ( const IsDescendantPositionIterator& ) = 0;
+
+    virtual void beginVisit ( const IsPrecedingSiblingPositionIterator& ) = 0;
+    virtual void endVisit   ( const IsPrecedingSiblingPositionIterator& ) = 0;
+
+    virtual void beginVisit ( const IsPrecedingPositionIterator& ) = 0;
+    virtual void endVisit   ( const IsPrecedingPositionIterator& ) = 0;
+
+    virtual void beginVisit ( const IsChildPositionIterator& ) = 0;
+    virtual void endVisit   ( const IsChildPositionIterator& ) = 0;
+
+    virtual void beginVisit ( const IsAttributeOfPositionIterator& ) = 0;
+    virtual void endVisit   ( const IsAttributeOfPositionIterator& ) = 0;
+
+    virtual void beginVisit ( const IsParentPositionIterator& ) = 0;
+    virtual void endVisit   ( const IsParentPositionIterator& ) = 0;
+
+    virtual void beginVisit ( const IsPrecedingInDocumentOrderPositionIterator& ) = 0;
+    virtual void endVisit   ( const IsPrecedingInDocumentOrderPositionIterator& ) = 0;
+
+    virtual void beginVisit ( const IsFollowingInDocumentOrderPositionIterator& ) = 0;
+    virtual void endVisit   ( const IsFollowingInDocumentOrderPositionIterator& ) = 0;
+
+    virtual void beginVisit ( const LevelPositionIterator& ) = 0;
+    virtual void endVisit   ( const LevelPositionIterator& ) = 0;
+
+    virtual void beginVisit ( const IsAttributePositionIterator& ) = 0;
+    virtual void endVisit   ( const IsAttributePositionIterator& ) = 0;
+
+    virtual void beginVisit ( const IsCommentPositionIterator& ) = 0;
+    virtual void endVisit   ( const IsCommentPositionIterator& ) = 0;
+
+    virtual void beginVisit ( const IsDocumentPositionIterator& ) = 0;
+    virtual void endVisit   ( const IsDocumentPositionIterator& ) = 0;
+
+    virtual void beginVisit ( const IsElementPositionIterator& ) = 0;
+    virtual void endVisit   ( const IsElementPositionIterator& ) = 0;
+
+    virtual void beginVisit ( const IsProcessingInstructionPositionIterator& ) = 0;
+    virtual void endVisit   ( const IsProcessingInstructionPositionIterator& ) = 0;
+
+    virtual void beginVisit ( const IsTextPositionIterator& ) = 0;
+    virtual void endVisit   ( const IsTextPositionIterator& ) = 0;
+
+    virtual void beginVisit ( const IsSiblingPositionIterator& ) = 0;
+    virtual void endVisit   ( const IsSiblingPositionIterator& ) = 0;
+
+    virtual void beginVisit ( const InSameTreePositionIterator& ) = 0;
+    virtual void endVisit   ( const InSameTreePositionIterator& ) = 0;
+
+    virtual void beginVisit ( const InCollectionPositionIterator& ) = 0;
+    virtual void endVisit   ( const InCollectionPositionIterator& ) = 0;
+
+    virtual void beginVisit ( const InSameCollectionPositionIterator& ) = 0;
+    virtual void endVisit   ( const InSameCollectionPositionIterator& ) = 0;
+
     virtual void beginVisit ( const NodeReferenceIterator& ) = 0;
     virtual void endVisit   ( const NodeReferenceIterator& ) = 0;
 

=== modified file 'src/runtime/visitors/pregenerated/printer_visitor.cpp'
--- src/runtime/visitors/pregenerated/printer_visitor.cpp	2011-10-19 15:28:51 +0000
+++ src/runtime/visitors/pregenerated/printer_visitor.cpp	2011-10-27 20:59:25 +0000
@@ -51,6 +51,7 @@
 #include "runtime/indexing/ic_ddl.h"
 #include "runtime/introspection/sctx.h"
 #include "runtime/maths/maths.h"
+#include "runtime/nodes/node_position.h"
 #include "runtime/nodes/nodes.h"
 #include "runtime/numerics/numerics.h"
 #include "runtime/parsing_and_serializing/parse_fragment.h"
@@ -2013,6 +2014,342 @@
 // </FrexpIterator>
 
 
+// <NodePositionIterator>
+void PrinterVisitor::beginVisit ( const NodePositionIterator& a) {
+  thePrinter.startBeginVisit("NodePositionIterator", ++theId);
+  printCommons( &a, theId );
+  thePrinter.endBeginVisit( theId );
+}
+
+void PrinterVisitor::endVisit ( const NodePositionIterator& ) {
+  thePrinter.startEndVisit();
+  thePrinter.endEndVisit();
+}
+// </NodePositionIterator>
+
+
+// <IsAncestorPositionIterator>
+void PrinterVisitor::beginVisit ( const IsAncestorPositionIterator& a) {
+  thePrinter.startBeginVisit("IsAncestorPositionIterator", ++theId);
+  printCommons( &a, theId );
+  thePrinter.endBeginVisit( theId );
+}
+
+void PrinterVisitor::endVisit ( const IsAncestorPositionIterator& ) {
+  thePrinter.startEndVisit();
+  thePrinter.endEndVisit();
+}
+// </IsAncestorPositionIterator>
+
+
+// <IsFollowingSiblingPositionIterator>
+void PrinterVisitor::beginVisit ( const IsFollowingSiblingPositionIterator& a) {
+  thePrinter.startBeginVisit("IsFollowingSiblingPositionIterator", ++theId);
+  printCommons( &a, theId );
+  thePrinter.endBeginVisit( theId );
+}
+
+void PrinterVisitor::endVisit ( const IsFollowingSiblingPositionIterator& ) {
+  thePrinter.startEndVisit();
+  thePrinter.endEndVisit();
+}
+// </IsFollowingSiblingPositionIterator>
+
+
+// <IsFollowingPositionIterator>
+void PrinterVisitor::beginVisit ( const IsFollowingPositionIterator& a) {
+  thePrinter.startBeginVisit("IsFollowingPositionIterator", ++theId);
+  printCommons( &a, theId );
+  thePrinter.endBeginVisit( theId );
+}
+
+void PrinterVisitor::endVisit ( const IsFollowingPositionIterator& ) {
+  thePrinter.startEndVisit();
+  thePrinter.endEndVisit();
+}
+// </IsFollowingPositionIterator>
+
+
+// <IsInSubtreeOfPositionIterator>
+void PrinterVisitor::beginVisit ( const IsInSubtreeOfPositionIterator& a) {
+  thePrinter.startBeginVisit("IsInSubtreeOfPositionIterator", ++theId);
+  printCommons( &a, theId );
+  thePrinter.endBeginVisit( theId );
+}
+
+void PrinterVisitor::endVisit ( const IsInSubtreeOfPositionIterator& ) {
+  thePrinter.startEndVisit();
+  thePrinter.endEndVisit();
+}
+// </IsInSubtreeOfPositionIterator>
+
+
+// <IsDescendantPositionIterator>
+void PrinterVisitor::beginVisit ( const IsDescendantPositionIterator& a) {
+  thePrinter.startBeginVisit("IsDescendantPositionIterator", ++theId);
+  printCommons( &a, theId );
+  thePrinter.endBeginVisit( theId );
+}
+
+void PrinterVisitor::endVisit ( const IsDescendantPositionIterator& ) {
+  thePrinter.startEndVisit();
+  thePrinter.endEndVisit();
+}
+// </IsDescendantPositionIterator>
+
+
+// <IsPrecedingSiblingPositionIterator>
+void PrinterVisitor::beginVisit ( const IsPrecedingSiblingPositionIterator& a) {
+  thePrinter.startBeginVisit("IsPrecedingSiblingPositionIterator", ++theId);
+  printCommons( &a, theId );
+  thePrinter.endBeginVisit( theId );
+}
+
+void PrinterVisitor::endVisit ( const IsPrecedingSiblingPositionIterator& ) {
+  thePrinter.startEndVisit();
+  thePrinter.endEndVisit();
+}
+// </IsPrecedingSiblingPositionIterator>
+
+
+// <IsPrecedingPositionIterator>
+void PrinterVisitor::beginVisit ( const IsPrecedingPositionIterator& a) {
+  thePrinter.startBeginVisit("IsPrecedingPositionIterator", ++theId);
+  printCommons( &a, theId );
+  thePrinter.endBeginVisit( theId );
+}
+
+void PrinterVisitor::endVisit ( const IsPrecedingPositionIterator& ) {
+  thePrinter.startEndVisit();
+  thePrinter.endEndVisit();
+}
+// </IsPrecedingPositionIterator>
+
+
+// <IsChildPositionIterator>
+void PrinterVisitor::beginVisit ( const IsChildPositionIterator& a) {
+  thePrinter.startBeginVisit("IsChildPositionIterator", ++theId);
+  printCommons( &a, theId );
+  thePrinter.endBeginVisit( theId );
+}
+
+void PrinterVisitor::endVisit ( const IsChildPositionIterator& ) {
+  thePrinter.startEndVisit();
+  thePrinter.endEndVisit();
+}
+// </IsChildPositionIterator>
+
+
+// <IsAttributeOfPositionIterator>
+void PrinterVisitor::beginVisit ( const IsAttributeOfPositionIterator& a) {
+  thePrinter.startBeginVisit("IsAttributeOfPositionIterator", ++theId);
+  printCommons( &a, theId );
+  thePrinter.endBeginVisit( theId );
+}
+
+void PrinterVisitor::endVisit ( const IsAttributeOfPositionIterator& ) {
+  thePrinter.startEndVisit();
+  thePrinter.endEndVisit();
+}
+// </IsAttributeOfPositionIterator>
+
+
+// <IsParentPositionIterator>
+void PrinterVisitor::beginVisit ( const IsParentPositionIterator& a) {
+  thePrinter.startBeginVisit("IsParentPositionIterator", ++theId);
+  printCommons( &a, theId );
+  thePrinter.endBeginVisit( theId );
+}
+
+void PrinterVisitor::endVisit ( const IsParentPositionIterator& ) {
+  thePrinter.startEndVisit();
+  thePrinter.endEndVisit();
+}
+// </IsParentPositionIterator>
+
+
+// <IsPrecedingInDocumentOrderPositionIterator>
+void PrinterVisitor::beginVisit ( const IsPrecedingInDocumentOrderPositionIterator& a) {
+  thePrinter.startBeginVisit("IsPrecedingInDocumentOrderPositionIterator", ++theId);
+  printCommons( &a, theId );
+  thePrinter.endBeginVisit( theId );
+}
+
+void PrinterVisitor::endVisit ( const IsPrecedingInDocumentOrderPositionIterator& ) {
+  thePrinter.startEndVisit();
+  thePrinter.endEndVisit();
+}
+// </IsPrecedingInDocumentOrderPositionIterator>
+
+
+// <IsFollowingInDocumentOrderPositionIterator>
+void PrinterVisitor::beginVisit ( const IsFollowingInDocumentOrderPositionIterator& a) {
+  thePrinter.startBeginVisit("IsFollowingInDocumentOrderPositionIterator", ++theId);
+  printCommons( &a, theId );
+  thePrinter.endBeginVisit( theId );
+}
+
+void PrinterVisitor::endVisit ( const IsFollowingInDocumentOrderPositionIterator& ) {
+  thePrinter.startEndVisit();
+  thePrinter.endEndVisit();
+}
+// </IsFollowingInDocumentOrderPositionIterator>
+
+
+// <LevelPositionIterator>
+void PrinterVisitor::beginVisit ( const LevelPositionIterator& a) {
+  thePrinter.startBeginVisit("LevelPositionIterator", ++theId);
+  printCommons( &a, theId );
+  thePrinter.endBeginVisit( theId );
+}
+
+void PrinterVisitor::endVisit ( const LevelPositionIterator& ) {
+  thePrinter.startEndVisit();
+  thePrinter.endEndVisit();
+}
+// </LevelPositionIterator>
+
+
+// <IsAttributePositionIterator>
+void PrinterVisitor::beginVisit ( const IsAttributePositionIterator& a) {
+  thePrinter.startBeginVisit("IsAttributePositionIterator", ++theId);
+  printCommons( &a, theId );
+  thePrinter.endBeginVisit( theId );
+}
+
+void PrinterVisitor::endVisit ( const IsAttributePositionIterator& ) {
+  thePrinter.startEndVisit();
+  thePrinter.endEndVisit();
+}
+// </IsAttributePositionIterator>
+
+
+// <IsCommentPositionIterator>
+void PrinterVisitor::beginVisit ( const IsCommentPositionIterator& a) {
+  thePrinter.startBeginVisit("IsCommentPositionIterator", ++theId);
+  printCommons( &a, theId );
+  thePrinter.endBeginVisit( theId );
+}
+
+void PrinterVisitor::endVisit ( const IsCommentPositionIterator& ) {
+  thePrinter.startEndVisit();
+  thePrinter.endEndVisit();
+}
+// </IsCommentPositionIterator>
+
+
+// <IsDocumentPositionIterator>
+void PrinterVisitor::beginVisit ( const IsDocumentPositionIterator& a) {
+  thePrinter.startBeginVisit("IsDocumentPositionIterator", ++theId);
+  printCommons( &a, theId );
+  thePrinter.endBeginVisit( theId );
+}
+
+void PrinterVisitor::endVisit ( const IsDocumentPositionIterator& ) {
+  thePrinter.startEndVisit();
+  thePrinter.endEndVisit();
+}
+// </IsDocumentPositionIterator>
+
+
+// <IsElementPositionIterator>
+void PrinterVisitor::beginVisit ( const IsElementPositionIterator& a) {
+  thePrinter.startBeginVisit("IsElementPositionIterator", ++theId);
+  printCommons( &a, theId );
+  thePrinter.endBeginVisit( theId );
+}
+
+void PrinterVisitor::endVisit ( const IsElementPositionIterator& ) {
+  thePrinter.startEndVisit();
+  thePrinter.endEndVisit();
+}
+// </IsElementPositionIterator>
+
+
+// <IsProcessingInstructionPositionIterator>
+void PrinterVisitor::beginVisit ( const IsProcessingInstructionPositionIterator& a) {
+  thePrinter.startBeginVisit("IsProcessingInstructionPositionIterator", ++theId);
+  printCommons( &a, theId );
+  thePrinter.endBeginVisit( theId );
+}
+
+void PrinterVisitor::endVisit ( const IsProcessingInstructionPositionIterator& ) {
+  thePrinter.startEndVisit();
+  thePrinter.endEndVisit();
+}
+// </IsProcessingInstructionPositionIterator>
+
+
+// <IsTextPositionIterator>
+void PrinterVisitor::beginVisit ( const IsTextPositionIterator& a) {
+  thePrinter.startBeginVisit("IsTextPositionIterator", ++theId);
+  printCommons( &a, theId );
+  thePrinter.endBeginVisit( theId );
+}
+
+void PrinterVisitor::endVisit ( const IsTextPositionIterator& ) {
+  thePrinter.startEndVisit();
+  thePrinter.endEndVisit();
+}
+// </IsTextPositionIterator>
+
+
+// <IsSiblingPositionIterator>
+void PrinterVisitor::beginVisit ( const IsSiblingPositionIterator& a) {
+  thePrinter.startBeginVisit("IsSiblingPositionIterator", ++theId);
+  printCommons( &a, theId );
+  thePrinter.endBeginVisit( theId );
+}
+
+void PrinterVisitor::endVisit ( const IsSiblingPositionIterator& ) {
+  thePrinter.startEndVisit();
+  thePrinter.endEndVisit();
+}
+// </IsSiblingPositionIterator>
+
+
+// <InSameTreePositionIterator>
+void PrinterVisitor::beginVisit ( const InSameTreePositionIterator& a) {
+  thePrinter.startBeginVisit("InSameTreePositionIterator", ++theId);
+  printCommons( &a, theId );
+  thePrinter.endBeginVisit( theId );
+}
+
+void PrinterVisitor::endVisit ( const InSameTreePositionIterator& ) {
+  thePrinter.startEndVisit();
+  thePrinter.endEndVisit();
+}
+// </InSameTreePositionIterator>
+
+
+// <InCollectionPositionIterator>
+void PrinterVisitor::beginVisit ( const InCollectionPositionIterator& a) {
+  thePrinter.startBeginVisit("InCollectionPositionIterator", ++theId);
+  printCommons( &a, theId );
+  thePrinter.endBeginVisit( theId );
+}
+
+void PrinterVisitor::endVisit ( const InCollectionPositionIterator& ) {
+  thePrinter.startEndVisit();
+  thePrinter.endEndVisit();
+}
+// </InCollectionPositionIterator>
+
+
+// <InSameCollectionPositionIterator>
+void PrinterVisitor::beginVisit ( const InSameCollectionPositionIterator& a) {
+  thePrinter.startBeginVisit("InSameCollectionPositionIterator", ++theId);
+  printCommons( &a, theId );
+  thePrinter.endBeginVisit( theId );
+}
+
+void PrinterVisitor::endVisit ( const InSameCollectionPositionIterator& ) {
+  thePrinter.startEndVisit();
+  thePrinter.endEndVisit();
+}
+// </InSameCollectionPositionIterator>
+
+
 // <NodeReferenceIterator>
 void PrinterVisitor::beginVisit ( const NodeReferenceIterator& a) {
   thePrinter.startBeginVisit("NodeReferenceIterator", ++theId);

=== modified file 'src/runtime/visitors/pregenerated/printer_visitor.h'
--- src/runtime/visitors/pregenerated/printer_visitor.h	2011-10-19 15:28:51 +0000
+++ src/runtime/visitors/pregenerated/printer_visitor.h	2011-10-27 20:59:25 +0000
@@ -457,6 +457,78 @@
     void beginVisit( const FrexpIterator& );
     void endVisit  ( const FrexpIterator& );
 
+    void beginVisit( const NodePositionIterator& );
+    void endVisit  ( const NodePositionIterator& );
+
+    void beginVisit( const IsAncestorPositionIterator& );
+    void endVisit  ( const IsAncestorPositionIterator& );
+
+    void beginVisit( const IsFollowingSiblingPositionIterator& );
+    void endVisit  ( const IsFollowingSiblingPositionIterator& );
+
+    void beginVisit( const IsFollowingPositionIterator& );
+    void endVisit  ( const IsFollowingPositionIterator& );
+
+    void beginVisit( const IsInSubtreeOfPositionIterator& );
+    void endVisit  ( const IsInSubtreeOfPositionIterator& );
+
+    void beginVisit( const IsDescendantPositionIterator& );
+    void endVisit  ( const IsDescendantPositionIterator& );
+
+    void beginVisit( const IsPrecedingSiblingPositionIterator& );
+    void endVisit  ( const IsPrecedingSiblingPositionIterator& );
+
+    void beginVisit( const IsPrecedingPositionIterator& );
+    void endVisit  ( const IsPrecedingPositionIterator& );
+
+    void beginVisit( const IsChildPositionIterator& );
+    void endVisit  ( const IsChildPositionIterator& );
+
+    void beginVisit( const IsAttributeOfPositionIterator& );
+    void endVisit  ( const IsAttributeOfPositionIterator& );
+
+    void beginVisit( const IsParentPositionIterator& );
+    void endVisit  ( const IsParentPositionIterator& );
+
+    void beginVisit( const IsPrecedingInDocumentOrderPositionIterator& );
+    void endVisit  ( const IsPrecedingInDocumentOrderPositionIterator& );
+
+    void beginVisit( const IsFollowingInDocumentOrderPositionIterator& );
+    void endVisit  ( const IsFollowingInDocumentOrderPositionIterator& );
+
+    void beginVisit( const LevelPositionIterator& );
+    void endVisit  ( const LevelPositionIterator& );
+
+    void beginVisit( const IsAttributePositionIterator& );
+    void endVisit  ( const IsAttributePositionIterator& );
+
+    void beginVisit( const IsCommentPositionIterator& );
+    void endVisit  ( const IsCommentPositionIterator& );
+
+    void beginVisit( const IsDocumentPositionIterator& );
+    void endVisit  ( const IsDocumentPositionIterator& );
+
+    void beginVisit( const IsElementPositionIterator& );
+    void endVisit  ( const IsElementPositionIterator& );
+
+    void beginVisit( const IsProcessingInstructionPositionIterator& );
+    void endVisit  ( const IsProcessingInstructionPositionIterator& );
+
+    void beginVisit( const IsTextPositionIterator& );
+    void endVisit  ( const IsTextPositionIterator& );
+
+    void beginVisit( const IsSiblingPositionIterator& );
+    void endVisit  ( const IsSiblingPositionIterator& );
+
+    void beginVisit( const InSameTreePositionIterator& );
+    void endVisit  ( const InSameTreePositionIterator& );
+
+    void beginVisit( const InCollectionPositionIterator& );
+    void endVisit  ( const InCollectionPositionIterator& );
+
+    void beginVisit( const InSameCollectionPositionIterator& );
+    void endVisit  ( const InSameCollectionPositionIterator& );
+
     void beginVisit( const NodeReferenceIterator& );
     void endVisit  ( const NodeReferenceIterator& );
 

=== modified file 'src/store/api/item.h'
--- src/store/api/item.h	2011-10-05 17:49:48 +0000
+++ src/store/api/item.h	2011-10-27 20:59:25 +0000
@@ -662,6 +662,12 @@
    *
    */
   virtual bool
+  isInSubtreeOf(const store::Item_t&) const;
+
+  /**
+   *
+   */
+  virtual bool
   isDescendant(const store::Item_t&) const;
 
   /**
@@ -686,17 +692,95 @@
    *
    */
   virtual bool
+  isAttribute(const store::Item_t&) const;
+
+  /**
+   *
+   */
+  virtual bool
   isParent(const store::Item_t&) const;
 
   /**
    *
    */
+  virtual bool
+  isPrecedingInDocumentOrder(const store::Item_t&) const;
+
+  /**
+   *
+   */
+  virtual bool
+  isFollowingInDocumentOrder(const store::Item_t&) const;
+
+  /**
+   *
+   */
   virtual store::Item_t
   getLevel() const;
 
   /**
    *
    */
+  virtual bool
+  isSibling(const store::Item_t&) const;
+
+  /**
+   *
+   */
+  virtual bool
+  isAttribute() const;
+
+  /**
+   *
+   */
+  virtual bool
+  isComment() const;
+
+  /**
+   *
+   */
+  virtual bool
+  isDocument() const;
+
+  /**
+   *
+   */
+  virtual bool
+  isElement() const;
+
+  /**
+   *
+   */
+  virtual bool
+  isProcessingInstruction() const;
+
+  /**
+   *
+   */
+  virtual bool
+  isText() const;
+
+  /**
+   *
+   */
+  virtual bool
+  inSameTree(const store::Item_t&) const;
+
+  /**
+   *
+   */
+  virtual bool
+  inCollection() const;
+
+  /**
+   *
+   */
+  virtual bool
+  inSameCollection(const store::Item_t&) const;
+
+  /**
+   *
+   */
   virtual store::Item_t
   leastCommonAncestor(const store::Item_t&) const;
 

=== modified file 'src/store/api/store.h'
--- src/store/api/store.h	2011-10-10 12:56:57 +0000
+++ src/store/api/store.h	2011-10-27 20:59:25 +0000
@@ -115,6 +115,15 @@
    */
   virtual bool getNodeByReference(store::Item_t& result, const zstring& reference) = 0;
 
+  /* ------------------ Structural Information Management ----------------------*/
+
+  /**
+   * Computes the structural information of the passed item.
+   *
+   * @param item XDM item
+   * @return Returns an item of type xs:uri
+   */
+  virtual bool getStructuralInformation(Item_t& result, const Item* node) = 0;
 
   /* --------------------------- Node Id Management ---------------------------*/
 

=== modified file 'src/store/naive/atomic_items.cpp'
--- src/store/naive/atomic_items.cpp	2011-09-30 14:06:33 +0000
+++ src/store/naive/atomic_items.cpp	2011-10-27 20:59:25 +0000
@@ -14,6 +14,7 @@
  * limitations under the License.
  */
 #include "stdafx.h"
+#include <limits.h>
 
 #include <zorba/internal/unique_ptr.h>
 
@@ -38,6 +39,7 @@
 #include "store/naive/item_iterator.h"
 #include "store/naive/node_items.h"
 #include "store/naive/atomic_items.h"
+#include "store/naive/ordpath.h"
 
 #include "util/ascii_util.h"
 #include "util/string_util.h"
@@ -562,6 +564,18 @@
 }
 
 
+bool UntypedAtomicItem::equals(
+    const store::Item* other,
+    long timezone,
+    const XQPCollator* collation) const
+{
+  if (collation == NULL || collation->doMemCmp())
+    return theValue == other->getString();
+
+  return (utf8::compare(theValue, other->getString(), collation) == 0);
+}
+
+
 store::Item_t UntypedAtomicItem::getEBV() const
 {
   bool b = ! ( theValue == "" );
@@ -598,11 +612,13 @@
   GET_STORE().getQNamePool().remove(this);
 }
 
+
 QNameItem* QNameItem::getNormalized() const
 {
   return (isNormalized() ? const_cast<QNameItem*>(this) : theNormQName.getp());
 }
 
+
 uint32_t QNameItem::hash(long timezone, const XQPCollator* aCollation) const
 {
   const void* tmp = getNormalized();
@@ -618,22 +634,20 @@
 
 store::Item_t QNameItem::getEBV() const
 {
-  throw XQUERY_EXCEPTION(
-    err::FORG0006,
-    ERROR_PARAMS(
-      ZED( OperationNotDef_23 ), ZED( EffectiveBooleanValue ), "QName"
-    )
-  );
+  throw XQUERY_EXCEPTION(err::FORG0006,
+  ERROR_PARAMS(ZED(OperationNotDef_23), ZED(EffectiveBooleanValue), "QName"));
 }
 
+
 bool QNameItem::equals(
-        const store::Item* item,
-        long timezone,
-        const XQPCollator* aCollation) const
+    const store::Item* item,
+    long timezone,
+    const XQPCollator* aCollation) const
 {
   return (getNormalized() == static_cast<const QNameItem*>(item)->getNormalized());
 }
 
+
 zstring QNameItem::getStringValue() const
 {
   if (thePrefix.empty())
@@ -742,7 +756,8 @@
                           long timezone,
                           const XQPCollator* aCollation) const
 {
-  return (theQName->getNormalized() == static_cast<const NotationItem*>(item)->theQName->getNormalized());
+  return (theQName->getNormalized() == 
+          static_cast<const NotationItem*>(item)->theQName->getNormalized());
 }
 
 
@@ -817,6 +832,723 @@
 }
 
 
+bool AnyUriItem::isAncestor(const store::Item_t& aOther) const
+{
+  store::Item_t lThisUri;
+  zstring tempValue=theValue;
+  GET_FACTORY().createStructuralAnyURI(lThisUri, tempValue);
+  return lThisUri->isAncestor(aOther);
+}
+
+
+bool AnyUriItem::isFollowingSibling(const store::Item_t& aOther) const
+{
+  store::Item_t lThisUri;
+  zstring tempValue=theValue;
+  GET_FACTORY().createStructuralAnyURI(lThisUri, tempValue);
+  return lThisUri->isFollowingSibling(aOther);
+}
+
+
+bool AnyUriItem::isFollowing(const store::Item_t& aOther) const
+{
+  store::Item_t lThisUri;
+  zstring tempValue=theValue;
+  GET_FACTORY().createStructuralAnyURI(lThisUri, tempValue);
+  return lThisUri->isFollowing(aOther);
+}
+
+
+bool AnyUriItem::isDescendant(const store::Item_t& aOther) const
+{
+  store::Item_t lThisUri;
+  zstring tempValue=theValue;
+  GET_FACTORY().createStructuralAnyURI(lThisUri, tempValue);
+  return lThisUri->isDescendant(aOther);
+}
+
+
+bool AnyUriItem::isInSubtreeOf(const store::Item_t& aOther) const
+{
+  store::Item_t lThisUri;
+  zstring tempValue=theValue;
+  GET_FACTORY().createStructuralAnyURI(lThisUri, tempValue);
+  return lThisUri->isInSubtreeOf(aOther);
+}
+
+
+bool AnyUriItem::isPrecedingSibling(const store::Item_t& aOther) const
+{
+  store::Item_t lThisUri;
+  zstring tempValue=theValue;
+  GET_FACTORY().createStructuralAnyURI(lThisUri, tempValue);
+  return lThisUri->isPrecedingSibling(aOther);
+}
+
+
+bool AnyUriItem::isPreceding(const store::Item_t& aOther) const
+{
+  store::Item_t lThisUri;
+  zstring tempValue=theValue;
+  GET_FACTORY().createStructuralAnyURI(lThisUri, tempValue);
+  return lThisUri->isPreceding(aOther);
+}
+
+
+bool AnyUriItem::isChild(const store::Item_t& aOther) const
+{
+  store::Item_t lThisUri;
+  zstring tempValue=theValue;
+  GET_FACTORY().createStructuralAnyURI(lThisUri, tempValue);
+  return lThisUri->isChild(aOther);
+}
+
+
+bool AnyUriItem::isAttribute(const store::Item_t& aOther) const
+{
+  store::Item_t lThisUri;
+  zstring tempValue=theValue;
+  GET_FACTORY().createStructuralAnyURI(lThisUri, tempValue);
+  return lThisUri->isAttribute(aOther);
+}
+
+
+bool AnyUriItem::isParent(const store::Item_t& aOther) const
+{
+  store::Item_t lThisUri;
+  zstring tempValue=theValue;
+  GET_FACTORY().createStructuralAnyURI(lThisUri, tempValue);
+  return lThisUri->isParent(aOther);
+}
+
+
+bool AnyUriItem::isPrecedingInDocumentOrder(const store::Item_t& aOther) const
+{
+  store::Item_t lThisUri;
+  zstring tempValue=theValue;
+  GET_FACTORY().createStructuralAnyURI(lThisUri, tempValue);
+  return lThisUri->isPrecedingInDocumentOrder(aOther);
+}
+
+
+bool AnyUriItem::isFollowingInDocumentOrder(const store::Item_t& aOther) const
+{
+  store::Item_t lThisUri;
+  zstring tempValue=theValue;
+  GET_FACTORY().createStructuralAnyURI(lThisUri, tempValue);
+  return lThisUri->isFollowingInDocumentOrder(aOther);
+}
+
+
+store::Item_t AnyUriItem::getLevel() const
+{
+  store::Item_t lThisUri;
+  zstring tempValue=theValue;
+  GET_FACTORY().createStructuralAnyURI(lThisUri, tempValue);
+  return lThisUri->getLevel();
+}
+
+
+bool AnyUriItem::isAttribute() const
+{
+  store::Item_t lThisUri;
+  zstring tempValue=theValue;
+  GET_FACTORY().createStructuralAnyURI(lThisUri, tempValue);
+  return lThisUri->isAttribute();
+}
+
+
+bool AnyUriItem::isComment() const
+{
+  store::Item_t lThisUri;
+  zstring tempValue=theValue;
+  GET_FACTORY().createStructuralAnyURI(lThisUri, tempValue);
+  return lThisUri->isComment();
+}
+
+
+bool AnyUriItem::isDocument() const
+{
+  store::Item_t lThisUri;
+  zstring tempValue=theValue;
+  GET_FACTORY().createStructuralAnyURI(lThisUri, tempValue);
+  return lThisUri->isDocument();
+}
+
+
+bool AnyUriItem::isElement() const
+{
+  store::Item_t lThisUri;
+  zstring tempValue=theValue;
+  GET_FACTORY().createStructuralAnyURI(lThisUri, tempValue);
+  return lThisUri->isElement();
+}
+
+
+bool AnyUriItem::isProcessingInstruction() const
+{
+  store::Item_t lThisUri;
+  zstring tempValue=theValue;
+  GET_FACTORY().createStructuralAnyURI(lThisUri, tempValue);
+  return lThisUri->isProcessingInstruction();
+}
+
+
+bool AnyUriItem::isText() const
+{
+  store::Item_t lThisUri;
+  zstring tempValue=theValue;
+  GET_FACTORY().createStructuralAnyURI(lThisUri, tempValue);
+  return lThisUri->isText();
+}
+
+
+bool AnyUriItem::isSibling(const store::Item_t& aOther) const
+{
+  store::Item_t lThisUri;
+  zstring tempValue=theValue;
+  GET_FACTORY().createStructuralAnyURI(lThisUri, tempValue);
+  return lThisUri->isSibling(aOther);
+}
+
+
+bool AnyUriItem::inSameTree(const store::Item_t& aOther) const
+{
+  store::Item_t lThisUri;
+  zstring tempValue=theValue;
+  GET_FACTORY().createStructuralAnyURI(lThisUri, tempValue);
+  return lThisUri->inSameTree(aOther);
+}
+
+
+bool AnyUriItem::inCollection() const
+{
+  store::Item_t lThisUri;
+  zstring tempValue=theValue;
+  GET_FACTORY().createStructuralAnyURI(lThisUri, tempValue);
+  return static_cast<StructuralAnyUriItem *>(lThisUri.getp())->inCollection();
+}
+
+
+bool AnyUriItem::inSameCollection(const store::Item_t& aOther) const
+{
+  store::Item_t lThisUri;
+  zstring tempValue=theValue;
+  GET_FACTORY().createStructuralAnyURI(lThisUri, tempValue);
+  return lThisUri->inSameCollection(aOther);
+}
+
+
+/*******************************************************************************
+  class StructuralAnyUriItem
+********************************************************************************/
+
+StructuralAnyUriItem::StructuralAnyUriItem(
+    zstring& encoded,
+    ulong collectionId,
+    ulong treeId, 
+    store::StoreConsts::NodeKind nodeKind,
+    const OrdPath& ordPath)
+  :
+  theCollectionId(collectionId),
+  theTreeId(treeId),
+  theNodeKind(nodeKind),
+  theOrdPath(ordPath)
+{
+  theValue.take(encoded);
+}
+
+
+StructuralAnyUriItem::StructuralAnyUriItem(zstring& value)
+{
+  theValue.take(value);
+
+  ulong prefixlen = (ulong)strlen("zorba:");
+
+  if (strncmp(theValue.c_str(), "zorba:", prefixlen))
+    throw ZORBA_EXCEPTION(zerr::ZAPI0028_INVALID_NODE_URI, ERROR_PARAMS(theValue));
+
+  const char* start;
+
+  errno = 0;
+
+  //
+  // Decode collection id
+  //
+  start = theValue.c_str() + prefixlen;
+
+  char* next = const_cast<char*>(start);
+
+  theCollectionId = strtoul(start, &next, 10);
+
+  if (errno != 0 || start == next)
+    throw ZORBA_EXCEPTION(zerr::ZAPI0028_INVALID_NODE_URI, ERROR_PARAMS(theValue));
+
+  start = next;
+
+  if (*start != '.')
+    throw ZORBA_EXCEPTION(zerr::ZAPI0028_INVALID_NODE_URI, ERROR_PARAMS(theValue));
+
+  ++start;
+
+  //
+  // Decode tree id
+  //
+  theTreeId = strtoul(start, &next, 10);
+
+  if (errno != 0 || start == next)
+    throw ZORBA_EXCEPTION(zerr::ZAPI0028_INVALID_NODE_URI, ERROR_PARAMS(theValue));
+
+  start = next;
+
+  if (*start != '.')
+    throw ZORBA_EXCEPTION(zerr::ZAPI0028_INVALID_NODE_URI, ERROR_PARAMS(theValue));
+
+  ++start;
+
+  //
+  // Parse the node kind
+  //
+  if (*start > '0' && *start <='6')
+    theNodeKind = static_cast<store::StoreConsts::NodeKind>(*start-'0');
+  else
+    throw ZORBA_EXCEPTION(zerr::ZAPI0028_INVALID_NODE_URI, ERROR_PARAMS(theValue));
+
+  ++start;
+
+  if (*start != '.')
+    throw ZORBA_EXCEPTION(zerr::ZAPI0028_INVALID_NODE_URI, ERROR_PARAMS(theValue));
+
+  ++start;
+
+  //
+  // Decode OrdPath
+  //
+  theOrdPath = OrdPath((unsigned char*)start, (ulong)strlen(start));
+}
+
+
+bool StructuralAnyUriItem::isAncestor(const store::Item_t& aOther) const
+{
+  // Is the "other" an ancestor of "this"?
+
+  AnyUriItem* lOtherUriP = static_cast<AnyUriItem *>(aOther.getp());
+
+  if (lOtherUriP->getAnyUriTypeCode() != STRUCTURAL_INFORMATION_ANY_URI)
+  {
+    store::Item_t lOtherUri;
+    zstring tmp = lOtherUriP->theValue;
+    GET_FACTORY().createStructuralAnyURI(lOtherUri, tmp);
+    return isAncestor(lOtherUri);
+  }
+  else
+  {
+    StructuralAnyUriItem* other = static_cast<StructuralAnyUriItem*>(aOther.getp());
+
+    return 
+    (other->theCollectionId == theCollectionId &&
+     other->theTreeId == theTreeId &&
+     theOrdPath.getRelativePosition(other->theOrdPath) == OrdPath::ANCESTOR);
+  }
+}
+
+
+bool StructuralAnyUriItem::isFollowingSibling(const store::Item_t& aOther) const
+{
+  // Is the "other" a following sibling of "this"?
+
+  AnyUriItem* lOtherUriP = static_cast<AnyUriItem *>(aOther.getp());
+
+  if (lOtherUriP->getAnyUriTypeCode() != STRUCTURAL_INFORMATION_ANY_URI)
+  {
+    store::Item_t lOtherUri;
+    zstring tmp = lOtherUriP->theValue;
+    GET_FACTORY().createStructuralAnyURI(lOtherUri, tmp);
+    return isFollowingSibling(lOtherUri);
+  }
+  else
+  {
+    StructuralAnyUriItem* other = static_cast<StructuralAnyUriItem*>(aOther.getp());
+
+    return 
+    (other->theCollectionId == theCollectionId &&
+     other->theTreeId == theTreeId &&
+     other->theNodeKind != store::StoreConsts::attributeNode &&
+     theNodeKind != store::StoreConsts::attributeNode &&
+     theOrdPath.getRelativePosition2(other->theOrdPath) == OrdPath::FOLLOWING_SIBLING);
+  }
+}
+
+
+bool StructuralAnyUriItem::isFollowing(const store::Item_t& aOther) const
+{
+  // Is the "other" a following node of "this"?
+
+  AnyUriItem* lOtherUriP = static_cast<AnyUriItem *>(aOther.getp());
+
+  if (lOtherUriP->getAnyUriTypeCode() != STRUCTURAL_INFORMATION_ANY_URI)
+  {
+    store::Item_t lOtherUri;
+    zstring tmp = lOtherUriP->theValue;
+    GET_FACTORY().createStructuralAnyURI(lOtherUri, tmp);
+    return isFollowing(lOtherUri);
+  }
+  else
+  {
+    StructuralAnyUriItem* other = static_cast<StructuralAnyUriItem*>(aOther.getp());
+
+    return 
+    (other->theCollectionId == theCollectionId &&
+     other->theTreeId == theTreeId &&
+     theOrdPath.getRelativePosition(other->theOrdPath) == OrdPath::FOLLOWING);
+  }
+}
+
+
+bool StructuralAnyUriItem::isDescendant(const store::Item_t& aOther) const
+{
+  // Is the "other" a descendant of "this"?
+
+  AnyUriItem* lOtherUriP = static_cast<AnyUriItem *>(aOther.getp());
+
+  if (lOtherUriP->getAnyUriTypeCode() != STRUCTURAL_INFORMATION_ANY_URI)
+  {
+    store::Item_t lOtherUri;
+    zstring tmp = lOtherUriP->theValue;
+    GET_FACTORY().createStructuralAnyURI(lOtherUri, tmp);
+    return isDescendant(lOtherUri);
+  }
+  else
+  {
+    StructuralAnyUriItem* other = static_cast<StructuralAnyUriItem*>(aOther.getp());
+    return 
+    (other->theCollectionId == theCollectionId &&
+     other->theTreeId == theTreeId &&
+     other->theNodeKind != store::StoreConsts::attributeNode &&
+     theOrdPath.getRelativePosition(other->theOrdPath) == OrdPath::DESCENDANT);
+  }
+}
+
+
+bool StructuralAnyUriItem::isInSubtreeOf(const store::Item_t& aOther) const
+{
+  // Is the "other" in the subtree rooted at "this"?
+
+  AnyUriItem* lOtherUriP = static_cast<AnyUriItem *>(aOther.getp());
+
+  if (lOtherUriP->getAnyUriTypeCode() != STRUCTURAL_INFORMATION_ANY_URI)
+  {
+    store::Item_t lOtherUri;
+    zstring tmp = lOtherUriP->theValue;
+    GET_FACTORY().createStructuralAnyURI(lOtherUri, tmp);
+    return isInSubtreeOf(lOtherUri);
+  }
+  else
+  {
+    StructuralAnyUriItem* other = static_cast<StructuralAnyUriItem*>(aOther.getp());
+    return 
+    (other->theCollectionId == theCollectionId &&
+     other->theTreeId == theTreeId &&
+     theOrdPath.getRelativePosition(other->theOrdPath) == OrdPath::DESCENDANT);
+  }
+}
+
+
+bool StructuralAnyUriItem::isPrecedingSibling(const store::Item_t& aOther) const
+{
+  // Is the "other" a preceding sibling of "this"?
+
+  AnyUriItem* lOtherUriP = static_cast<AnyUriItem *>(aOther.getp());
+
+  if (lOtherUriP->getAnyUriTypeCode() != STRUCTURAL_INFORMATION_ANY_URI)
+  {
+    store::Item_t lOtherUri;
+    zstring tmp = lOtherUriP->theValue;
+    GET_FACTORY().createStructuralAnyURI(lOtherUri, tmp);
+    return isPrecedingSibling(lOtherUri);
+  }
+  else
+  {
+    StructuralAnyUriItem* other = static_cast<StructuralAnyUriItem*>(aOther.getp());
+    return 
+    (other->theCollectionId == theCollectionId &&
+     other->theTreeId == theTreeId &&
+     other->theNodeKind != store::StoreConsts::attributeNode &&
+     theNodeKind != store::StoreConsts::attributeNode &&
+     theOrdPath.getRelativePosition2(other->theOrdPath) == OrdPath::PRECEDING_SIBLING);
+  }
+}
+
+
+bool StructuralAnyUriItem::isPreceding(const store::Item_t& aOther) const
+{
+  // Is the "other" a preceding node of "this"?
+
+  AnyUriItem* lOtherUriP = static_cast<AnyUriItem *>(aOther.getp());
+
+  if (lOtherUriP->getAnyUriTypeCode() != STRUCTURAL_INFORMATION_ANY_URI)
+  {
+    store::Item_t lOtherUri;
+    zstring tmp = lOtherUriP->theValue;
+    GET_FACTORY().createStructuralAnyURI(lOtherUri, tmp);
+    return isPreceding(lOtherUri);
+  }
+  else
+  {
+    StructuralAnyUriItem* other = static_cast<StructuralAnyUriItem*>(aOther.getp());
+    return 
+    (other->theCollectionId == theCollectionId &&
+     other->theTreeId == theTreeId &&
+     theOrdPath.getRelativePosition(other->theOrdPath) == OrdPath::PRECEDING);
+  }
+}
+
+
+bool StructuralAnyUriItem::isChild(const store::Item_t& aOther) const
+{
+  // Is the "other" a child of "this"?
+
+  AnyUriItem* lOtherUriP = static_cast<AnyUriItem *>(aOther.getp());
+
+  if (lOtherUriP->getAnyUriTypeCode() != STRUCTURAL_INFORMATION_ANY_URI)
+  {
+    store::Item_t lOtherUri;
+    zstring tmp = lOtherUriP->theValue;
+    GET_FACTORY().createStructuralAnyURI(lOtherUri, tmp);
+    return isChild(lOtherUri);
+  }
+  else
+  {
+    StructuralAnyUriItem* other = static_cast<StructuralAnyUriItem*>(aOther.getp());
+    return 
+    (other->theCollectionId == theCollectionId &&
+     other->theTreeId == theTreeId &&
+     other->theNodeKind != store::StoreConsts::attributeNode &&
+     theOrdPath.getRelativePosition2(other->theOrdPath) == OrdPath::CHILD);
+  }
+}
+
+
+bool StructuralAnyUriItem::isAttribute(const store::Item_t& aOther) const
+{
+  // Is the "other" an attribute of "this"?
+
+  AnyUriItem* lOtherUriP = static_cast<AnyUriItem *>(aOther.getp());
+
+  if (lOtherUriP->getAnyUriTypeCode() != STRUCTURAL_INFORMATION_ANY_URI)
+  {
+    store::Item_t lOtherUri;
+    zstring tmp = lOtherUriP->theValue;
+    GET_FACTORY().createStructuralAnyURI(lOtherUri, tmp);
+    return isAttribute(lOtherUri);
+  }
+  else
+  {
+    StructuralAnyUriItem* other = static_cast<StructuralAnyUriItem*>(aOther.getp());
+    return 
+    (other->theCollectionId == theCollectionId &&
+     other->theTreeId == theTreeId &&
+     other->theNodeKind == store::StoreConsts::attributeNode &&
+     theOrdPath.getRelativePosition2(other->theOrdPath) == OrdPath::CHILD);
+  }
+}
+
+
+bool StructuralAnyUriItem::isParent(const store::Item_t& aOther) const
+{
+  // Is the "other" an parent of "this"?
+
+  AnyUriItem* lOtherUriP = static_cast<AnyUriItem *>(aOther.getp());
+
+  if (lOtherUriP->getAnyUriTypeCode() != STRUCTURAL_INFORMATION_ANY_URI)
+  {
+    store::Item_t lOtherUri;
+    zstring tmp = lOtherUriP->theValue;
+    GET_FACTORY().createStructuralAnyURI(lOtherUri, tmp);
+    return isParent(lOtherUri);
+  }
+  else
+  {
+    StructuralAnyUriItem* other = static_cast<StructuralAnyUriItem*>(aOther.getp());
+    return 
+    (other->theCollectionId == theCollectionId &&
+     other->theTreeId == theTreeId &&
+     theOrdPath.getRelativePosition2(other->theOrdPath) == OrdPath::PARENT);
+  }
+}
+
+
+bool StructuralAnyUriItem::isPrecedingInDocumentOrder(const store::Item_t& aOther) const
+{
+  AnyUriItem* lOtherUriP = static_cast<AnyUriItem *>(aOther.getp());
+
+  if (lOtherUriP->getAnyUriTypeCode() != STRUCTURAL_INFORMATION_ANY_URI)
+  {
+    store::Item_t lOtherUri;
+    zstring tmp = lOtherUriP->theValue;
+    GET_FACTORY().createStructuralAnyURI(lOtherUri, tmp);
+    return isPrecedingInDocumentOrder(lOtherUri);
+  }
+  else
+  {
+    StructuralAnyUriItem* other = static_cast<StructuralAnyUriItem*>(aOther.getp());
+    return
+    (theCollectionId > other->theCollectionId ||
+    (theCollectionId == other->theCollectionId && theTreeId > other->theTreeId) ||
+    (theCollectionId == other->theCollectionId && other->theTreeId == theTreeId && theOrdPath > other->theOrdPath));
+  }
+}
+
+
+bool StructuralAnyUriItem::isFollowingInDocumentOrder(const store::Item_t& aOther) const
+{
+  AnyUriItem* lOtherUriP = static_cast<AnyUriItem *>(aOther.getp());
+
+  if (lOtherUriP->getAnyUriTypeCode() != STRUCTURAL_INFORMATION_ANY_URI)
+  {
+    store::Item_t lOtherUri;
+    zstring tmp = lOtherUriP->theValue;
+    GET_FACTORY().createStructuralAnyURI(lOtherUri, tmp);
+    return isFollowingInDocumentOrder(lOtherUri);
+  }
+  else
+  {
+    StructuralAnyUriItem* other = static_cast<StructuralAnyUriItem*>(aOther.getp());
+    return
+    (theCollectionId < other->theCollectionId ||
+    (theCollectionId == other->theCollectionId && theTreeId < other->theTreeId) ||
+    (theCollectionId == other->theCollectionId && other->theTreeId == theTreeId && theOrdPath < other->theOrdPath));
+  }
+}
+
+
+store::Item_t StructuralAnyUriItem::getLevel() const
+{
+  store::Item_t lResult;
+  GET_FACTORY().createInteger(lResult, theOrdPath.getLevel());
+  return lResult;
+}
+
+
+bool StructuralAnyUriItem::isAttribute() const
+{
+  return theNodeKind == store::StoreConsts::attributeNode;
+}
+
+
+bool StructuralAnyUriItem::isComment() const
+{
+  return theNodeKind == store::StoreConsts::commentNode;
+}
+
+
+bool StructuralAnyUriItem::isDocument() const
+{
+  return theNodeKind == store::StoreConsts::documentNode;
+}
+
+
+bool StructuralAnyUriItem::isElement() const
+{
+  return theNodeKind == store::StoreConsts::elementNode;
+}
+
+
+bool StructuralAnyUriItem::isProcessingInstruction() const
+{
+  return theNodeKind == store::StoreConsts::piNode;
+}
+
+
+bool StructuralAnyUriItem::isText() const
+{
+  return theNodeKind == store::StoreConsts::textNode;
+}
+
+
+bool StructuralAnyUriItem::isSibling(const store::Item_t& aOther) const
+{
+  AnyUriItem* lOtherUriP = static_cast<AnyUriItem *>(aOther.getp());
+
+  if (lOtherUriP->getAnyUriTypeCode() != STRUCTURAL_INFORMATION_ANY_URI)
+  {
+    store::Item_t lOtherUri;
+    zstring tmp = lOtherUriP->theValue;
+    GET_FACTORY().createStructuralAnyURI(lOtherUri, tmp);
+    return isSibling(lOtherUri);
+  }
+  else
+  {
+    StructuralAnyUriItem* other = static_cast<StructuralAnyUriItem*>(aOther.getp());
+
+    if (other->theCollectionId == theCollectionId &&
+        other->theTreeId == theTreeId &&
+        other->theNodeKind != store::StoreConsts::attributeNode &&
+        theNodeKind != store::StoreConsts::attributeNode)
+    {
+      OrdPath::RelativePosition pos = 
+      theOrdPath.getRelativePosition2(other->theOrdPath);
+
+      return (pos == OrdPath::FOLLOWING_SIBLING ||
+              pos==OrdPath::PRECEDING_SIBLING);
+    }
+    else
+    {
+      return false;
+    }
+  }
+}
+
+
+bool StructuralAnyUriItem::inSameTree(const store::Item_t& aOther) const
+{
+  AnyUriItem* lOtherUriP = static_cast<AnyUriItem *>(aOther.getp());
+
+  if (lOtherUriP->getAnyUriTypeCode() != STRUCTURAL_INFORMATION_ANY_URI)
+  {
+    store::Item_t lOtherUri;
+    zstring tmp = lOtherUriP->theValue;
+    GET_FACTORY().createStructuralAnyURI(lOtherUri, tmp);
+    return inSameTree(lOtherUri);
+  }
+  else
+  {
+    StructuralAnyUriItem* other = static_cast<StructuralAnyUriItem*>(aOther.getp());
+    return (theCollectionId == other->theCollectionId &&
+            theTreeId == other->theTreeId);
+  }
+}
+
+
+bool StructuralAnyUriItem::inCollection() const
+{
+  return theCollectionId != 0;
+}
+
+
+bool StructuralAnyUriItem::inSameCollection(const store::Item_t& aOther) const
+{
+  AnyUriItem* lOtherUriP = static_cast<AnyUriItem *>(aOther.getp());
+
+  if (lOtherUriP->getAnyUriTypeCode() != STRUCTURAL_INFORMATION_ANY_URI)
+  {
+    store::Item_t lOtherUri;
+    zstring tmp = lOtherUriP->theValue;
+    GET_FACTORY().createStructuralAnyURI(lOtherUri, tmp);
+    return inSameCollection(lOtherUri);
+  }
+  else
+  {
+    return
+    (
+     theCollectionId !=0 &&
+     theCollectionId == static_cast<StructuralAnyUriItem*>(aOther.getp())->theCollectionId
+    );
+
+  }
+}
+
+
 /*******************************************************************************
   class StringItem
 ********************************************************************************/
@@ -849,6 +1581,8 @@
     long timezone,
     const XQPCollator* aCollation) const
 {
+  // Note: utf8::compare does byte comparison if the collation is null or
+  // requires byte comparison.
   return utf8::compare(theValue, other->getString(), aCollation);
 }
 
@@ -871,10 +1605,11 @@
 }
 
 #ifndef ZORBA_NO_FULL_TEXT
-FTTokenIterator_t
-StringItem::getTokens( TokenizerProvider const &provider,
-                       Tokenizer::Numbers &numbers, iso639_1::type lang,
-                       bool wildcards ) const
+FTTokenIterator_t StringItem::getTokens( 
+    TokenizerProvider const &provider,
+    Tokenizer::Numbers &numbers,
+    iso639_1::type lang,
+    bool wildcards ) const
 {
   typedef NaiveFTTokenIterator::container_type tokens_t;
   unique_ptr<tokens_t> tokens( new tokens_t );
@@ -893,7 +1628,8 @@
 ********************************************************************************/
 void StreamableStringItem::appendStringValue(zstring& aBuf) const
 {
-  if (!theIsMaterialized) {
+  if (!theIsMaterialized) 
+  {
     materialize();
   }
   aBuf += theValue;
@@ -905,7 +1641,8 @@
     long aTimezone,
     const XQPCollator* aCollator) const
 {
-  if (!theIsMaterialized) {
+  if (!theIsMaterialized) 
+  {
     materialize();
   }
   return StringItem::compare(aOther, aTimezone, aCollator);
@@ -917,7 +1654,8 @@
     long aTimezone,
     XQPCollator const* aCollator) const 
 {
-  if (!theIsMaterialized) {
+  if (!theIsMaterialized) 
+  {
     materialize();
   }
   return StringItem::equals(aItem, aTimezone, aCollator);
@@ -926,7 +1664,8 @@
 
 store::Item_t StreamableStringItem::getEBV() const
 {
-  if (!theIsMaterialized) {
+  if (!theIsMaterialized) 
+  {
     materialize();
   }
   return StringItem::getEBV();
@@ -935,7 +1674,8 @@
 
 zstring const& StreamableStringItem::getString() const
 {
-  if (!theIsMaterialized) {
+  if (!theIsMaterialized) 
+  {
     materialize();
   }
   return theValue;
@@ -944,7 +1684,8 @@
 
 zstring StreamableStringItem::getStringValue() const
 {
-  if (!theIsMaterialized) {
+  if (!theIsMaterialized) 
+  {
     materialize();
   }
   return theValue;
@@ -953,7 +1694,8 @@
 
 void StreamableStringItem::getStringValue2(zstring &val) const
 {
-  if (!theIsMaterialized) {
+  if (!theIsMaterialized) 
+  {
     materialize();
   }
   val = theValue;
@@ -964,7 +1706,8 @@
     long aTimezone,
     XQPCollator const* aCollator) const
 {
-  if (!theIsMaterialized) {
+  if (!theIsMaterialized) 
+  {
     materialize();
   }
   return StringItem::hash(aTimezone, aCollator);
@@ -973,7 +1716,8 @@
 
 zstring StreamableStringItem::show() const
 {
-  if (!theIsMaterialized) {
+  if (!theIsMaterialized) 
+  {
     materialize();
   }
   return StringItem::show();
@@ -1016,11 +1760,13 @@
   return theIstream;
 }
 
+
 StreamReleaser StreamableStringItem::getStreamReleaser()
 {
   return theStreamReleaser;
 }
 
+
 void StreamableStringItem::setStreamReleaser(StreamReleaser aReleaser)
 {
   theStreamReleaser = aReleaser;

=== modified file 'src/store/naive/atomic_items.h'
--- src/store/naive/atomic_items.h	2011-09-30 14:06:33 +0000
+++ src/store/naive/atomic_items.h	2011-10-27 20:59:25 +0000
@@ -38,6 +38,7 @@
 #include "zorbatypes/datetime.h"
 
 #include "diagnostics/xquery_diagnostics.h"
+#include "store/naive/ordpath.h"
 
 
 namespace zorba
@@ -46,6 +47,13 @@
 namespace simplestore
 {
 
+
+enum AnyUriTypeCode
+{
+  NON_SPECIALIZED_ANY_URI,
+  STRUCTURAL_INFORMATION_ANY_URI
+};
+
 class AtomicItemTokenizerCallback;
 
 class QNameItem;
@@ -308,12 +316,9 @@
   bool equals(
         const store::Item* other,
         long timezone = 0,
-        const XQPCollator* aCollation = 0) const
-  {
-    return theValue == other->getString();
-  }
+        const XQPCollator* collation = 0) const;
 
-  store::Item_t getEBV( ) const;
+  store::Item_t getEBV() const;
 
   zstring getStringValue() const { return theValue; }
 
@@ -483,6 +488,7 @@
 class AnyUriItem : public AtomicItem
 {
   friend class BasicItemFactory;
+  friend class StructuralAnyUriItem;
 
 protected:
   zstring theValue;
@@ -493,6 +499,11 @@
   AnyUriItem() {}
 
 public:
+  virtual AnyUriTypeCode getAnyUriTypeCode() const 
+  {
+    return NON_SPECIALIZED_ANY_URI;
+  }
+
   SchemaTypeCode getTypeCode() const { return XS_ANY_URI; }
 
   store::Item* getType( ) const;
@@ -526,6 +537,177 @@
   const zstring& getString() const { return theValue; }
 
   zstring show() const;
+
+  virtual bool
+  isAncestor(const store::Item_t&) const;
+
+  virtual bool
+  isFollowingSibling(const store::Item_t&) const;
+
+  virtual bool
+  isFollowing(const store::Item_t&) const;
+
+  virtual bool
+  isInSubtreeOf(const store::Item_t&) const;
+
+  virtual bool
+  isDescendant(const store::Item_t&) const;
+
+  virtual bool
+  isPrecedingSibling(const store::Item_t&) const;
+
+  virtual bool
+  isPreceding(const store::Item_t&) const;
+
+  virtual bool
+  isChild(const store::Item_t&) const;
+
+  virtual bool
+  isAttribute(const store::Item_t&) const;
+
+  virtual bool
+  isParent(const store::Item_t&) const;
+
+  virtual bool
+  isPrecedingInDocumentOrder(const store::Item_t&) const;
+
+  virtual bool
+  isFollowingInDocumentOrder(const store::Item_t&) const;
+
+  virtual store::Item_t
+  getLevel() const;
+
+  virtual bool
+  isAttribute() const;
+
+  virtual bool
+  isComment() const;
+
+  virtual bool
+  isDocument() const;
+
+  virtual bool
+  isElement() const;
+
+  virtual bool
+  isProcessingInstruction() const;
+
+  virtual bool
+  isText() const;
+
+  virtual bool
+  isSibling(const store::Item_t&) const;
+
+  virtual bool
+  inSameTree(const store::Item_t&) const;
+
+  virtual bool
+  inCollection() const;
+
+  virtual bool
+  inSameCollection(const store::Item_t&) const;
+};
+
+
+/*******************************************************************************
+  class StructuralAnyUriItem
+********************************************************************************/
+class StructuralAnyUriItem : public AnyUriItem
+{
+  friend class BasicItemFactory;
+
+protected:
+  ulong                        theCollectionId;
+  ulong                        theTreeId;
+  store::StoreConsts::NodeKind theNodeKind;
+  OrdPath                      theOrdPath;
+
+protected:
+  virtual AnyUriTypeCode getAnyUriTypeCode() const 
+  {
+    return STRUCTURAL_INFORMATION_ANY_URI;
+  }
+
+  StructuralAnyUriItem(zstring& value);
+
+  StructuralAnyUriItem(
+      zstring& value,
+      ulong collectionId,
+      ulong treeId,
+      store::StoreConsts::NodeKind nodeKind,
+      const OrdPath& ordPath);
+
+  StructuralAnyUriItem() {}
+
+public:
+  bool
+  isAncestor(const store::Item_t&) const;
+
+  bool
+  isFollowingSibling(const store::Item_t&) const;
+
+  bool
+  isFollowing(const store::Item_t&) const;
+
+  bool
+  isInSubtreeOf(const store::Item_t&) const;
+
+  bool
+  isDescendant(const store::Item_t&) const;
+
+  bool
+  isPrecedingSibling(const store::Item_t&) const;
+
+  bool
+  isPreceding(const store::Item_t&) const;
+
+  bool
+  isChild(const store::Item_t&) const;
+
+  bool
+  isAttribute(const store::Item_t&) const;
+
+  bool
+  isParent(const store::Item_t&) const;
+
+  bool
+  isPrecedingInDocumentOrder(const store::Item_t&) const;
+
+  bool
+  isFollowingInDocumentOrder(const store::Item_t&) const;
+
+  store::Item_t
+  getLevel() const;
+
+  bool
+  isAttribute() const;
+
+  bool
+  isComment() const;
+
+  bool
+  isDocument() const;
+
+  bool
+  isElement() const;
+
+  bool
+  isProcessingInstruction() const;
+
+  bool
+  isText() const;
+
+  bool
+  isSibling(const store::Item_t&) const;
+
+  bool
+  inSameTree(const store::Item_t&) const;
+
+  bool
+  inCollection() const;
+
+  bool
+  inSameCollection(const store::Item_t&) const;
 };
 
 
@@ -637,7 +819,8 @@
 
   ~StreamableStringItem()
   {
-    if (theStreamReleaser) {
+    if (theStreamReleaser) 
+    {
       theStreamReleaser(&theIstream);
     }
   }

=== modified file 'src/store/naive/item.cpp'
--- src/store/naive/item.cpp	2011-09-27 20:45:01 +0000
+++ src/store/naive/item.cpp	2011-10-27 20:59:25 +0000
@@ -1027,6 +1027,15 @@
 }
 
 bool
+Item::isInSubtreeOf(const store::Item_t&) const
+{
+  throw ZORBA_EXCEPTION(
+    zerr::ZSTR0050_FUNCTION_NOT_IMPLEMENTED_FOR_ITEMTYPE,
+    ERROR_PARAMS( __FUNCTION__, getType()->getStringValue() )
+  );
+}
+
+bool
 Item::isDescendant(const store::Item_t&) const
 {
   throw ZORBA_EXCEPTION(
@@ -1063,6 +1072,15 @@
 }
 
 bool
+Item::isAttribute(const store::Item_t&) const
+{
+  throw ZORBA_EXCEPTION(
+    zerr::ZSTR0050_FUNCTION_NOT_IMPLEMENTED_FOR_ITEMTYPE,
+    ERROR_PARAMS( __FUNCTION__, getType()->getStringValue() )
+  );
+}
+
+bool
 Item::isParent(const store::Item_t&) const
 {
   throw ZORBA_EXCEPTION(
@@ -1071,6 +1089,24 @@
   );
 }
 
+bool
+Item::isPrecedingInDocumentOrder(const store::Item_t&) const
+{
+  throw ZORBA_EXCEPTION(
+    zerr::ZSTR0050_FUNCTION_NOT_IMPLEMENTED_FOR_ITEMTYPE,
+    ERROR_PARAMS( __FUNCTION__, getType()->getStringValue() )
+  );
+}
+
+bool
+Item::isFollowingInDocumentOrder(const store::Item_t&) const
+{
+  throw ZORBA_EXCEPTION(
+    zerr::ZSTR0050_FUNCTION_NOT_IMPLEMENTED_FOR_ITEMTYPE,
+    ERROR_PARAMS( __FUNCTION__, getType()->getStringValue() )
+  );
+}
+
 store::Item_t
 Item::getLevel() const
 {
@@ -1080,6 +1116,97 @@
   );
 }
 
+bool
+Item::isSibling(const store::Item_t&) const
+{
+  throw ZORBA_EXCEPTION(
+    zerr::ZSTR0050_FUNCTION_NOT_IMPLEMENTED_FOR_ITEMTYPE,
+    ERROR_PARAMS( __FUNCTION__, getType()->getStringValue() )
+  );
+}
+
+bool
+Item::isAttribute() const
+{
+  throw ZORBA_EXCEPTION(
+    zerr::ZSTR0050_FUNCTION_NOT_IMPLEMENTED_FOR_ITEMTYPE,
+    ERROR_PARAMS( __FUNCTION__, getType()->getStringValue() )
+  );
+}
+
+bool
+Item::isComment() const
+{
+  throw ZORBA_EXCEPTION(
+    zerr::ZSTR0050_FUNCTION_NOT_IMPLEMENTED_FOR_ITEMTYPE,
+    ERROR_PARAMS( __FUNCTION__, getType()->getStringValue() )
+  );
+}
+
+bool
+Item::isDocument() const
+{
+  throw ZORBA_EXCEPTION(
+    zerr::ZSTR0050_FUNCTION_NOT_IMPLEMENTED_FOR_ITEMTYPE,
+    ERROR_PARAMS( __FUNCTION__, getType()->getStringValue() )
+  );
+}
+
+
+bool
+Item::isElement() const
+{
+  throw ZORBA_EXCEPTION(
+    zerr::ZSTR0050_FUNCTION_NOT_IMPLEMENTED_FOR_ITEMTYPE,
+    ERROR_PARAMS( __FUNCTION__, getType()->getStringValue() )
+  );
+}
+
+bool
+Item::isProcessingInstruction() const
+{
+  throw ZORBA_EXCEPTION(
+    zerr::ZSTR0050_FUNCTION_NOT_IMPLEMENTED_FOR_ITEMTYPE,
+    ERROR_PARAMS( __FUNCTION__, getType()->getStringValue() )
+  );
+}
+
+bool
+Item::isText() const
+{
+  throw ZORBA_EXCEPTION(
+    zerr::ZSTR0050_FUNCTION_NOT_IMPLEMENTED_FOR_ITEMTYPE,
+    ERROR_PARAMS( __FUNCTION__, getType()->getStringValue() )
+  );
+}
+
+bool
+Item::inSameTree(const store::Item_t&) const
+{
+  throw ZORBA_EXCEPTION(
+    zerr::ZSTR0050_FUNCTION_NOT_IMPLEMENTED_FOR_ITEMTYPE,
+    ERROR_PARAMS( __FUNCTION__, getType()->getStringValue() )
+  );
+}
+
+bool
+Item::inCollection() const
+{
+  throw ZORBA_EXCEPTION(
+    zerr::ZSTR0050_FUNCTION_NOT_IMPLEMENTED_FOR_ITEMTYPE,
+    ERROR_PARAMS( __FUNCTION__, getType()->getStringValue() )
+  );
+}
+
+bool
+Item::inSameCollection(const store::Item_t&) const
+{
+  throw ZORBA_EXCEPTION(
+    zerr::ZSTR0050_FUNCTION_NOT_IMPLEMENTED_FOR_ITEMTYPE,
+    ERROR_PARAMS( __FUNCTION__, getType()->getStringValue() )
+  );
+}
+
 store::Item_t
 Item::leastCommonAncestor(const store::Item_t&) const
 {

=== modified file 'src/store/naive/loader_fast.cpp'
--- src/store/naive/loader_fast.cpp	2011-07-15 16:39:51 +0000
+++ src/store/naive/loader_fast.cpp	2011-10-27 20:59:25 +0000
@@ -216,11 +216,9 @@
 
     if (stream.bad())
     {
-      theXQueryDiagnostics->add_error(
-      	NEW_ZORBA_EXCEPTION(
-          zerr::ZSTR0020_LOADER_IO_ERROR, ERROR_PARAMS( ZED( BadStreamState ) )
-        )
-      );
+      theXQueryDiagnostics->
+      add_error(NEW_ZORBA_EXCEPTION(zerr::ZSTR0020_LOADER_IO_ERROR,
+                                    ERROR_PARAMS(ZED(BadStreamState))));
     }
 
     return stream.gcount();

=== modified file 'src/store/naive/node_items.cpp'
--- src/store/naive/node_items.cpp	2011-10-10 12:56:57 +0000
+++ src/store/naive/node_items.cpp	2011-10-27 20:59:25 +0000
@@ -739,9 +739,6 @@
   if (parent == NULL)
   {
     theOrdPath.setAsRoot();
-
-    if (nodeKind != store::StoreConsts::documentNode)
-      theOrdPath.appendComp(1);
   }
   else
   {
@@ -1141,7 +1138,7 @@
   Return the position of the given node among the children of "this". If the
   given node is not a child of "this", return the number of children of "this".
 ********************************************************************************/
-csize InternalNode::findChild(XmlNode* child) const
+csize InternalNode::findChild(const XmlNode* child) const
 {
   const_iterator begin = childrenBegin();
   const_iterator end = childrenEnd();
@@ -3604,6 +3601,78 @@
 }
 
 
+#ifndef TEXT_ORDPATH
+/*******************************************************************************
+
+********************************************************************************/
+void TextNode::getOrdPath(OrdPath& ordPath) const
+{
+  InternalNode* parent = static_cast<InternalNode*>(getParent());
+
+  if (parent == NULL)
+  {
+    // The text node is the root
+    ordPath.setAsRoot();
+    return;
+  }
+
+  ZORBA_FATAL(parent->theOrdPath.isValid(),"Parent ordpath is invalid.");
+
+  csize pos = parent->findChild(this);
+  csize numChildren = parent->numChildren();
+  csize numAttrs = parent->numAttrs();
+
+  if (numChildren == 1 && numAttrs == 0)
+  {
+    // Parent has no other children and no attributes
+    ordPath = parent->theOrdPath;
+    ordPath.appendComp(1);
+  }
+  else 
+  {
+    // Parent has either children or attributes
+    
+    // The smallest Ordpath at the same level of the textNode which must
+    // be greater than the OrdPath of the textNode
+    const OrdPath* upperOrdPath = NULL;
+    
+    // The biggest Ordpath at the same level of the textNode which must 
+    // be smaller than the OrdPath of the textNode
+    const OrdPath* lowerOrdPath = NULL; 
+    
+    if (pos < numChildren-1) 
+    {
+      //There could be an upperOrdPath
+      upperOrdPath = parent->getFirstChildOrdPathAfter(pos);
+    }
+    
+    if (pos > 0)
+    {
+      //There could be a lowerOrdPath in the children
+      lowerOrdPath = parent->getFirstChildOrdPathBefore(pos-1);
+    }
+    
+    if (lowerOrdPath == NULL && numAttrs > 0) 
+    {
+      //There is a lowerOrdPath in the attributes
+      lowerOrdPath = &parent->getAttr(numAttrs-1)->theOrdPath;
+    }
+    
+    if (upperOrdPath != NULL && lowerOrdPath != NULL)
+      OrdPath::insertInto(parent->theOrdPath, *lowerOrdPath, *upperOrdPath, ordPath);
+
+    else if (upperOrdPath == NULL && lowerOrdPath != NULL)
+      OrdPath::insertAfter(parent->theOrdPath, *lowerOrdPath, ordPath);
+
+    else if (upperOrdPath != NULL && lowerOrdPath == NULL)
+      OrdPath::insertBefore(parent->theOrdPath, *upperOrdPath, ordPath);
+
+    else
+      ZORBA_FATAL(0,"Adjacent text nodes.");
+  }
+}
+#endif
+
 
 /*******************************************************************************
 

=== modified file 'src/store/naive/node_items.h'
--- src/store/naive/node_items.h	2011-10-10 12:56:57 +0000
+++ src/store/naive/node_items.h	2011-10-27 20:59:25 +0000
@@ -660,6 +660,7 @@
   friend class CommentNode;
   friend class UpdPut;
   friend class CollectionPul;
+  friend class SimpleStore;
 
 public:
   typedef std::vector<XmlNode*> NodeVector;
@@ -757,7 +758,7 @@
   void finalizeNode();
 
 protected:
-  csize findChild(XmlNode* child) const;
+  csize findChild(const XmlNode* child) const;
 
   void insertChild(XmlNode* child, csize pos);
 
@@ -1255,6 +1256,10 @@
         const XmlNode* rootCopy,
         const store::CopyMode& copymode) const;
 
+#ifndef TEXT_ORDPATH
+  void getOrdPath(OrdPath& ordPath) const;
+#endif
+
   bool isTyped() const;
 
   void setTypedValue(store::Item_t& value);

=== modified file 'src/store/naive/ordpath.cpp'
--- src/store/naive/ordpath.cpp	2011-06-14 17:26:33 +0000
+++ src/store/naive/ordpath.cpp	2011-10-27 20:59:25 +0000
@@ -614,6 +614,76 @@
   }
 }
 
+/*******************************************************************************
+ Determine the position of the "other" ordpath relative to "this" ordpath.
+ The result is one of: PRECEDING_SIBLING, FOLLOWING_SIBLING, PARENT, CHILD or OTHER
+********************************************************************************/
+OrdPath::RelativePosition OrdPath::getRelativePosition2(const OrdPath& other) const
+{
+  int32_t dewey1[MAX_NUM_COMPS], dewey2[MAX_NUM_COMPS];
+  ulong offsets1[MAX_NUM_COMPS], offsets2[MAX_NUM_COMPS];
+  ulong numComps1 = 0, numComps2 = 0;
+  ulong bitLen1 = 0, bitLen2 = 0;
+  bool thisFirst;
+
+  decompress(0, dewey1, offsets1, numComps1, bitLen1);
+  other.decompress(0, dewey2, offsets2, numComps2, bitLen2);
+
+  // curr will be the first non-shared component
+  ulong curr = 0;
+
+  if (numComps1 < numComps2)
+  {
+    while (curr < numComps1 && dewey1[curr] == dewey2[curr])
+      ++curr;
+  }
+  else
+  {
+    while (curr < numComps2 && dewey1[curr] == dewey2[curr])
+      ++curr;
+
+    if (curr == numComps1 && numComps1 == numComps2)
+      return OTHER; //The two ordpaths are the same
+  }
+
+  if (curr < numComps1 && curr < numComps2 && dewey1[curr] < dewey2[curr])
+    thisFirst = true;
+  else
+    thisFirst = false;
+
+  ulong extraLevels1 = 0, extraLevels2 = 0;
+
+  for (ulong i = curr; i < numComps1; ++i)
+  {
+    if (dewey1[i] % 2 == 1)
+      ++extraLevels1;
+  }
+
+  for (ulong i = curr; i < numComps2; ++i)
+  {
+    if (dewey2[i] % 2 == 1)
+      ++extraLevels2;
+  }
+
+  // extraLevels1/2 == 0 means that we exhausted ordpath1/2, i.e. one ordpath
+  // is a prefix of the other ordpath.
+
+  if (extraLevels1 > 1 || extraLevels2 > 1)
+    return OTHER;
+
+  else if (extraLevels1 == 1 && extraLevels2 == 0)
+    return PARENT;
+
+  else if (extraLevels1 == 0 && extraLevels2 == 1)
+    return CHILD;
+
+  else if (extraLevels1 == 1 && extraLevels2 == 1)
+    return thisFirst ? FOLLOWING_SIBLING : PRECEDING_SIBLING;
+
+  ZORBA_FATAL(0,"");//The last component of an OrdPath is odd.
+                    //Since the two labels were different at least one
+                    //of the two must have a odd component left.
+}
 
 /*******************************************************************************
   Compress a dewey id into an ordpath.
@@ -1467,6 +1537,30 @@
 
 
 /*******************************************************************************
+
+********************************************************************************/
+ulong OrdPath::getLevel() const
+{
+  int32_t dewey[MAX_NUM_COMPS];
+  ulong offsets[MAX_NUM_COMPS];
+  ulong numComps = 0;
+  ulong bitLen = 0;
+
+  decompress(0, dewey, offsets, numComps, bitLen);
+
+  ulong level = 0;
+
+  for (ulong i = 0; i < numComps; ++i)
+  {
+    if (dewey[i] % 2 == 1)
+      ++level;
+  }
+
+  return level;
+}
+
+
+/*******************************************************************************
   Decompress all the components that appear after a given starting offset
   within the ordpath data buffer (it is assumed that startOffset points to
   the start of some component).

=== modified file 'src/store/naive/ordpath.h'
--- src/store/naive/ordpath.h	2011-06-14 17:26:33 +0000
+++ src/store/naive/ordpath.h	2011-10-27 20:59:25 +0000
@@ -34,9 +34,8 @@
 
 
 /*******************************************************************************
-
+  only exported for unit testing
 ********************************************************************************/
-// only exported for unit testing
 class ZORBA_DLL_PUBLIC OrdPath
 {
   friend class OrdPathStack;
@@ -48,11 +47,15 @@
     ANCESTOR,
     SELF,
     DESCENDANT,
-    FOLLOWING
+    FOLLOWING,
+    PRECEDING_SIBLING,
+    FOLLOWING_SIBLING,
+    PARENT,
+    CHILD,
+    OTHER
   }
   RelativePosition;
 
-
   typedef std::vector<int32_t> DeweyID;
 
 public:
@@ -182,6 +185,10 @@
 
   RelativePosition getRelativePosition(const OrdPath& other) const;
 
+  RelativePosition getRelativePosition2(const OrdPath& other) const;
+
+  ulong getLevel() const;
+
   void compress(const DeweyID& dewey);
 
   void appendComp(int32_t value);

=== modified file 'src/store/naive/pul_primitives.cpp'
--- src/store/naive/pul_primitives.cpp	2011-10-13 19:44:33 +0000
+++ src/store/naive/pul_primitives.cpp	2011-10-27 20:59:25 +0000
@@ -795,6 +795,9 @@
 {
   SimpleStore* store = &GET_STORE();
 
+  zstring targetUri;
+  theTargetUri->getStringValue2(targetUri);
+
   try
   {
     // Have to copy because addNode() will set the doc uri of target tree to
@@ -805,33 +808,32 @@
     // a parent already.
     store::CopyMode copymode;
     copymode.set(true, true, true, true);
-    theTarget = theTarget->copy(NULL, copymode);
 
     if (theTarget->getNodeKind() != store::StoreConsts::documentNode)
     {
-      XmlNode* target =  BASE_NODE(theTarget);
-
-      DocumentNode* doc = GET_STORE().getNodeFactory().createDocumentNode();
-      doc->setId(target->getTree(), NULL);
-      doc->insertChild(target, 0);
-      doc->getTree()->setRoot(doc);
-
-      store::Item_t docItem(doc);
-
-      theTarget = docItem;
-    }
-
-    store->addNode(theTargetUri->getStringValue(), theTarget);
+      store::Item_t docItem;
+      GET_FACTORY().createDocumentNode(docItem, targetUri, targetUri);
+
+      theTarget = theTarget->copy(docItem.getp(), copymode);
+
+      theTarget.transfer(docItem);
+    }
+    else
+    {
+      theTarget = theTarget->copy(NULL, copymode);
+    }
+
+    store->addNode(targetUri, theTarget);
   }
   catch(ZorbaException const& e)
   {
     if (e.diagnostic() == zerr::ZAPI0020_DOCUMENT_ALREADY_EXISTS)
     {
-      theOldDocument = store->getDocument(theTargetUri->getStringValue());
-
-      store->deleteDocument(theTargetUri->getStringValue());
-
-      store->addNode(theTargetUri->getStringValue(), theTarget);
+      theOldDocument = store->getDocument(targetUri);
+
+      store->deleteDocument(targetUri);
+
+      store->addNode(targetUri, theTarget);
     }
     else
     {

=== modified file 'src/store/naive/simple_item_factory.cpp'
--- src/store/naive/simple_item_factory.cpp	2011-10-12 07:17:05 +0000
+++ src/store/naive/simple_item_factory.cpp	2011-10-27 20:59:25 +0000
@@ -106,6 +106,35 @@
 }
 
 
+bool BasicItemFactory::createStructuralAnyURI(store::Item_t& result, zstring& value)
+{
+  result =  new StructuralAnyUriItem(value);
+  return true;
+}
+
+
+bool BasicItemFactory::createStructuralAnyURI(
+    store::Item_t& result,
+    ulong collectionId,
+    ulong treeId,
+    store::StoreConsts::NodeKind nodeKind,
+    const OrdPath& ordPath)
+{
+  ZORBA_FATAL(nodeKind,"Unexpected node kind");
+  std::ostringstream stream;
+  stream   << "zorba:"
+           << collectionId << "."
+           << treeId << "."
+           << static_cast<int>(nodeKind) << "."
+           << ordPath.serialize();
+  zstring uri = stream.str();
+
+  theUriPool->insert(uri);
+  result = new StructuralAnyUriItem(uri, collectionId, treeId, nodeKind, ordPath);
+  return true;
+}
+
+
 bool BasicItemFactory::createString(store::Item_t& result, zstring& value)
 {
   result = new StringItem(value);
@@ -117,7 +146,8 @@
     store::Item_t& result,
     std::istream &stream,
     StreamReleaser streamReleaser,
-    bool seekable) {
+    bool seekable) 
+{
   result = new StreamableStringItem( stream, streamReleaser, seekable );
   return true;
 }

=== modified file 'src/store/naive/simple_item_factory.h'
--- src/store/naive/simple_item_factory.h	2011-07-22 07:23:17 +0000
+++ src/store/naive/simple_item_factory.h	2011-10-27 20:59:25 +0000
@@ -41,6 +41,7 @@
 class StringPool;
 typedef StringPool UriPool;
 class QNamePool;
+class OrdPath;
 
 
 class BasicItemFactory : public store::ItemFactory
@@ -78,6 +79,15 @@
 
   bool createAnyURI(store::Item_t& result, const char* value);
 
+  bool createStructuralAnyURI(store::Item_t& result, zstring& value);
+
+  bool createStructuralAnyURI(
+      store::Item_t& result,
+      ulong collectionId,
+      ulong treeId,
+      store::StoreConsts::NodeKind nodeKind,
+      const OrdPath& ordPath);
+
   bool createUntypedAtomic(store::Item_t& result, zstring& value);
 
   bool createString(store::Item_t& result, zstring& value);

=== modified file 'src/store/naive/simple_store.cpp'
--- src/store/naive/simple_store.cpp	2011-10-10 12:56:57 +0000
+++ src/store/naive/simple_store.cpp	2011-10-27 20:59:25 +0000
@@ -1343,6 +1343,77 @@
 
 
 /*******************************************************************************
+
+********************************************************************************/
+bool SimpleStore::getPathInfo(
+    const store::Item*               docUriItem,
+    std::vector<const store::Item*>& contextPath,
+    std::vector<const store::Item*>& relativePath,
+    bool                             isAttrPath,
+    bool&                            found,
+    bool&                            unique)
+{
+  zstring docUri;
+  docUriItem->getStringValue2(docUri);
+
+  XmlNode_t docRoot = BASE_NODE(getDocument(docUri));
+
+  if (docRoot == NULL)
+    return false;
+
+  GuideNode* guideRoot = docRoot->getDataGuide();
+
+  if (!guideRoot)
+    return false;
+
+  guideRoot->getPathInfo(contextPath, relativePath, isAttrPath, found, unique);
+  return true;
+}
+
+
+/*******************************************************************************
+  Computes the Structural Reference for the given node.
+********************************************************************************/
+bool SimpleStore::getStructuralInformation(
+    store::Item_t& result, 
+    const store::Item* node)
+{
+#ifdef TEXT_ORDPATH
+  const OrdPathNode* n = static_cast<const OrdPathNode*>(node);
+
+  return theItemFactory->createStructuralAnyURI(result,
+                                                n->getCollectionId(),
+                                                n->getTreeId(),
+                                                n->getNodeKind(),
+                                                n->getOrdPath());
+#else
+  if (node->getNodeKind() == store::StoreConsts::textNode)
+  {
+    OrdPath ordPath;
+    const TextNode* n = static_cast<const TextNode*>(node);
+    n->getOrdPath(ordPath);
+
+    return theItemFactory->createStructuralAnyURI(result,
+                                                  n->getCollectionId(),
+                                                  n->getTreeId(),
+                                                  store::StoreConsts::textNode,
+                                                  ordPath);
+  }
+  else
+  {
+    const OrdPathNode* n = static_cast<const OrdPathNode*>(node);
+
+    return theItemFactory->createStructuralAnyURI(result,
+                                                  n->getCollectionId(),
+                                                  n->getTreeId(),
+                                                  n->getNodeKind(),
+                                                  n->getOrdPath());
+  }
+#endif
+}
+
+
+/*******************************************************************************
  Computes the reference of the given node.
  
  @param node XDM node
@@ -1445,35 +1516,6 @@
 
 
 /*******************************************************************************
-
-********************************************************************************/
-bool SimpleStore::getPathInfo(
-    const store::Item*               docUriItem,
-    std::vector<const store::Item*>& contextPath,
-    std::vector<const store::Item*>& relativePath,
-    bool                             isAttrPath,
-    bool&                            found,
-    bool&                            unique)
-{
-  zstring docUri;
-  docUriItem->getStringValue2(docUri);
-
-  XmlNode_t docRoot = BASE_NODE(getDocument(docUri));
-
-  if (docRoot == NULL)
-    return false;
-
-  GuideNode* guideRoot = docRoot->getDataGuide();
-
-  if (!guideRoot)
-    return false;
-
-  guideRoot->getPathInfo(contextPath, relativePath, isAttrPath, found, unique);
-  return true;
-}
-
-
-/*******************************************************************************
   Creates a new TempSeq. The instance can be used, e.g. for variable bindings
 
   @param iterator   The source for the XMDInstance

=== modified file 'src/store/naive/simple_store.h'
--- src/store/naive/simple_store.h	2011-10-10 12:56:57 +0000
+++ src/store/naive/simple_store.h	2011-10-27 20:59:25 +0000
@@ -331,6 +331,8 @@
 
   store::Iterator_t checkDistinctNodes(store::Iterator* input);
 
+  bool getStructuralInformation(store::Item_t& result, const store::Item* node);
+
   bool getPathInfo(
         const store::Item* docUri,
         std::vector<const store::Item*>& contextPath,

=== modified file 'src/types/casting.cpp'
--- src/types/casting.cpp	2011-07-29 22:38:19 +0000
+++ src/types/casting.cpp	2011-10-27 20:59:25 +0000
@@ -25,6 +25,7 @@
 
 #include "diagnostics/xquery_diagnostics.h"
 #include "diagnostics/assert.h"
+#include "diagnostics/util_macros.h"
 
 #include "context/namespace_context.h"
 
@@ -64,13 +65,18 @@
 
 struct ErrorInfo
 {
-  const XQType* theSourceType;
-  const XQType* theTargetType;
+  const XQType   * theSourceType;
+  const XQType   * theTargetType;
+  const QueryLoc & theLoc;
 };
 
 
-#define TYPE_EXCEPTION( ERROR_CODE, ERROR_INFO ) \
-  XQUERY_EXCEPTION( ERROR_CODE, ERROR_PARAMS( *(ERROR_INFO).theSourceType, ZED( NoCastTo_34o ), *(ERROR_INFO).theTargetType ) )
+#define TYPE_EXCEPTION( ERROR_CODE, ERROR_INFO )  \
+  XQUERY_EXCEPTION(ERROR_CODE,                    \
+  ERROR_PARAMS(*(ERROR_INFO).theSourceType,       \
+               ZED( NoCastTo_34o ),               \
+               *(ERROR_INFO).theTargetType ),     \
+  ERROR_LOC(ERROR_INFO.theLoc) )
 
 
 /*******************************************************************************
@@ -136,41 +142,49 @@
 
 T1_TO_T2(str, flt)
 {
-  try {
+  try 
+  {
     xs_float const n(strval.c_str());
     return aFactory->createFloat(result, n);
   }
-  catch ( std::invalid_argument const& ) {
-    throw TYPE_EXCEPTION( err::FORG0001, aErrorInfo );
+  catch (std::invalid_argument const&) 
+  {
+    throw TYPE_EXCEPTION(err::FORG0001, aErrorInfo);
   }
-  catch ( std::range_error const& ) {
-    throw XQUERY_EXCEPTION( err::FOAR0002, ERROR_PARAMS( strval ) );
+  catch ( std::range_error const& ) 
+  {
+    throw XQUERY_EXCEPTION(err::FOAR0002, ERROR_PARAMS(strval));
   }
 }
 
 
 T1_TO_T2(str, dbl)
 {
-  try {
+  try 
+  {
     xs_double const n(strval.c_str());
     return aFactory->createDouble(result, n);
   }
-  catch ( std::invalid_argument const& ) {
+  catch (std::invalid_argument const& ) 
+  {
     throw TYPE_EXCEPTION( err::FORG0001, aErrorInfo );
   }
-  catch ( std::range_error const& ) {
-    throw XQUERY_EXCEPTION( err::FOAR0002, ERROR_PARAMS( strval ) );
+  catch (std::range_error const& ) 
+  {
+    throw XQUERY_EXCEPTION(err::FOAR0002, ERROR_PARAMS(strval));
   }
 }
 
 
 T1_TO_T2(str, dec)
 {
-  try {
+  try 
+  {
     xs_decimal const n(strval.c_str());
     return aFactory->createDecimal(result, n);
   }
-  catch ( std::exception const& ) {
+  catch ( std::exception const& ) 
+  {
     throw TYPE_EXCEPTION( err::FORG0001, aErrorInfo );
   }
 }
@@ -178,14 +192,17 @@
 
 T1_TO_T2(str, int)
 {
-  try {
+  try 
+  {
     xs_integer const n(strval.c_str());
     return aFactory->createInteger(result, n);
   }
-  catch ( std::invalid_argument const& ) {
+  catch ( std::invalid_argument const& ) 
+  {
     throw TYPE_EXCEPTION( err::FORG0001, aErrorInfo );
   }
-  catch ( std::range_error const& ) {
+  catch ( std::range_error const& ) 
+  {
     throw TYPE_EXCEPTION( err::FOAR0002, aErrorInfo );
   }
 }
@@ -199,7 +216,7 @@
   if (0 == (err = Duration::parseDuration(strval.c_str(), strval.size(), d)))
     return aFactory->createDuration(result, &d);
 
-  throw TYPE_EXCEPTION( err::FORG0001, aErrorInfo );
+  throw TYPE_EXCEPTION(err::FORG0001, aErrorInfo);
 }
 
 
@@ -1669,7 +1686,7 @@
 
   const XQType* sourceType = rtm.STRING_TYPE_ONE.getp();
 
-  ErrorInfo lErrorInfo = {&*sourceType, aTargetType};
+  ErrorInfo lErrorInfo = {&*sourceType, aTargetType, loc};
 
   if (!TypeOps::is_atomic(tm, *aTargetType))
     throw XQUERY_EXCEPTION( err::XPST0051, ERROR_PARAMS( aTargetType ) );
@@ -1740,112 +1757,110 @@
 
 
 /*******************************************************************************
-  Cast, if possible, a given item SI to an atomic item TI of a given type TT.
-  If I1 is not
+  Cast, if possible, a given atomic item SI to an atomic item TI of a given 
+  type TT. If the cast is not allowed, the method raises an error. If the cast
+  is not possible, the method may raise an error or return false (TODO fix 
+  this!). Otherwise, it returns true.
 ********************************************************************************/
 bool GenericCast::castToAtomic(
     store::Item_t&       result,
     store::Item_t&       aItem,
-    const XQType*        aTargetType,
+    const XQType*        targetType,
     const TypeManager*   tm,
-    namespace_context*   aNCtx,
+    namespace_context*   nsCtx,
     const QueryLoc&      loc)
 {
   RootTypeManager& rtm = GENV_TYPESYSTEM;
-  store::ItemFactory* lFactory = GENV_ITEMFACTORY;
-
-  xqtref_t lSourceType = tm->create_named_type(aItem->getType(),
-                                               TypeConstants::QUANT_ONE,
-                                               QueryLoc::null,
-                                               err::XPTY0004);
+  store::ItemFactory* factory = GENV_ITEMFACTORY;
 
   ZORBA_ASSERT(aItem->isAtomic());
-  ZORBA_ASSERT(lSourceType != NULL);
-  ZORBA_ASSERT(TypeOps::is_atomic(tm, *lSourceType));
+
+  xqtref_t sourceType = tm->create_named_type(aItem->getType(),
+                                              TypeConstants::QUANT_ONE,
+                                              QueryLoc::null,
+                                              err::XPTY0004);
+  ZORBA_ASSERT(sourceType != NULL);
+  assert(TypeOps::is_atomic(tm, *sourceType));
 
   // std::cout << "-castToAtomic: " << aItem.getp()->getStringValue()->c_str()
-  //           << " srcType: " << lSourceType->get_qname()->getLocalName()->c_str()
-  //           << " @ " << lSourceType->get_qname()->getNamespace()->c_str() << "\n";
+  //           << " srcType: " << sourceType->get_qname()->getLocalName()->c_str()
+  //           << " @ " << sourceType->get_qname()->getNamespace()->c_str() << "\n";
   // std::cout << "\t\t  tgtType: " << aTargetType->get_qname()->getLocalName()->c_str()
   //           << " @ " << aTargetType->get_qname()->getNamespace()->c_str() << "\n";
 
-  ErrorInfo lErrorInfo = {&*lSourceType, aTargetType};
+  ErrorInfo errorInfo = {&*sourceType, targetType, loc};
 
-  if (!TypeOps::is_atomic(tm, *aTargetType))
-    throw XQUERY_EXCEPTION(err::XPST0051, ERROR_PARAMS(aTargetType));
+  if (!TypeOps::is_atomic(tm, *targetType))
+    RAISE_ERROR(err::XPST0051, loc, ERROR_PARAMS(targetType));
 
 #ifndef ZORBA_NO_XMLSCHEMA
-  if (aTargetType->type_kind() == XQType::USER_DEFINED_KIND)
+  if (targetType->type_kind() == XQType::USER_DEFINED_KIND)
   {
-    castToUserDefinedType(result, aItem, lSourceType.getp(), aTargetType, loc);
+    castToUserDefinedType(result, aItem, sourceType.getp(), targetType, loc);
     return result != NULL;
   }
 #endif // ZORBA_NO_XMLSCHEMA
 
+  sourceType = sourceType->getBaseBuiltinType();
+
   zstring sourceString;
-  ATOMIC_CODE_T lSourceTypeCode;
-  ATOMIC_CODE_T lTargetTypeCode = TypeOps::get_atomic_type_code(*aTargetType);
-
-  lSourceType = lSourceType->getBaseBuiltinType();
-
-  ZORBA_ASSERT(TypeOps::is_builtin_atomic(tm, *lSourceType));
-
-  lSourceTypeCode = TypeOps::get_atomic_type_code(*lSourceType);
-
-  if (lSourceTypeCode == lTargetTypeCode)
+  ATOMIC_CODE_T sourceTypeCode = TypeOps::get_atomic_type_code(*sourceType);
+  ATOMIC_CODE_T targetTypeCode = TypeOps::get_atomic_type_code(*targetType);
+
+  if (sourceTypeCode == targetTypeCode)
   {
     result.transfer(aItem);
     return true;
   }
 
-  if (theMapping[lSourceTypeCode] == theMapping[TypeConstants::XS_STRING])
+  if (targetTypeCode == TypeConstants::XS_NOTATION ||
+      targetTypeCode == TypeConstants::XS_ANY_ATOMIC)
+  {
+    RAISE_ERROR(err::XPST0080, loc,
+    ERROR_PARAMS(*errorInfo.theTargetType));
+  }
+
+  if (sourceTypeCode == TypeConstants::XS_ANY_ATOMIC)
+    throw TYPE_EXCEPTION(err::XPTY0004, errorInfo);
+
+  if (targetTypeCode == TypeConstants::XS_NCNAME &&
+      sourceTypeCode != TypeConstants::XS_STRING &&
+      sourceTypeCode != TypeConstants::XS_NCNAME &&
+      sourceTypeCode != TypeConstants::XS_UNTYPED_ATOMIC)
+    throw TYPE_EXCEPTION(err::XPTY0004, errorInfo);
+
+  CastFunc castFunc = theCastMatrix[theMapping[sourceTypeCode]]
+                                    [theMapping[targetTypeCode]];
+  if (castFunc == 0)
+    throw TYPE_EXCEPTION(err::XPTY0004, errorInfo);
+
+  if (theMapping[sourceTypeCode] == theMapping[TypeConstants::XS_STRING])
   {
     aItem->getStringValue2(sourceString);
   }
 
-  if (lTargetTypeCode == TypeConstants::XS_NOTATION ||
-      lTargetTypeCode == TypeConstants::XS_ANY_ATOMIC)
-  {
-    throw XQUERY_EXCEPTION(err::XPST0080,
-                           ERROR_PARAMS(*lErrorInfo.theTargetType),
-                           ERROR_LOC(loc));
-  }
-
-  if (lSourceTypeCode == TypeConstants::XS_ANY_ATOMIC)
-    throw TYPE_EXCEPTION(err::XPTY0004, lErrorInfo);
-
-  if (lTargetTypeCode == TypeConstants::XS_NCNAME &&
-      lSourceTypeCode != TypeConstants::XS_STRING &&
-      lSourceTypeCode != TypeConstants::XS_NCNAME &&
-      lSourceTypeCode != TypeConstants::XS_UNTYPED_ATOMIC)
-    throw TYPE_EXCEPTION(err::XPTY0004, lErrorInfo);
-
-  CastFunc lCastFunc = theCastMatrix[theMapping[lSourceTypeCode]]
-                                    [theMapping[lTargetTypeCode]];
-  if (lCastFunc == 0)
-    throw TYPE_EXCEPTION(err::XPTY0004, lErrorInfo);
-
-  bool valid = (*lCastFunc)(result,
-                            aItem,
-                            sourceString,
-                            lFactory,
-                            aNCtx,
-                            lErrorInfo);
-
-  DownCastFunc lDownCastFunc = theDownCastMatrix[theMapping[lTargetTypeCode]];
-
-  if (lDownCastFunc != 0 &&
-      lTargetTypeCode != TypeConstants::XS_STRING &&
-      lTargetTypeCode != TypeConstants::XS_INTEGER)
-  {
-    valid = (*lDownCastFunc)(result,
-                             &*result,
-                             rtm,
-                             lTargetTypeCode,
-                             lFactory,
-                             lErrorInfo);
-  }
-
+  bool valid = (*castFunc)(result,
+                           aItem,
+                           sourceString,
+                           factory,
+                           nsCtx,
+                           errorInfo);
+
+  DownCastFunc downCastFunc = theDownCastMatrix[theMapping[targetTypeCode]];
+
+  if (downCastFunc != 0 &&
+      targetTypeCode != TypeConstants::XS_STRING &&
+      targetTypeCode != TypeConstants::XS_INTEGER)
+  {
+    valid = (*downCastFunc)(result,
+                            &*result,
+                            rtm,
+                            targetTypeCode,
+                            factory,
+                            errorInfo);
+  }
+
+  assert(valid);
   return valid;
 }
 
@@ -1860,7 +1875,7 @@
     const XQType* aTargetType,
     const QueryLoc& loc)
 {
-  ErrorInfo lErrorInfo = {aSourceType, aTargetType};
+  ErrorInfo lErrorInfo = {aSourceType, aTargetType, loc};
 
   // std::cout << "-castToUserDefinedType: " << aItem.getp()->getStringValue()->c_str()
   //           << " srcType: " << aSourceType->get_qname()->getLocalName()->c_str()
@@ -1875,7 +1890,7 @@
   if (aSourceType->type_kind() != XQType::ATOMIC_TYPE_KIND ||
       (TypeOps::get_atomic_type_code(*aSourceType) != TypeConstants::XS_STRING))
   {
-    throw TYPE_EXCEPTION( err::FORG0001, lErrorInfo );
+    throw TYPE_EXCEPTION(err::FORG0001, lErrorInfo);
   }
 
   const UserDefinedXQType* udt =
@@ -1971,7 +1986,7 @@
     );
   }
 
-  ErrorInfo errorInfo = { sourceType.getp(), rtm.QNAME_TYPE_ONE.getp() };
+  ErrorInfo errorInfo = { sourceType.getp(), rtm.QNAME_TYPE_ONE.getp(), loc };
 
   zstring strval;
   item->getStringValue2(strval);
@@ -2405,14 +2420,15 @@
   if (TypeOps::is_equal(tm, *lItemType, *rtm.UNTYPED_ATOMIC_TYPE_ONE) &&
       ! TypeOps::is_equal(tm, *TypeOps::prime_type(tm, *aTargetType), *rtm.QNAME_TYPE_ONE))
   {
-    return GenericCast::castToAtomic(result, aItem, aTargetType, tm, NULL, loc);
+    // untyped --> target type
+    return castToAtomic(result, aItem, aTargetType, tm, NULL, loc);
   }
   else if (TypeOps::is_subtype(tm, *aTargetType, *rtm.FLOAT_TYPE_ONE))
   {
     // decimal --> xs:float
     if (TypeOps::is_subtype(tm, *lItemType, *rtm.DECIMAL_TYPE_ONE))
     {
-      return GenericCast::castToAtomic(result, aItem, aTargetType, tm, NULL, loc);
+      return castToAtomic(result, aItem, aTargetType, tm, NULL, loc);
     }
   }
   else if (TypeOps::is_subtype(tm, *aTargetType, *rtm.DOUBLE_TYPE_ONE))
@@ -2421,7 +2437,7 @@
     if (TypeOps::is_subtype(tm, *lItemType, *rtm.DECIMAL_TYPE_ONE) ||
         TypeOps::is_subtype(tm, *lItemType, *rtm.FLOAT_TYPE_ONE))
     {
-      return GenericCast::castToAtomic(result, aItem, aTargetType, tm, NULL, loc);
+      return castToAtomic(result, aItem, aTargetType, tm, NULL, loc);
     }
   }
   else if (TypeOps::is_subtype(tm, *aTargetType, *rtm.STRING_TYPE_ONE))
@@ -2429,7 +2445,7 @@
     // URI --> xs:String Promotion
     if (TypeOps::is_subtype(tm, *lItemType, *rtm.ANY_URI_TYPE_ONE))
     {
-      return GenericCast::castToAtomic(result, aItem, &*rtm.STRING_TYPE_ONE, tm, NULL, loc);
+      return castToAtomic(result, aItem, &*rtm.STRING_TYPE_ONE, tm, NULL, loc);
     }
   }
 

=== modified file 'src/types/schema/schema.cpp'
--- src/types/schema/schema.cpp	2011-07-22 07:23:17 +0000
+++ src/types/schema/schema.cpp	2011-10-27 20:59:25 +0000
@@ -1177,7 +1177,7 @@
   }
   else if ( XMLString::equals(SchemaSymbols::fgDT_MONTH, local) )
   {
-    result = GENV_TYPESYSTEM.GMONTH_DAY_TYPE_ONE;
+    result = GENV_TYPESYSTEM.GMONTH_TYPE_ONE;
   }
   else if ( XMLString::equals(SchemaSymbols::fgDT_DURATION, local) )
   {

=== modified file 'swig/CMakeLists.txt'
--- swig/CMakeLists.txt	2011-09-09 16:33:19 +0000
+++ swig/CMakeLists.txt	2011-10-27 20:59:25 +0000
@@ -26,6 +26,7 @@
   SET (SWIG_MODULE_zorba_api_EXTRA_DEPS ${SWIG_FILES})
   SET (SWIG_MODULE_libzorba_api_EXTRA_DEPS ${SWIG_FILES})
 
+  
   # on apple and cmake 2.8, the generated swig libraries are prefixed with "lib"
   SET (ZORBA_SWIG_LIB_PREFIX)
   IF (APPLE AND CMAKE_MINOR_VERSION GREATER 6)

=== added file 'swig/ItemFactory.h'
--- swig/ItemFactory.h	1970-01-01 00:00:00 +0000
+++ swig/ItemFactory.h	2011-10-27 20:59:25 +0000
@@ -0,0 +1,69 @@
+// Interface
+
+class ItemFactory
+{
+
+  private:
+    zorba::ItemFactory* theItemFactory;
+  public:
+    ItemFactory(): theItemFactory(0) {}
+    ItemFactory(zorba::ItemFactory* aItemFactory) : theItemFactory(aItemFactory) {}
+    ItemFactory(const ItemFactory& aItemFactory) : theItemFactory(aItemFactory.theItemFactory) {}
+
+    Item 	createAnyURI (const std::string &aURI);
+    Item 	createAttributeNode (Item aParent, Item aNodeName, Item aTypeName, Item aTypedValue);
+    Item 	createAttributeNode (Item aParent, Item aNodeName, Item aTypeName, std::vector< Item > aTypedValue);
+    Item 	createBase64Binary (const char *aBinData, size_t aLength);
+    Item 	createBase64Binary (std::istream &aStream);
+    Item 	createBase64Binary (const unsigned char *aBinData, size_t aLength);
+    Item 	createBoolean (bool aValue);
+    Item 	createByte (char aByte);
+    Item 	createDate (const std::string &aDate);
+    Item 	createDate (short aYear, short aMonth, short aDay);
+    Item 	createDateTime (const std::string &aDateTimeValue);
+    Item 	createDateTime (short aYear, short aMonth, short aDay, short aHour, short aMinute, double aSecond, short aTimeZone_hours);
+    Item 	createDecimal (const std::string &aValue);
+    Item 	createDecimalFromDouble (double aValue);
+    Item 	createDecimalFromLong (unsigned long aValue);
+    Item 	createDouble (const std::string &aValue);
+    Item 	createDouble (double aValue);
+    Item 	createDuration (const std::string &aValue);
+    Item 	createDuration (short aYear, short aMonths, short aDays, short aHours, short aMinutes, double aSeconds);
+    //Item 	createElementNode (Item &aParent, Item aNodeName, Item aTypeName, bool aHasTypedValue, bool aHasEmptyValue, std::vector< std::pair< std::string, std::string > > aNsBindings);
+    Item 	createFloat (const std::string &aValue);
+    Item 	createFloat (float aValue);
+    Item 	createGDay (const std::string &aValue);
+    Item 	createGDay (short aDay);
+    Item 	createGMonth (const std::string &aValue);
+    Item 	createGMonth (short aMonth);
+    Item 	createGMonthDay (const std::string &aValue);
+    Item 	createGMonthDay (short aMonth, short aDay);
+    Item 	createGYear (short aYear);
+    Item 	createGYear (const std::string &aValue);
+    Item 	createGYearMonth (const std::string &aValue);
+    Item 	createGYearMonth (short aYear, short aMonth);
+    Item 	createHexBinary (const char *aHexData, size_t aSize);
+    Item 	createInt (int aInt);
+    Item 	createInteger (const std::string &aInteger);
+    Item 	createInteger (long long aInteger);
+    Item 	createLong (long long aLong);
+    Item 	createNCName (const std::string &aValue);
+    Item 	createNegativeInteger (long long aValue);
+    Item 	createNonNegativeInteger (unsigned long long aValue);
+    Item 	createNonPositiveInteger (long long aValue);
+    Item 	createPositiveInteger (unsigned long long aValue);
+    Item 	createQName (const std::string &aNamespace, const std::string &aPrefix, const std::string &aLocalname);
+    Item 	createQName (const std::string &aNamespace, const std::string &aLocalname);
+    Item 	createQName (const std::string &aQNameString);
+    Item 	createShort (short aShort);
+    //Item 	createStreamableString (std::istream &stream, StreamReleaser streamReleaser, bool seekable=false);
+    Item 	createString (const std::string &aString);
+    Item 	createTextNode (Item parent, std::string content);
+    Item 	createTime (short aHour, short aMinute, double aSecond, short aTimeZone_hours);
+    Item 	createTime (short aHour, short aMinute, double aSecond);
+    Item 	createTime (const std::string &aValue);
+    Item 	createUnsignedByte (const unsigned char aValue);
+    Item 	createUnsignedInt (unsigned int aValue);
+    Item 	createUnsignedLong (unsigned long long aValue);
+    Item 	createUnsignedShort (unsigned short aValue);
+}; // class ItemFactory

=== added file 'swig/ItemFactory.i'
--- swig/ItemFactory.i	1970-01-01 00:00:00 +0000
+++ swig/ItemFactory.i	2011-10-27 20:59:25 +0000
@@ -0,0 +1,192 @@
+
+%{  // start Implementation
+
+
+ 
+  Item 	ItemFactory::createAnyURI (const std::string &aURI){
+    return Item(theItemFactory->createAnyURI(aURI));
+  }
+  
+  Item 	ItemFactory::createAttributeNode (Item aParent, Item aNodeName, Item aTypeName, Item aTypedValue){
+    return Item( theItemFactory->createAttributeNode( aParent.theItem, aNodeName.theItem, aTypeName.theItem, aTypedValue.theItem ));
+  }
+  
+  Item 	ItemFactory::createAttributeNode (Item aParent, Item aNodeName, Item aTypeName, std::vector< Item > aTypedValue){
+
+    std::vector< zorba::Item > typedValue;
+    typedValue.reserve(aTypedValue.size());
+    std::vector< Item >::iterator iter;
+    for(iter = aTypedValue.begin(); iter != aTypedValue.end(); iter++) {
+      typedValue.push_back((*iter).theItem);
+    }
+    return Item( theItemFactory->createAttributeNode (aParent.theItem, aNodeName.theItem, aTypeName.theItem, typedValue ));
+  }
+  
+  Item 	ItemFactory::createBase64Binary (const char *aBinData, size_t aLength){
+    return Item( theItemFactory->createBase64Binary(aBinData, aLength));
+  }
+  Item 	ItemFactory::createBase64Binary (std::istream &aStream){
+    return Item( theItemFactory->createBase64Binary(aStream));
+  }
+  Item 	ItemFactory::createBase64Binary (const unsigned char *aBinData, size_t aLength){
+    return Item( theItemFactory->createBase64Binary(aBinData, aLength));
+  }
+  Item 	ItemFactory::createBoolean (bool aValue){
+    return Item( theItemFactory->createBoolean(aValue));
+  }
+  Item 	ItemFactory::createByte (char aByte){
+    return Item( theItemFactory->createByte(aByte));
+  }
+  Item 	ItemFactory::createDate (const std::string &aDate){
+    return Item( theItemFactory->createDate(aDate));
+  }
+  Item 	ItemFactory::createDate (short aYear, short aMonth, short aDay){
+    return Item( theItemFactory->createDate (aYear, aMonth, aDay));
+  }
+  Item 	ItemFactory::createDateTime (const std::string &aDateTimeValue){
+    return Item( theItemFactory->createDateTime (aDateTimeValue));
+  }
+  Item 	ItemFactory::createDateTime (short aYear, short aMonth, short aDay, short aHour, short aMinute, double aSecond, short aTimeZone_hours){
+    return Item( theItemFactory->createDateTime (aYear, aMonth, aDay, aHour, aMinute, aSecond, aTimeZone_hours));
+  }
+  Item 	ItemFactory::createDecimal (const std::string &aValue){
+    return Item( theItemFactory->createDecimal (aValue));
+  }
+  Item 	ItemFactory::createDecimalFromDouble (double aValue){
+    return Item( theItemFactory->createDecimalFromDouble (aValue));
+  }
+  Item 	ItemFactory::createDecimalFromLong (unsigned long aValue){
+    return Item( theItemFactory->createDecimalFromLong (aValue));
+  }
+  Item 	ItemFactory::createDouble (const std::string &aValue){
+    return Item( theItemFactory->createDouble (aValue));
+  }
+  Item 	ItemFactory::createDouble (double aValue){
+    return Item( theItemFactory->createDouble (aValue));
+  }
+  Item 	ItemFactory::createDuration (const std::string &aValue){
+    return Item( theItemFactory->createDuration (aValue));
+  }
+  Item 	ItemFactory::createDuration (short aYear, short aMonths, short aDays, short aHours, short aMinutes, double aSeconds){
+    return Item( theItemFactory->createDuration (aYear, aMonths, aDays, aHours, aMinutes, aSeconds));
+  }
+  /*
+  Item 	ItemFactory::createElementNode (Item &aParent, Item aNodeName, Item aTypeName, bool aHasTypedValue, bool aHasEmptyValue, std::vector< std::pair< std::string, std::string > > aNsBindings){
+    return Item( theItemFactory->createElementNode (aParent.theItem, aNodeName.theItem, aTypeName.theItem, aHasTypedValue, aHasEmptyValue, aNsBindings));
+  }
+  */
+  Item 	ItemFactory::createFloat (const std::string &aValue){
+    return Item( theItemFactory->createFloat (aValue));
+  }
+  Item 	ItemFactory::createFloat (float aValue){
+    return Item( theItemFactory->createFloat (aValue));
+  }
+  Item 	ItemFactory::createGDay (const std::string &aValue){
+    return Item( theItemFactory->createGDay (aValue));
+  }
+  Item 	ItemFactory::createGDay (short aDay){
+    return Item( theItemFactory->createGDay (aDay));
+  }
+  Item 	ItemFactory::createGMonth (const std::string &aValue){
+    return Item( theItemFactory->createGMonth (aValue));
+  }
+  Item 	ItemFactory::createGMonth (short aMonth){
+    return Item( theItemFactory->createGMonth (aMonth));
+  }
+  Item 	ItemFactory::createGMonthDay (const std::string &aValue){
+    return Item( theItemFactory->createGMonthDay (aValue));
+  }
+  Item 	ItemFactory::createGMonthDay (short aMonth, short aDay){
+    return Item( theItemFactory->createGMonthDay (aMonth, aDay));
+  }
+  Item 	ItemFactory::createGYear (short aYear){
+    return Item( theItemFactory->createGYear (aYear));
+  }
+  Item 	ItemFactory::createGYear (const std::string &aValue){
+    return Item( theItemFactory->createGYear (aValue));
+  }
+  Item 	ItemFactory::createGYearMonth (const std::string &aValue){
+    return Item( theItemFactory->createGYearMonth (aValue));
+  }
+  Item 	ItemFactory::createGYearMonth (short aYear, short aMonth){
+    return Item( theItemFactory->createGYearMonth (aYear, aMonth));
+  }
+  Item 	ItemFactory::createHexBinary (const char *aHexData, size_t aSize){
+    return Item( theItemFactory->createHexBinary (aHexData, aSize));
+  }
+  Item 	ItemFactory::createInt (int aInt){
+    return Item( theItemFactory->createInt (aInt));
+  }
+  Item 	ItemFactory::createInteger (const std::string &aInteger){
+    return Item( theItemFactory->createInteger (aInteger));
+  }
+  Item 	ItemFactory::createInteger (long long aInteger){
+    return Item( theItemFactory->createInteger (aInteger));
+  }
+  Item 	ItemFactory::createLong (long long aLong){
+    return Item( theItemFactory->createLong (aLong));
+  }
+  Item 	ItemFactory::createNCName (const std::string &aValue){
+    return Item( theItemFactory->createNCName (aValue));
+  }
+  Item 	ItemFactory::createNegativeInteger (long long aValue){
+    return Item( theItemFactory->createNegativeInteger (aValue));
+  }
+  Item 	ItemFactory::createNonNegativeInteger (unsigned long long aValue){
+    return Item( theItemFactory->createNonNegativeInteger (aValue));
+  }
+  Item 	ItemFactory::createNonPositiveInteger (long long aValue){
+    return Item( theItemFactory->createNonPositiveInteger (aValue));
+  }
+  Item 	ItemFactory::createPositiveInteger (unsigned long long aValue){
+    return Item( theItemFactory->createPositiveInteger (aValue));
+  }
+  Item 	ItemFactory::createQName (const std::string &aNamespace, const std::string &aPrefix, const std::string &aLocalname){
+    return Item( theItemFactory->createQName (aNamespace, aPrefix, aLocalname));
+  }
+  Item 	ItemFactory::createQName (const std::string &aNamespace, const std::string &aLocalname){
+    return Item( theItemFactory->createQName (aNamespace, aLocalname));
+  }
+  Item 	ItemFactory::createQName (const std::string &aQNameString){
+    return Item( theItemFactory->createQName (aQNameString));
+  }
+  Item 	ItemFactory::createShort (short aShort){
+    return Item( theItemFactory->createShort (aShort));
+  }
+  /*
+  Item 	ItemFactory::createStreamableString (std::istream &stream, StreamReleaser streamReleaser, bool seekable=false){
+    return Item( theItemFactory->createStreamableString (std::istream &stream, StreamReleaser streamReleaser, seekable));
+  }
+  */
+  Item 	ItemFactory::createString (const std::string &aString){
+    return Item( theItemFactory->createString (aString));
+  }
+  Item 	ItemFactory::createTextNode (Item parent, std::string content){
+    return Item( theItemFactory->createTextNode (parent.theItem, content));
+  }
+  Item 	ItemFactory::createTime (short aHour, short aMinute, double aSecond, short aTimeZone_hours){
+    return Item( theItemFactory->createTime (aHour, aMinute, aSecond, aTimeZone_hours));
+  }
+  Item 	ItemFactory::createTime (short aHour, short aMinute, double aSecond){
+    return Item( theItemFactory->createTime (aHour, aMinute, aSecond));
+  }
+  Item 	ItemFactory::createTime (const std::string &aValue){
+    return Item( theItemFactory->createTime (aValue));
+  }
+  Item 	ItemFactory::createUnsignedByte (const unsigned char aValue){
+    return Item( theItemFactory->createUnsignedByte (aValue));
+  }
+  Item 	ItemFactory::createUnsignedInt (unsigned int aValue){
+    return Item( theItemFactory->createUnsignedInt (aValue));
+  }
+  Item 	ItemFactory::createUnsignedLong (unsigned long long aValue){
+    return Item( theItemFactory->createUnsignedLong (aValue));
+  }
+  Item 	ItemFactory::createUnsignedShort (unsigned short aValue){
+    return Item( theItemFactory->createUnsignedShort (aValue));
+  }
+
+
+%}  // end Implementation
+
+%include "ItemFactory.h"
\ No newline at end of file

=== added file 'swig/StaticContext.h'
--- swig/StaticContext.h	1970-01-01 00:00:00 +0000
+++ swig/StaticContext.h	2011-10-27 20:59:25 +0000
@@ -0,0 +1,69 @@
+#include <zorba/static_context_consts.h>
+
+class StaticContext 
+{
+friend class Zorba;
+friend class XQuery;
+
+private:
+  zorba::StaticContext_t theStaticContext;
+public:
+  StaticContext();
+  StaticContext(const StaticContext& aStaticContext);
+  StaticContext(zorba::StaticContext_t aStaticContext);
+  
+  virtual void addColation(const std::string& aURI); 
+  virtual bool addNamespace(const std::string& aPrefix,
+                            const std::string& aURI);
+  void addReference() const;
+  virtual bool containsFunction(const std::string &aFnNameUri, 
+                                const std::string &aFnNameLocal, 
+                                int arity) const;
+
+  virtual StaticContext createChildContext() const;
+  virtual void declareOption(const Item &aQName, 
+                             const std::string &aOptionVal);
+  virtual void disableFunction(const Item &aQName, int arity);
+
+  virtual void free ();
+  virtual std::string getBaseURI () const;
+  virtual zorba::boundary_space_mode_t getBoundarySpacePolicy () const;
+
+  virtual zorba::construction_mode_t getConstructionMode () const;
+  virtual void getCopyNamespacesMode (zorba::preserve_mode_t &aPreserve, zorba::inherit_mode_t &aInherit) const;
+  virtual std::string getDefaultCollation () const;
+  virtual std::string getDefaultElementAndTypeNamespace () const;
+  virtual std::string getDefaultFunctionNamespace () const;
+  virtual zorba::order_empty_mode_t getDefaultOrderForEmptySequences () const;
+
+  virtual std::string getNamespaceURIByPrefix(const std::string &aPrefix) const;
+  virtual bool getOption(const Item &aQName, std::string &aOptionValue) const;
+  virtual zorba::ordering_mode_t getOrderingMode() const;
+  long getRefCount() const;
+  virtual zorba::validation_mode_t getRevalidationMode();
+  virtual zorba::xpath1_0compatib_mode_t getXPath1_0CompatibMode () const;
+  virtual void loadProlog (const std::string & aProlog, 
+                           const CompilerHints &hints);
+
+  void removeReference ();
+  virtual void resetTraceStream ();
+  virtual bool setBaseURI (const std::string &aBaseURI);
+  virtual bool setBoundarySpacePolicy (zorba::boundary_space_mode_t aMode);
+
+  virtual bool setConstructionMode (zorba::construction_mode_t aMode);
+
+  virtual bool setCopyNamespacesMode (zorba::preserve_mode_t aPreserve, 
+                                      zorba::inherit_mode_t aInherit);
+  virtual void setDefaultCollation (const std::string &aURI);
+  virtual bool setDefaultElementAndTypeNamespace (const std::string &aURI);
+  virtual bool setDefaultFunctionNamespace (const std::string &aURI);
+  virtual bool setDefaultOrderForEmptySequences (zorba::order_empty_mode_t aMode);
+
+  virtual bool setOrderingMode (zorba::ordering_mode_t aMode);
+  virtual void setRevalidationMode (zorba::validation_mode_t aMode);
+
+  virtual bool setXPath1_0CompatibMode (zorba::xpath1_0compatib_mode_t aMode);
+
+  void destroy();
+}; // class StaticContext
+

=== modified file 'swig/StaticContext.i'
--- swig/StaticContext.i	2011-06-29 20:05:38 +0000
+++ swig/StaticContext.i	2011-10-27 20:59:25 +0000
@@ -20,149 +20,144 @@
 #include <zorba/static_context_consts.h>
 
 
-class StaticContext 
-{
-  friend class Zorba;
+StaticContext::StaticContext() {}
 
-private:
-  zorba::StaticContext_t theStaticContext;
-public:
-  StaticContext() {}
-  StaticContext(const StaticContext& aStaticContext) : 
+StaticContext::StaticContext(const StaticContext& aStaticContext) : 
     theStaticContext(aStaticContext.theStaticContext) {}
-  StaticContext(zorba::StaticContext_t aStaticContext) : 
+    
+StaticContext::StaticContext(zorba::StaticContext_t aStaticContext) : 
     theStaticContext(aStaticContext) {}
 
-  virtual void addColation(const std::string& aURI)
+void StaticContext::addColation(const std::string& aURI)
   { theStaticContext->addCollation(aURI); }
 
-  virtual bool addNamespace(const std::string& aPrefix, 
+bool StaticContext::addNamespace(const std::string& aPrefix, 
                             const std::string& aURI)
   { return theStaticContext->addNamespace(aPrefix, aURI); }
 
-  void addReference() const
+void StaticContext::addReference() const
   { theStaticContext->addReference(); }
   
-  virtual bool containsFunction(const std::string &aFnNameUri, 
+bool StaticContext::containsFunction(const std::string &aFnNameUri, 
                                 const std::string &aFnNameLocal, 
                                 int arity) const 
   { return theStaticContext->containsFunction(aFnNameUri, aFnNameLocal,
                                               arity); }
 
-  virtual StaticContext	createChildContext() const
+StaticContext	StaticContext::createChildContext() const
   { return StaticContext(theStaticContext->createChildContext()); }
   
-  virtual void 	declareOption (const Item &aQName, 
+void 	StaticContext::declareOption (const Item &aQName, 
                                const std::string &aOptionVal)
   { return theStaticContext->declareOption(aQName.theItem, aOptionVal); }
 
-  virtual void 	disableFunction (const Item &aQName, int arity)
+void 	StaticContext::disableFunction (const Item &aQName, int arity)
   { theStaticContext->disableFunction( aQName.theItem, arity); }
 
-  virtual void 	free ()
+void 	StaticContext::free ()
   { theStaticContext->free(); }
 
-  virtual std::string getBaseURI () const
+std::string StaticContext::getBaseURI () const
   { return std::string(theStaticContext->getBaseURI().c_str()); }
 
-  virtual zorba::boundary_space_mode_t getBoundarySpacePolicy() const
+zorba::boundary_space_mode_t StaticContext::getBoundarySpacePolicy() const
   { return theStaticContext->getBoundarySpacePolicy(); }
 
-  virtual zorba::construction_mode_t getConstructionMode () const 
+zorba::construction_mode_t StaticContext::getConstructionMode () const 
   { return theStaticContext->getConstructionMode(); }		
 
-  virtual void 	getCopyNamespacesMode (zorba::preserve_mode_t &aPreserve, zorba::inherit_mode_t &aInherit) const
+void 	StaticContext::getCopyNamespacesMode (zorba::preserve_mode_t &aPreserve, zorba::inherit_mode_t &aInherit) const
   { return theStaticContext->getCopyNamespacesMode(aPreserve, aInherit); }		
 
-  virtual std::string getDefaultCollation () const 
+std::string StaticContext::getDefaultCollation () const 
   { return std::string(theStaticContext->getDefaultCollation().c_str()); }
 
-  virtual std::string getDefaultElementAndTypeNamespace () const 
+std::string StaticContext::getDefaultElementAndTypeNamespace () const 
   { 
     return std::string(theStaticContext->getDefaultElementAndTypeNamespace().
                        c_str()); 
   }
 
-  virtual std::string getDefaultFunctionNamespace () const 
+std::string StaticContext::getDefaultFunctionNamespace () const 
   { 
     return std::string(theStaticContext->getDefaultFunctionNamespace().c_str());
   }
 
-  virtual zorba::order_empty_mode_t getDefaultOrderForEmptySequences() const
+zorba::order_empty_mode_t StaticContext::getDefaultOrderForEmptySequences() const
   { return theStaticContext->getDefaultOrderForEmptySequences(); }
 
-  virtual std::string getNamespaceURIByPrefix(const std::string &aPrefix) const
+std::string StaticContext::getNamespaceURIByPrefix(const std::string &aPrefix) const
   {
     return std::string(theStaticContext->getNamespaceURIByPrefix(aPrefix).
                        c_str());
   }
 
-  virtual bool getOption(const Item &aQName, std::string &aOptionValue) const
+bool StaticContext::getOption(const Item &aQName, std::string &aOptionValue) const
   { 
     zorba::String optVal = zorba::String(aOptionValue.c_str());
     return theStaticContext->getOption(aQName.theItem, optVal); 
   }
 
-  virtual zorba::ordering_mode_t getOrderingMode () const
+zorba::ordering_mode_t StaticContext::getOrderingMode () const
   { return theStaticContext->getOrderingMode(); }
 
-  long getRefCount () const
+long StaticContext::getRefCount () const
   { return theStaticContext->getRefCount(); }
 
-  virtual zorba::validation_mode_t getRevalidationMode ()
+zorba::validation_mode_t StaticContext::getRevalidationMode ()
   { return theStaticContext->getRevalidationMode(); }
 
-  virtual zorba::xpath1_0compatib_mode_t getXPath1_0CompatibMode () const
+zorba::xpath1_0compatib_mode_t StaticContext::getXPath1_0CompatibMode () const
   { return theStaticContext->getXPath1_0CompatibMode(); } 
 
-  virtual void loadProlog (const std::string & aProlog, 
+void StaticContext::loadProlog (const std::string & aProlog, 
                            const CompilerHints &hints)
   { theStaticContext->loadProlog( aProlog, hints.theCompilerHints); }
 
-  void removeReference ()
+void StaticContext::removeReference ()
   { theStaticContext->removeReference(); }
 
-  virtual void resetTraceStream ()
+void StaticContext::resetTraceStream ()
   { theStaticContext->resetTraceStream(); }
 
-  virtual bool setBaseURI (const std::string &aBaseURI)
+bool StaticContext::setBaseURI (const std::string &aBaseURI)
   { return theStaticContext->setBaseURI(aBaseURI); }
 
-  virtual bool setBoundarySpacePolicy (zorba::boundary_space_mode_t aMode)
+bool StaticContext::setBoundarySpacePolicy (zorba::boundary_space_mode_t aMode)
   { return theStaticContext->setBoundarySpacePolicy(aMode); } 
 
-  virtual bool setConstructionMode (zorba::construction_mode_t aMode)
+bool StaticContext::setConstructionMode (zorba::construction_mode_t aMode)
   { return theStaticContext->setConstructionMode(aMode); } 
 
-  virtual bool setCopyNamespacesMode (zorba::preserve_mode_t aPreserve, 
+bool StaticContext::setCopyNamespacesMode (zorba::preserve_mode_t aPreserve, 
     zorba::inherit_mode_t aInherit)
   { return theStaticContext->setCopyNamespacesMode(aPreserve, aInherit); }   
 
-  virtual void setDefaultCollation (const std::string &aURI)
+void StaticContext::setDefaultCollation (const std::string &aURI)
   { theStaticContext->setDefaultCollation(aURI); }
 
-  virtual bool setDefaultElementAndTypeNamespace (const std::string &aURI)
+bool StaticContext::setDefaultElementAndTypeNamespace (const std::string &aURI)
   { return theStaticContext->setDefaultElementAndTypeNamespace(aURI); }
 
-  virtual bool setDefaultFunctionNamespace (const std::string &aURI)
+bool StaticContext::setDefaultFunctionNamespace (const std::string &aURI)
   { return theStaticContext->setDefaultFunctionNamespace(aURI); }
 
-  virtual bool setDefaultOrderForEmptySequences (zorba::order_empty_mode_t aMode)
+bool StaticContext::setDefaultOrderForEmptySequences (zorba::order_empty_mode_t aMode)
   { return theStaticContext->setDefaultOrderForEmptySequences(aMode); } 
 
-  virtual bool setOrderingMode (zorba::ordering_mode_t aMode)
+bool StaticContext::setOrderingMode (zorba::ordering_mode_t aMode)
   { return theStaticContext->setOrderingMode(aMode); } 
 
-  virtual void setRevalidationMode (zorba::validation_mode_t aMode)
+void StaticContext::setRevalidationMode (zorba::validation_mode_t aMode)
   { return theStaticContext->setRevalidationMode(aMode); } 
 
-  virtual bool setXPath1_0CompatibMode (zorba::xpath1_0compatib_mode_t aMode)
+bool StaticContext::setXPath1_0CompatibMode (zorba::xpath1_0compatib_mode_t aMode)
   { return theStaticContext->setXPath1_0CompatibMode(aMode); }
 
-  void destroy() 
+void StaticContext::destroy() 
   { theStaticContext = 0; }
    
-}; // class StaticContext
+ // class StaticContext
 
 
 
@@ -209,63 +204,4 @@
 %rename(VALIDATE_LAX) validate_lax;
 %rename(VALIDATE_STRICT) validate_strict;
 
-#include <zorba/static_context_consts.h>
-
-
-class StaticContext 
-{
- public:
-  virtual void addColation(const std::string& aURI);  
-  virtual bool addNamespace(const std::string& aPrefix, 
-                            const std::string& aURI);
-  void addReference() const;
-  virtual bool containsFunction(const std::string &aFnNameUri, 
-                                const std::string &aFnNameLocal, 
-                                int arity) const;
-
-  virtual StaticContext createChildContext() const;
-  virtual void declareOption(const Item &aQName, 
-                             const std::string &aOptionVal);
-  virtual void disableFunction(const Item &aQName, int arity);
-
-  virtual void free ();
-  virtual std::string getBaseURI () const;
-  virtual zorba::boundary_space_mode_t getBoundarySpacePolicy () const;
-
-  virtual zorba::construction_mode_t getConstructionMode () const;
-  virtual void getCopyNamespacesMode (zorba::preserve_mode_t &aPreserve, zorba::inherit_mode_t &aInherit) const;
-  virtual std::string getDefaultCollation () const;
-  virtual std::string getDefaultElementAndTypeNamespace () const;
-  virtual std::string getDefaultFunctionNamespace () const;
-  virtual zorba::order_empty_mode_t getDefaultOrderForEmptySequences () const;
-
-  virtual std::string getNamespaceURIByPrefix(const std::string &aPrefix) const;
-  virtual bool getOption(const Item &aQName, std::string &aOptionValue) const;
-  virtual zorba::ordering_mode_t getOrderingMode() const;
-  long getRefCount() const;
-  virtual zorba::validation_mode_t getRevalidationMode();
-  virtual zorba::xpath1_0compatib_mode_t getXPath1_0CompatibMode () const;
-  virtual void loadProlog (const std::string &, 
-                           const Zorba_CompilerHints_t &hints);
-
-  void removeReference ();
-  virtual void resetTraceStream ();
-  virtual bool setBaseURI (const std::string &aBaseURI);
-  virtual bool setBoundarySpacePolicy (zorba::boundary_space_mode_t aMode);
-
-  virtual bool setConstructionMode (zorba::construction_mode_t aMode);
-
-  virtual bool setCopyNamespacesMode (zorba::preserve_mode_t aPreserve, 
-                                      zorba::inherit_mode_t aInherit);
-  virtual void setDefaultCollation (const std::string &aURI);
-  virtual bool setDefaultElementAndTypeNamespace (const std::string &aURI);
-  virtual bool setDefaultFunctionNamespace (const std::string &aURI);
-  virtual bool setDefaultOrderForEmptySequences (zorba::order_empty_mode_t aMode);
-
-  virtual bool setOrderingMode (zorba::ordering_mode_t aMode);
-  virtual void setRevalidationMode (zorba::validation_mode_t aMode);
-
-  virtual bool setXPath1_0CompatibMode (zorba::xpath1_0compatib_mode_t aMode);
-
-  void destroy();
-}; // class StaticContext
+%include "StaticContext.h"

=== modified file 'swig/XQuery.i'
--- swig/XQuery.i	2011-07-20 01:40:52 +0000
+++ swig/XQuery.i	2011-10-27 20:59:25 +0000
@@ -74,6 +74,7 @@
   friend class DocumentManager; 
   friend class SingletonIterator;
   friend class DynamicContext;
+  friend class ItemFactory;
 
 private:
   zorba::Item theItem;
@@ -209,6 +210,17 @@
     return lStream.str();
   }
 
+  void compile (const std::string &aQuery)
+  {
+    theQuery->compile(aQuery);
+  }
+
+  void compile (const std::string &aQuery, StaticContext &aStaticContext )
+  {
+    Zorba_CompilerHints_t hints;
+    theQuery->compile(aQuery, aStaticContext.theStaticContext, hints);
+  }
+
   std::string printPlanAsXML()
   {
     std::ostringstream lStream;
@@ -322,6 +334,8 @@
   std::string execute();
   std::string printPlanAsXML();
   std::string printPlanAsDOT();
+  void compile (const std::string &aQuery);
+  void compile (const std::string &aQuery, StaticContext &aStaticContext);
 
 #ifdef SWIGPYTHON
   void executeSAX(SAX2ContentHandlerProxy* contentHandlerProxy);

=== modified file 'swig/Zorba.i'
--- swig/Zorba.i	2011-07-13 21:24:04 +0000
+++ swig/Zorba.i	2011-10-27 20:59:25 +0000
@@ -16,6 +16,11 @@
     return Zorba(zorba::Zorba::getInstance(aStore.getStore()));
   }
   
+  ItemFactory getItemFactory()
+  {
+    return ItemFactory(theZorba->getItemFactory());
+  }
+
   StaticContext createStaticContext()
   {
     return StaticContext(theZorba->createStaticContext());
@@ -25,7 +30,25 @@
   {
     return XQuery(theZorba->compileQuery(aStr));
   }
-/*
+
+  XQuery createQuery() 
+  {
+    return XQuery(theZorba->createQuery());
+  }
+
+  XQuery compileQuery(
+    const std::string& aStr,
+    StaticContext &aStaticContext )
+  { 
+    return XQuery(
+      theZorba->compileQuery(
+        aStr,
+        aStaticContext.theStaticContext
+      )
+    );
+  }
+
+  /*
   //--->> DiagnosticHandler implementations are postponed
   XQuery compileQuery(
     const std::string& aStr,
@@ -85,7 +108,11 @@
  public:
   static Zorba getInstance(const Store&);
   StaticContext createStaticContext();
+  XQuery createQuery();
   XQuery compileQuery(const std::string& aStr);
+  XQuery compileQuery(const std::string& aStr, StaticContext &aStaticContext );
+  ItemFactory getItemFactory();
+  
   /*
   XQuery compileQuery(const std::string& aStr, DiagnosticHandler* aDiagnosticHandler);
   XQuery compileQuery(const std::string& aStr, StaticContext &aStaticContext, 

=== modified file 'swig/java/CMakeLists.txt'
--- swig/java/CMakeLists.txt	2011-09-02 19:58:59 +0000
+++ swig/java/CMakeLists.txt	2011-10-27 20:59:25 +0000
@@ -60,6 +60,8 @@
   MESSAGE(STATUS "Java module install path: " ${JAVA_SITEARCH_DIR})
 
   FILE(GLOB JAVA_SWIG_FILES "${CMAKE_CURRENT_BINARY_DIR}/*.java")
+  CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/../StaticContext.h" "${CMAKE_CURRENT_BINARY_DIR}/StaticContext.h")
+  CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/../ItemFactory.h" "${CMAKE_CURRENT_BINARY_DIR}/ItemFactory.h")
 
   IF ( APPLE )
     INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/${ZORBA_SWIG_LIB_PREFIX}libzorba_api.jnilib DESTINATION ${JAVA_SITEARCH_DIR})

=== modified file 'swig/php/CMakeLists.txt'
--- swig/php/CMakeLists.txt	2011-09-02 19:58:59 +0000
+++ swig/php/CMakeLists.txt	2011-10-27 20:59:25 +0000
@@ -38,6 +38,9 @@
     SWIG_LINK_LIBRARIES (zorba_api ${PHP5_LIBRARY})
   ENDIF (WIN32)
 
+  CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/../StaticContext.h" "${CMAKE_CURRENT_BINARY_DIR}/StaticContext.h")
+  CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/../ItemFactory.h" "${CMAKE_CURRENT_BINARY_DIR}/ItemFactory.h")
+
   # The following fix was added because of the changes in CMake 2.8, which have the
   # result of naming the java binding library "liblibzorba_api.so" instead of "libzorba_api.so"
   SET_TARGET_PROPERTIES( ${SWIG_MODULE_zorba_api_REAL_NAME} PROPERTIES PROJECT_LABEL "Api_PHP" )

=== modified file 'swig/php/zorba_api.i'
--- swig/php/zorba_api.i	2011-07-12 00:51:50 +0000
+++ swig/php/zorba_api.i	2011-10-27 20:59:25 +0000
@@ -28,6 +28,12 @@
   #define PHP_COMPILER_ID "VC6"
 #endif
 #endif
+
+#if defined(_MSC_VER)
+#define strtoll _strtoi64
+#define strtoull _strtoui64
+#endif
+
 %}
 
 

=== modified file 'swig/python/CMakeLists.txt'
--- swig/python/CMakeLists.txt	2011-09-02 19:58:59 +0000
+++ swig/python/CMakeLists.txt	2011-10-27 20:59:25 +0000
@@ -29,6 +29,8 @@
   )
    
   SET (PYTHON_INSTALL_PATH "${CMAKE_INSTALL_PREFIX}/share/python")
+  CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/../StaticContext.h" "${CMAKE_CURRENT_BINARY_DIR}/StaticContext.h")
+  CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/../ItemFactory.h" "${CMAKE_CURRENT_BINARY_DIR}/ItemFactory.h")
   MESSAGE (STATUS "SWIG Python: Python module install path: " ${PYTHON_INSTALL_PATH})
 
   IF (NOT WIN32)   

=== modified file 'swig/ruby/CMakeLists.txt'
--- swig/ruby/CMakeLists.txt	2011-09-02 19:58:59 +0000
+++ swig/ruby/CMakeLists.txt	2011-10-27 20:59:25 +0000
@@ -28,6 +28,13 @@
   ELSE (WIN32)
     SWIG_ADD_MODULE(zorba_api ruby zorba_api.i)
     SWIG_LINK_LIBRARIES(zorba_api zorba_simplestore ${RUBY_LIBRARY})
+    # Necessary because UseSWIG.cmake uses ADD_LIBRARY(..MODULE..), which
+    # apparently doesn't allow CMake's RPATH-rewriting magic to work.
+    GET_TARGET_PROPERTY(_rpath zorba_simplestore LOCATION)
+    GET_FILENAME_COMPONENT(_rpath "${_rpath}" PATH)
+    SET_TARGET_PROPERTIES(zorba_api PROPERTIES
+      INSTALL_RPATH "${CMAKE_INSTALL_RPATH}:${_rpath}"
+      BUILD_WITH_INSTALL_RPATH ON)
   ENDIF (WIN32)
 
   IF ( APPLE )
@@ -43,6 +50,8 @@
   EXECUTE_PROCESS(COMMAND ${RUBY_EXECUTABLE} -r rbconfig -e "print Config::CONFIG['sitearchdir']"
     OUTPUT_VARIABLE RUBY_SITEARCH_DIR)
   #STRING(REPLACE "/usr/" "" RUBY_SITEARCH_DIR "${RUBY_SITEARCH_DIR}" )
+  CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/../StaticContext.h" "${CMAKE_CURRENT_BINARY_DIR}/StaticContext.h")
+  CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/../ItemFactory.h" "${CMAKE_CURRENT_BINARY_DIR}/ItemFactory.h")
   
   SET (RUBY_SITEARCH_DIR "${CMAKE_INSTALL_PREFIX}/share/ruby")
   
@@ -67,6 +76,7 @@
       
     ENDIF ( LINUX )
   ENDIF ( APPLE )
+
 ELSE (RUBY_LIBRARY AND RUBY_INCLUDE_PATH)
   MESSAGE(STATUS "SWIG Ruby: binding not generated because library and include files are not installed.")
 ENDIF (RUBY_LIBRARY AND RUBY_INCLUDE_PATH)

=== modified file 'swig/zorba_api.i'
--- swig/zorba_api.i	2011-07-13 21:24:04 +0000
+++ swig/zorba_api.i	2011-10-27 20:59:25 +0000
@@ -52,7 +52,6 @@
   class Item;
   class Iterator;
   class XQuery;
-  class StaticContext;
   class Store;
   class Zorba;
 
@@ -65,6 +64,9 @@
   class UserException;
   class ZorbaException;
 
+  #include "StaticContext.h"
+  #include "ItemFactory.h"
+
 %}
 
 
@@ -77,5 +79,6 @@
 %include "CompilerHints.i"
 %include "StaticContext.i"
 %include "Zorba.i"
+%include "ItemFactory.i"
 
 

=== added file 'test/rbkt/ExpQueryResults/zorba/nodes/position_1.xml.res'
--- test/rbkt/ExpQueryResults/zorba/nodes/position_1.xml.res	1970-01-01 00:00:00 +0000
+++ test/rbkt/ExpQueryResults/zorba/nodes/position_1.xml.res	2011-10-27 20:59:25 +0000
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<result><ancestor-of>true true false false false false false</ancestor-of><following-sibling-of>true true false false false false false false</following-sibling-of><following-of>true false false false false false</following-of><descendant-of>true true false false false false false false</descendant-of><in-subtree-of>true true true false false false false false</in-subtree-of><preceding-sibling-of>true true false false false false false false</preceding-sibling-of><preceding-of>true false false false false false</preceding-of></result>
\ No newline at end of file

=== added file 'test/rbkt/ExpQueryResults/zorba/nodes/position_1_parsed.xml.res'
--- test/rbkt/ExpQueryResults/zorba/nodes/position_1_parsed.xml.res	1970-01-01 00:00:00 +0000
+++ test/rbkt/ExpQueryResults/zorba/nodes/position_1_parsed.xml.res	2011-10-27 20:59:25 +0000
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<result><ancestor-of>true true false false false false false</ancestor-of><following-sibling-of>true true false false false false false false</following-sibling-of><following-of>true false false false false false</following-of><descendant-of>true true false false false false false false</descendant-of><in-subtree-of>true true true false false false false false</in-subtree-of><preceding-sibling-of>true true false false false false false false</preceding-sibling-of><preceding-of>true false false false false false</preceding-of></result>
\ No newline at end of file

=== added file 'test/rbkt/ExpQueryResults/zorba/nodes/position_2.xml.res'
--- test/rbkt/ExpQueryResults/zorba/nodes/position_2.xml.res	1970-01-01 00:00:00 +0000
+++ test/rbkt/ExpQueryResults/zorba/nodes/position_2.xml.res	2011-10-27 20:59:25 +0000
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<result><child-of>true true false false false false false false</child-of><attribute-of>true false false false false false false false false</attribute-of><parent-of>true true false false false false false false</parent-of><preceding-in-document-order-of>true true true true false false false false false false</preceding-in-document-order-of><following-in-document-order-of>true true true true false false false false false false</following-in-document-order-of><level>1 1 2 3 3 3 4 4</level><sibling-of>true true true false false false false false</sibling-of><in-same-tree-of>true true false false false</in-same-tree-of><in-collection>true true true true false false false false</in-collection><in-same-collection>true true true true false false false false false</in-same-collection></result>
\ No newline at end of file

=== added file 'test/rbkt/ExpQueryResults/zorba/nodes/position_2_parsed.xml.res'
--- test/rbkt/ExpQueryResults/zorba/nodes/position_2_parsed.xml.res	1970-01-01 00:00:00 +0000
+++ test/rbkt/ExpQueryResults/zorba/nodes/position_2_parsed.xml.res	2011-10-27 20:59:25 +0000
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<result><child-of>true true false false false false false false</child-of><attribute-of>true false false false false false false false false</attribute-of><parent-of>true true false false false false false false</parent-of><preceding-in-document-order-of>true true true true false false false false false false</preceding-in-document-order-of><following-in-document-order-of>true true true true false false false false false false</following-in-document-order-of><level>1 1 2 3 3 3 4 4</level><sibling-of>true true true false false false false false</sibling-of><in-same-tree-of>true true false false false</in-same-tree-of><in-collection>true true true true false false false false</in-collection><in-same-collection>true true true true false false false false false</in-same-collection></result>
\ No newline at end of file

=== added file 'test/rbkt/ExpQueryResults/zorba/nodes/position_3.xml.res'
--- test/rbkt/ExpQueryResults/zorba/nodes/position_3.xml.res	1970-01-01 00:00:00 +0000
+++ test/rbkt/ExpQueryResults/zorba/nodes/position_3.xml.res	2011-10-27 20:59:25 +0000
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<result><attr>true false false false false false</attr><comm>false true false false false false</comm><docu>false false true false false false</docu><elem>false false false true false false</elem><proc>false false false false true false</proc><text>false false false false false true</text></result>
\ No newline at end of file

=== added file 'test/rbkt/ExpQueryResults/zorba/nodes/position_3_parsed.xml.res'
--- test/rbkt/ExpQueryResults/zorba/nodes/position_3_parsed.xml.res	1970-01-01 00:00:00 +0000
+++ test/rbkt/ExpQueryResults/zorba/nodes/position_3_parsed.xml.res	2011-10-27 20:59:25 +0000
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<result><attr>true false false false false false</attr><comm>false true false false false false</comm><docu>false false true false false false</docu><elem>false false false true false false</elem><proc>false false false false true false</proc><text>false false false false false true</text></result>
\ No newline at end of file

=== added file 'test/rbkt/ExpQueryResults/zorba/nodes/position_4.xml.res'
--- test/rbkt/ExpQueryResults/zorba/nodes/position_4.xml.res	1970-01-01 00:00:00 +0000
+++ test/rbkt/ExpQueryResults/zorba/nodes/position_4.xml.res	2011-10-27 20:59:25 +0000
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<result><test1>OK: np:40</test1><test2>OK: np:68</test2><test3>OK: np:72</test3><test4>OK: np:72</test4><test5>OK: np:76</test5><test6>OK: np:68</test6><test7>OK: np:72</test7><test8>OK: np:72</test8><test9>OK: np:76</test9><test10>OK: np:62</test10><test11>OK: np:7080</test11><test12>OK: np:7080</test12><test13>OK: np:7480</test13></result>
\ No newline at end of file

=== added file 'test/rbkt/ExpQueryResults/zorba/nodes/position_4_parsed.xml.res'
--- test/rbkt/ExpQueryResults/zorba/nodes/position_4_parsed.xml.res	1970-01-01 00:00:00 +0000
+++ test/rbkt/ExpQueryResults/zorba/nodes/position_4_parsed.xml.res	2011-10-27 20:59:25 +0000
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<result><test1>OK: np:40</test1><test2>OK: np:68</test2><test3>OK: np:72</test3><test4>OK: np:72</test4><test5>OK: np:76</test5><test6>OK: np:68</test6><test7>OK: np:72</test7><test8>OK: np:72</test8><test9>OK: np:76</test9><test10>OK: np:62</test10><test11>OK: np:7080</test11><test12>OK: np:7080</test12><test13>OK: np:7480</test13></result>
\ No newline at end of file

=== added file 'test/rbkt/ExpQueryResults/zorba/nodes/position_err.xml.res'
--- test/rbkt/ExpQueryResults/zorba/nodes/position_err.xml.res	1970-01-01 00:00:00 +0000
+++ test/rbkt/ExpQueryResults/zorba/nodes/position_err.xml.res	2011-10-27 20:59:25 +0000
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<err><err-code>zerr:ZAPI0028</err-code><err-description>"not a uri": invalid node URI</err-description><err-value/><err-line>9</err-line></err>
+
+<err><err-code>zerr:ZAPI0028</err-code><err-description>"zorba:0.3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333.1.50": invalid node URI</err-description><err-value/><err-line>27</err-line></err>
+
+<err><err-code>zerr:ZAPI0028</err-code><err-description>"zorba:0..1.50": invalid node URI</err-description><err-value/><err-line>45</err-line></err>

=== modified file 'test/rbkt/Queries/CMakeLists.txt'
--- test/rbkt/Queries/CMakeLists.txt	2011-10-10 10:31:20 +0000
+++ test/rbkt/Queries/CMakeLists.txt	2011-10-27 20:59:25 +0000
@@ -1,11 +1,11 @@
 # Copyright 2006-2008 The FLWOR Foundation.
-# 
+#
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
 # You may obtain a copy of the License at
-# 
+#
 # http://www.apache.org/licenses/LICENSE-2.0
-# 
+#
 # Unless required by applicable law or agreed to in writing, software
 # distributed under the License is distributed on an "AS IS" BASIS,
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -18,10 +18,10 @@
 
 MESSAGE(STATUS "Adding tests for CTest")
 
-FILE(GLOB_RECURSE TESTFILES FOLLOW_SYMLINKS 
+FILE(GLOB_RECURSE TESTFILES FOLLOW_SYMLINKS
   RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "*.xq")
 IF(ZORBA_TEST_XQUERYX)
-  FILE(GLOB_RECURSE TESTFILES_XQX FOLLOW_SYMLINKS 
+  FILE(GLOB_RECURSE TESTFILES_XQX FOLLOW_SYMLINKS
     RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} FOLLOW_SYMLINKS "*.xqx")
   IF (TESTFILES_XQX)
     LIST(APPEND TESTFILES ${TESTFILES_XQX})
@@ -94,7 +94,7 @@
     LIST(SORT CHAINED_TESTS_FILES)
 
     SET(TEST_NAME "test/rbkt/${TEST_NAME}")
-    
+
     # finally add the test
     ZORBA_ADD_TEST("${TEST_NAME}" testdriver ${CHAINED_TESTS_FILES})
 
@@ -143,7 +143,7 @@
       SET(SKIP_TEST 1)
     ENDIF(HTTP_CLIENT)
   ENDIF(NOT CURL_FOUND)
-  
+
   IF(NOT ZORBA_WITH_FILE_ACCESS)
     #these tests require the file module
     STRING(REGEX MATCH "file/" NEEDS_FILE "${TESTNAME}")
@@ -211,6 +211,7 @@
 IF (FOUND_XQTS AND NOT ZORBA_TEST_W3C_TO_SUBMIT_RESULTS)
 
   EXPECTED_FAILURE(test/rbkt/w3c_testsuite/XQuery/PathExpr/Steps/Steps-leading-lone-slash-8a 3408285)
+  EXPECTED_FAILURE(test/rbkt/w3c_testsuite/XQuery/Functions/QNameFunc/NamespaceURIForPrefixFunc/K2-NamespaceURIForPrefixFunc-2 872732)
 
   IF(NOT ZORBA_WITH_BIG_INTEGER)
     # These tests fail due to integer overflow.

=== modified file 'test/rbkt/Queries/w3c_known_failures.txt'
--- test/rbkt/Queries/w3c_known_failures.txt	2011-09-12 23:22:24 +0000
+++ test/rbkt/Queries/w3c_known_failures.txt	2011-10-27 20:59:25 +0000
@@ -107,6 +107,7 @@
 test/rbkt/w3c_testsuite/XQuery/Functions/HigherOrder/MapPairs/map-pairs-001
 test/rbkt/w3c_testsuite/XQuery/Functions/HigherOrder/MapPairs/map-pairs-008
 test/rbkt/w3c_testsuite/XQuery/Functions/HigherOrder/MapPairs/map-pairs-902
+test/rbkt/w3c_testsuite/XQuery/Functions/QNameFunc/NamespaceURIForPrefixFunc/K2-NamespaceURIForPrefixFunc-2
 test/rbkt/w3c_testsuite/XQuery/SchemaValidation/ValidateExpression/validateexpr-28
 test/rbkt/w3c_testsuite/XQuery/exprSeqTypes/PrologExpr/VariableProlog/ExternalVariablesWith/K2-ExternalVariablesWith-22
 test/rbkt/w3c_testsuite/XQuery/StaticTyping/STFLWORExpr/ST-PITest-02

=== added file 'test/rbkt/Queries/zorba/nodes/position.xml'
--- test/rbkt/Queries/zorba/nodes/position.xml	1970-01-01 00:00:00 +0000
+++ test/rbkt/Queries/zorba/nodes/position.xml	2011-10-27 20:59:25 +0000
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<a><b/><b/><b/><b attr="" attr2=""><c attr=""/><c/><c/><c/></b></a>
+<!-- 
+<a>
+    <b/>
+    <b/>
+    <b/>
+    <b attr="" attr2="">
+        <c attr=""/>
+        <c/>
+        <c/>
+        <c/>
+    </b>
+</a>
+ -->
\ No newline at end of file

=== added file 'test/rbkt/Queries/zorba/nodes/position_1.xq'
--- test/rbkt/Queries/zorba/nodes/position_1.xq	1970-01-01 00:00:00 +0000
+++ test/rbkt/Queries/zorba/nodes/position_1.xq	2011-10-27 20:59:25 +0000
@@ -0,0 +1,97 @@
+import module namespace np = "http://www.zorba-xquery.com/modules/node-position";;
+
+import module namespace ddl = "http://www.zorba-xquery.com/modules/store/dynamic/collections/ddl";;
+import module namespace dml = "http://www.zorba-xquery.com/modules/store/dynamic/collections/dml";;
+
+ddl:create(xs:QName("ddl:coll"),doc("position.xml")/a);
+variable $xx:=dml:collection(xs:QName("ddl:coll"));
+
+ddl:create(xs:QName("ddl:coll2"),doc("position.xml")/a);
+variable $yy:=dml:collection(xs:QName("ddl:coll2"));
+
+variable $x :=  doc("position.xml")/a;
+insert node <newb><c/></newb> before $x/b[4];
+insert node <newb><c/></newb> after $x/b[4];
+variable $y :=  element {"x"}{$x}/*;
+
+<result>
+  <ancestor-of>
+  {
+    np:ancestor-of(np:node-position($x/b[1]), np:node-position($x)),
+    np:ancestor-of(np:node-position($x/b[4]/c[1]), np:node-position($x)),
+    np:ancestor-of(np:node-position($x), np:node-position($x/b[1])),
+    np:ancestor-of(np:node-position($x), np:node-position($x/b[4]/c[1])),
+    np:ancestor-of(np:node-position($x), np:node-position($x)),
+    np:ancestor-of(np:node-position($x/b[1]), np:node-position($y)),
+    np:ancestor-of(np:node-position($xx/b[1]), np:node-position($yy))
+  }
+  </ancestor-of>
+  <following-sibling-of>
+  {   
+    np:following-sibling-of(np:node-position($x/b[1]), np:node-position($x/b[2])),
+    np:following-sibling-of(np:node-position($x/b[1]), np:node-position($x/newb[1])),
+    np:following-sibling-of(np:node-position($x/b[2]), np:node-position($x/b[1])),
+    np:following-sibling-of(np:node-position($x), np:node-position($x)),
+    np:following-sibling-of(np:node-position($x/b/@attr), np:node-position($x/b/@attr2)),
+    np:following-sibling-of(np:node-position($x/b/@attr2), np:node-position($x/b/@attr)),
+    np:following-sibling-of(np:node-position($x/b[1]), np:node-position($y/b[2])),
+    np:following-sibling-of(np:node-position($xx/b[1]), np:node-position($yy/b[2]))
+  }
+  </following-sibling-of>
+  <following-of>
+  { 
+    np:following-of(np:node-position($x/b[1]), np:node-position($x/b[4]/c[1])),
+    np:following-of(np:node-position($x/b[4]), np:node-position($x/b[4]/c[1])),
+    np:following-of(np:node-position($x/b[4]/c[1]), np:node-position($x/b[1])),
+    np:following-of(np:node-position($x), np:node-position($x)),
+    np:following-of(np:node-position($x/b[1]), np:node-position($y/b[4]/c[1])),
+    np:following-of(np:node-position($xx/b[1]), np:node-position($yy/b[4]/c[1]))
+  }
+  </following-of>
+  <descendant-of>
+  {        
+    np:descendant-of(np:node-position($x), np:node-position($x/b[1])),
+    np:descendant-of(np:node-position($x), np:node-position($x/b[4]/c[1])),
+    np:descendant-of(np:node-position($x), np:node-position($x/b/@attr)),
+    np:descendant-of(np:node-position($x/b[1]), np:node-position($x)),
+    np:descendant-of(np:node-position($x/b[4]/c[1]), np:node-position($x)),    
+    np:descendant-of(np:node-position($x), np:node-position($x)),
+    np:descendant-of(np:node-position($x), np:node-position($y/b[1])),
+    np:descendant-of(np:node-position($xx), np:node-position($yy/b[1]))
+  }
+  </descendant-of>
+  <in-subtree-of>
+  {        
+    np:in-subtree-of(np:node-position($x), np:node-position($x/b[1])),
+    np:in-subtree-of(np:node-position($x), np:node-position($x/b[4]/c[1])),
+    np:in-subtree-of(np:node-position($x), np:node-position($x/b/@attr)),
+    np:in-subtree-of(np:node-position($x/b[1]), np:node-position($x)),
+    np:in-subtree-of(np:node-position($x/b[4]/c[1]), np:node-position($x)),    
+    np:in-subtree-of(np:node-position($x), np:node-position($x)),
+    np:in-subtree-of(np:node-position($x), np:node-position($y/b[1])),
+    np:in-subtree-of(np:node-position($xx), np:node-position($yy/b[1]))
+  }
+  </in-subtree-of>
+  <preceding-sibling-of>
+  { 
+    np:preceding-sibling-of(np:node-position($x/b[2]), np:node-position($x/b[1])),
+    np:preceding-sibling-of(np:node-position($x/b[4]), np:node-position($x/newb[1])),
+    np:preceding-sibling-of(np:node-position($x/b[1]), np:node-position($x/b[2])),
+    np:preceding-sibling-of(np:node-position($x), np:node-position($x)),
+    np:preceding-sibling-of(np:node-position($x/b/@attr), np:node-position($x/b/@attr2)),
+    np:preceding-sibling-of(np:node-position($x/b/@attr2), np:node-position($x/b/@attr)),
+    np:preceding-sibling-of(np:node-position($x/b[2]), np:node-position($y/b[1])),
+    np:preceding-sibling-of(np:node-position($xx/b[2]), np:node-position($yy/b[1]))
+  }
+  </preceding-sibling-of>
+  <preceding-of>
+  {
+    np:preceding-of(np:node-position($x/b[4]/c[1]), np:node-position($x/b[1])),
+    np:preceding-of(np:node-position($x/b[1]), np:node-position($x/b[4]/c[1])),
+    np:preceding-of(np:node-position($x/b[4]), np:node-position($x/b[4]/c[1])),    
+    np:preceding-of(np:node-position($x), np:node-position($x)),
+    np:preceding-of(np:node-position($x/b[4]/c[1]), np:node-position($y/b[1])),
+    np:preceding-of(np:node-position($xx/b[4]/c[1]), np:node-position($yy/b[1]))
+  }
+  </preceding-of>
+</result>   

=== added file 'test/rbkt/Queries/zorba/nodes/position_1_parsed.xq'
--- test/rbkt/Queries/zorba/nodes/position_1_parsed.xq	1970-01-01 00:00:00 +0000
+++ test/rbkt/Queries/zorba/nodes/position_1_parsed.xq	2011-10-27 20:59:25 +0000
@@ -0,0 +1,98 @@
+import module namespace np = "http://www.zorba-xquery.com/modules/node-position";;
+
+import module namespace ddl = "http://www.zorba-xquery.com/modules/store/dynamic/collections/ddl";;
+import module namespace dml = "http://www.zorba-xquery.com/modules/store/dynamic/collections/dml";;
+
+ddl:create(xs:QName("ddl:coll"),doc("position.xml")/a);
+variable $xx:=dml:collection(xs:QName("ddl:coll"));
+
+ddl:create(xs:QName("ddl:coll2"),doc("position.xml")/a);
+variable $yy:=dml:collection(xs:QName("ddl:coll2"));
+
+
+variable $x :=  doc("position.xml")/a;
+insert node <newb><c/></newb> before $x/b[4];
+insert node <newb><c/></newb> after $x/b[4];
+variable $y :=  element {"x"}{$x}/*;
+
+<result>
+  <ancestor-of>
+  {
+    np:ancestor-of(xs:anyURI(string(np:node-position($x/b[1]))), xs:anyURI(string(np:node-position($x)))),
+    np:ancestor-of(xs:anyURI(string(np:node-position($x/b[4]/c[1]))), xs:anyURI(string(np:node-position($x)))),
+    np:ancestor-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x/b[1])))),
+    np:ancestor-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x/b[4]/c[1])))),
+    np:ancestor-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x)))),
+    np:ancestor-of(xs:anyURI(string(np:node-position($x/b[1]))), xs:anyURI(string(np:node-position($y)))),
+    np:ancestor-of(xs:anyURI(string(np:node-position($xx/b[1]))), xs:anyURI(string(np:node-position($yy))))
+  }
+  </ancestor-of>
+  <following-sibling-of>
+  {   
+    np:following-sibling-of(xs:anyURI(string(np:node-position($x/b[1]))), xs:anyURI(string(np:node-position($x/b[2])))),
+    np:following-sibling-of(xs:anyURI(string(np:node-position($x/b[1]))), xs:anyURI(string(np:node-position($x/newb[1])))),
+    np:following-sibling-of(xs:anyURI(string(np:node-position($x/b[2]))), xs:anyURI(string(np:node-position($x/b[1])))),
+    np:following-sibling-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x)))),
+    np:following-sibling-of(xs:anyURI(string(np:node-position($x/b/@attr))), xs:anyURI(string(np:node-position($x/b/@attr2)))),
+    np:following-sibling-of(xs:anyURI(string(np:node-position($x/b/@attr2))), xs:anyURI(string(np:node-position($x/b/@attr)))),
+    np:following-sibling-of(xs:anyURI(string(np:node-position($x/b[1]))), xs:anyURI(string(np:node-position($y/b[2])))),
+    np:following-sibling-of(xs:anyURI(string(np:node-position($xx/b[1]))), xs:anyURI(string(np:node-position($yy/b[2]))))
+  }
+  </following-sibling-of>
+  <following-of>
+  { 
+    np:following-of(xs:anyURI(string(np:node-position($x/b[1]))), xs:anyURI(string(np:node-position($x/b[4]/c[1])))),
+    np:following-of(xs:anyURI(string(np:node-position($x/b[4]))), xs:anyURI(string(np:node-position($x/b[4]/c[1])))),
+    np:following-of(xs:anyURI(string(np:node-position($x/b[4]/c[1]))), xs:anyURI(string(np:node-position($x/b[1])))),
+    np:following-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x)))),
+    np:following-of(xs:anyURI(string(np:node-position($x/b[1]))), xs:anyURI(string(np:node-position($y/b[4]/c[1])))),
+    np:following-of(xs:anyURI(string(np:node-position($xx/b[1]))), xs:anyURI(string(np:node-position($yy/b[4]/c[1]))))
+  }
+  </following-of>
+  <descendant-of>
+  {        
+    np:descendant-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x/b[1])))),
+    np:descendant-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x/b[4]/c[1])))),
+    np:descendant-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x/b/@attr)))),
+    np:descendant-of(xs:anyURI(string(np:node-position($x/b[1]))), xs:anyURI(string(np:node-position($x)))),
+    np:descendant-of(xs:anyURI(string(np:node-position($x/b[4]/c[1]))), xs:anyURI(string(np:node-position($x)))),    
+    np:descendant-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x)))),
+    np:descendant-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($y/b[1])))),
+    np:descendant-of(xs:anyURI(string(np:node-position($xx))), xs:anyURI(string(np:node-position($yy/b[1]))))
+  }
+  </descendant-of>
+  <in-subtree-of>
+  {        
+    np:in-subtree-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x/b[1])))),
+    np:in-subtree-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x/b[4]/c[1])))),
+    np:in-subtree-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x/b/@attr)))),
+    np:in-subtree-of(xs:anyURI(string(np:node-position($x/b[1]))), xs:anyURI(string(np:node-position($x)))),
+    np:in-subtree-of(xs:anyURI(string(np:node-position($x/b[4]/c[1]))), xs:anyURI(string(np:node-position($x)))),    
+    np:in-subtree-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x)))),
+    np:in-subtree-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($y/b[1])))),
+    np:in-subtree-of(xs:anyURI(string(np:node-position($xx))), xs:anyURI(string(np:node-position($yy/b[1]))))
+  }
+  </in-subtree-of>
+  <preceding-sibling-of>
+  { 
+    np:preceding-sibling-of(xs:anyURI(string(np:node-position($x/b[2]))), xs:anyURI(string(np:node-position($x/b[1])))),
+    np:preceding-sibling-of(xs:anyURI(string(np:node-position($x/b[4]))), xs:anyURI(string(np:node-position($x/newb[1])))),
+    np:preceding-sibling-of(xs:anyURI(string(np:node-position($x/b[1]))), xs:anyURI(string(np:node-position($x/b[2])))),
+    np:preceding-sibling-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x)))),
+    np:preceding-sibling-of(xs:anyURI(string(np:node-position($x/b/@attr))), xs:anyURI(string(np:node-position($x/b/@attr2)))),
+    np:preceding-sibling-of(xs:anyURI(string(np:node-position($x/b/@attr2))), xs:anyURI(string(np:node-position($x/b/@attr)))),
+    np:preceding-sibling-of(xs:anyURI(string(np:node-position($x/b[2]))), xs:anyURI(string(np:node-position($y/b[1])))),
+    np:preceding-sibling-of(xs:anyURI(string(np:node-position($xx/b[2]))), xs:anyURI(string(np:node-position($yy/b[1]))))
+  }
+  </preceding-sibling-of>
+  <preceding-of>
+  {
+    np:preceding-of(xs:anyURI(string(np:node-position($x/b[4]/c[1]))), xs:anyURI(string(np:node-position($x/b[1])))),
+    np:preceding-of(xs:anyURI(string(np:node-position($x/b[1]))), xs:anyURI(string(np:node-position($x/b[4]/c[1])))),
+    np:preceding-of(xs:anyURI(string(np:node-position($x/b[4]))), xs:anyURI(string(np:node-position($x/b[4]/c[1])))),    
+    np:preceding-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x)))),
+    np:preceding-of(xs:anyURI(string(np:node-position($x/b[4]/c[1]))), xs:anyURI(string(np:node-position($y/b[1])))),
+    np:preceding-of(xs:anyURI(string(np:node-position($xx/b[4]/c[1]))), xs:anyURI(string(np:node-position($yy/b[1]))))
+  }
+  </preceding-of>
+</result>
\ No newline at end of file

=== added file 'test/rbkt/Queries/zorba/nodes/position_2.xq'
--- test/rbkt/Queries/zorba/nodes/position_2.xq	1970-01-01 00:00:00 +0000
+++ test/rbkt/Queries/zorba/nodes/position_2.xq	2011-10-27 20:59:25 +0000
@@ -0,0 +1,157 @@
+import module namespace np = "http://www.zorba-xquery.com/modules/node-position";;
+import module namespace ddl = "http://www.zorba-xquery.com/modules/store/dynamic/collections/ddl";;
+import module namespace dml = "http://www.zorba-xquery.com/modules/store/dynamic/collections/dml";;
+
+ddl:create(xs:QName("ddl:coll"),<dummy/>);
+variable $xx:=dml:collection(xs:QName("ddl:coll"));
+
+ddl:create(xs:QName("ddl:coll2"),<dummy/>);
+variable $yy:=dml:collection(xs:QName("ddl:coll2"));
+
+ddl:create(xs:QName("ddl:coll3"),doc("position.xml")/a);
+variable $xxx:=dml:collection(xs:QName("ddl:coll3"));
+
+ddl:create(xs:QName("ddl:coll4"),doc("position.xml")/a);
+variable $yyy:=dml:collection(xs:QName("ddl:coll4"));
+
+insert node <b/> into $xx;
+insert node <bb/> into $xx/b;
+insert node <b2/> into $xx;
+insert node <bb2/> into $xx/b2;
+
+insert node <b/> into $yy;
+insert node <bb/> into $yy/b;
+insert node <b2/> into $yy;
+insert node <bb2/> into $yy/b2;
+
+variable $x :=  doc("position.xml")/a;
+insert node <newb><c/></newb> before $x/b[4];
+insert node <newb><c/></newb> after $x/b[4];
+variable $y :=  element {"x"}{$x}/*;
+
+<result>
+  <child-of>
+  {
+    np:child-of(np:node-position($x), np:node-position($x/b[1])),
+    np:child-of(np:node-position($x), np:node-position($x/newb[1])),
+    np:child-of(np:node-position($x), np:node-position($x/b[4]/c[1])),
+    np:child-of(np:node-position($x/b[1]), np:node-position($x)),
+    np:child-of(np:node-position($x/b[4]/c[1]), np:node-position($x)),    
+    np:child-of(np:node-position($x), np:node-position($x)),
+    np:child-of(np:node-position($x/b[1]), np:node-position($y)),
+    np:child-of(np:node-position($xxx), np:node-position($yyy/b[1]))
+  }
+  </child-of>
+  <attribute-of>
+  {
+    np:attribute-of(np:node-position($x/b[4]), np:node-position($x/b[4]/@attr)),
+    np:attribute-of(np:node-position($x/b[4]), np:node-position($x/b[4]/c/@attr)),
+    np:attribute-of(np:node-position($x/b[4]/@attr), np:node-position($x/b[4])),
+    np:attribute-of(np:node-position($x/b[4]/c/@attr), np:node-position($x/b[4])),    
+    np:attribute-of(np:node-position($x), np:node-position($x/b[1])),
+    np:attribute-of(np:node-position($x), np:node-position($x/newb[1])),    
+    np:attribute-of(np:node-position($x/b[4]/@attr), np:node-position($x/b[4]/@attr)),
+    np:attribute-of(np:node-position($x/b[4]), np:node-position($y/b[4]/@attr)),
+    np:attribute-of(np:node-position($xxx/b[4]), np:node-position($yyy/b[4]/@attr))
+  }
+  </attribute-of>
+  <parent-of>
+  { 
+    np:parent-of(np:node-position($x/b[1]), np:node-position($x)),
+    np:parent-of(np:node-position($x/newb[1]), np:node-position($x)),
+    np:parent-of(np:node-position($x/b[4]/c[1]), np:node-position($x)),
+    np:parent-of(np:node-position($x), np:node-position($x/b[1])),
+    np:parent-of(np:node-position($x), np:node-position($x/b[4]/c[1])),        
+    np:parent-of(np:node-position($x), np:node-position($x)),
+    np:parent-of(np:node-position($x/b[1]), np:node-position($y)),
+    np:parent-of(np:node-position($xxx/b[1]), np:node-position($yyy))
+  }
+  </parent-of>
+  <preceding-in-document-order-of>
+  {
+    np:preceding-in-document-order-of(np:node-position($x/b[4]/@attr), np:node-position($x/b[1])),
+    np:preceding-in-document-order-of(np:node-position($x/b[4]/c[1]), np:node-position($x/b[1])),
+    np:preceding-in-document-order-of(np:node-position($x/b[4]/c[1]), np:node-position($x/b[4])),
+    np:preceding-in-document-order-of(np:node-position($y), np:node-position($x)),
+    np:preceding-in-document-order-of(np:node-position($x), np:node-position($y)),
+    np:preceding-in-document-order-of(np:node-position($x), np:node-position($x)),
+    np:preceding-in-document-order-of(np:node-position($x/b[1]), np:node-position($x/b[4]/@attr)),
+    np:preceding-in-document-order-of(np:node-position($x/b[1]), np:node-position($x/b[4]/c[1])),
+    np:preceding-in-document-order-of(np:node-position($x/b[4]), np:node-position($x/b[4]/c[1])),
+    np:preceding-in-document-order-of(np:node-position($xxx/b[4]/@attr), np:node-position($yyy/b[1]))
+  }
+  </preceding-in-document-order-of>
+  <following-in-document-order-of>
+  { 
+    np:following-in-document-order-of(np:node-position($x/b[1]), np:node-position($x/b[4]/@attr)),   
+    np:following-in-document-order-of(np:node-position($x/b[1]), np:node-position($x/b[4]/c[1])),
+    np:following-in-document-order-of(np:node-position($x/b[4]), np:node-position($x/b[4]/c[1])),
+    np:following-in-document-order-of(np:node-position($x), np:node-position($y)),
+    np:following-in-document-order-of(np:node-position($y), np:node-position($x)),
+    np:following-in-document-order-of(np:node-position($x), np:node-position($x)),
+    np:following-in-document-order-of(np:node-position($x/b[4]/@attr), np:node-position($x/b[1])),
+    np:following-in-document-order-of(np:node-position($x/b[4]/c[1]), np:node-position($x/b[1])),
+    np:following-in-document-order-of(np:node-position($x/b[4]/c[1]), np:node-position($x/b[4])),
+    np:following-in-document-order-of(np:node-position($yyy/b[1]), np:node-position($xxx/b[4]/@attr))
+  }
+  </following-in-document-order-of>
+  <level>
+  {
+    np:level(np:node-position(document {"x"})),
+    np:level(np:node-position(element {"x"}{"x"})),    
+    np:level(np:node-position($x)),
+    np:level(np:node-position($x/b[1])),
+    np:level(np:node-position($x/newb[1])),
+    np:level(np:node-position($x/newb[2])),
+    np:level(np:node-position($x/b/@attr)),
+    np:level(np:node-position($x/b/c[1]))
+  }
+  </level>
+  <sibling-of>
+  {
+    np:sibling-of(np:node-position($x/b[1]), np:node-position($x/b[2])),
+    np:sibling-of(np:node-position($x/b[1]), np:node-position($x/newb[1])),
+    np:sibling-of(np:node-position($x/b[2]), np:node-position($x/b[1])),
+    np:sibling-of(np:node-position($x), np:node-position($x)),
+    np:sibling-of(np:node-position($x/b/@attr), np:node-position($x/b/@attr2)),
+    np:sibling-of(np:node-position($x/b/@attr2), np:node-position($x/b/@attr)),
+    np:sibling-of(np:node-position($x/b[1]), np:node-position($y/b[2])),
+    np:sibling-of(np:node-position($xxx/b[1]), np:node-position($yyy/b[2]))
+  }  
+  </sibling-of>
+  <in-same-tree-of>
+  {
+    np:in-same-tree-of(np:node-position($x/b[1]), np:node-position($x/b[2])),
+    np:in-same-tree-of(np:node-position($y/b[1]), np:node-position($y/b[2])),
+    np:in-same-tree-of(np:node-position($x/b[1]), np:node-position($y/b[2])),
+    np:in-same-tree-of(np:node-position($y/b[2]), np:node-position($x/b[1])),
+    np:in-same-tree-of(np:node-position($xxx/b[1]), np:node-position($yyy/b[2]))    
+  }
+  </in-same-tree-of>
+  <in-collection>
+  {
+    np:in-collection(np:node-position($xx/b)),
+    np:in-collection(np:node-position($xx/b2)),
+    np:in-collection(np:node-position($xx/b/bb)),
+    np:in-collection(np:node-position($xx/b2/bb2)),
+    np:in-collection(np:node-position($x)),
+    np:in-collection(np:node-position($x/b[1])),
+    np:in-collection(np:node-position($x/b/@attr)),
+    np:in-collection(np:node-position($x/b/c[1]))
+  }
+  </in-collection>
+  <in-same-collection>
+  {
+    np:in-same-collection-of(np:node-position($xx/b),np:node-position($xx/b)),
+    np:in-same-collection-of(np:node-position($xx/b2),np:node-position($xx/b2)),
+    np:in-same-collection-of(np:node-position($xx/b/bb),np:node-position($xx/b/bb)),
+    np:in-same-collection-of(np:node-position($xx/b2/bb2),np:node-position($xx/b2/bb2)),
+    np:in-same-collection-of(np:node-position($xx/b),np:node-position($yy/b)),
+    np:in-same-collection-of(np:node-position($xx/b2),np:node-position($yy/b2)),
+    np:in-same-collection-of(np:node-position($xx/b/bb),np:node-position($yy/b/bb)),
+    np:in-same-collection-of(np:node-position($xx/b2/bb2),np:node-position($yy/b2/bb2)),    
+    np:in-same-collection-of(np:node-position($x),np:node-position($x))    
+  }
+  </in-same-collection>
+</result>    
+ 
\ No newline at end of file

=== added file 'test/rbkt/Queries/zorba/nodes/position_2_parsed.xq'
--- test/rbkt/Queries/zorba/nodes/position_2_parsed.xq	1970-01-01 00:00:00 +0000
+++ test/rbkt/Queries/zorba/nodes/position_2_parsed.xq	2011-10-27 20:59:25 +0000
@@ -0,0 +1,156 @@
+import module namespace np = "http://www.zorba-xquery.com/modules/node-position";;
+import module namespace ddl = "http://www.zorba-xquery.com/modules/store/dynamic/collections/ddl";;
+import module namespace dml = "http://www.zorba-xquery.com/modules/store/dynamic/collections/dml";;
+
+ddl:create(xs:QName("ddl:coll"),<dummy/>);
+variable $xx:=dml:collection(xs:QName("ddl:coll"));
+
+ddl:create(xs:QName("ddl:coll2"),<dummy/>);
+variable $yy:=dml:collection(xs:QName("ddl:coll2"));
+
+ddl:create(xs:QName("ddl:coll3"),doc("position.xml")/a);
+variable $xxx:=dml:collection(xs:QName("ddl:coll3"));
+
+ddl:create(xs:QName("ddl:coll4"),doc("position.xml")/a);
+variable $yyy:=dml:collection(xs:QName("ddl:coll4"));
+
+insert node <b/> into $xx;
+insert node <bb/> into $xx/b;
+insert node <b2/> into $xx;
+insert node <bb2/> into $xx/b2;
+
+insert node <b/> into $yy;
+insert node <bb/> into $yy/b;
+insert node <b2/> into $yy;
+insert node <bb2/> into $yy/b2;
+
+variable $x :=  doc("position.xml")/a;
+insert node <newb><c/></newb> before $x/b[4];
+insert node <newb><c/></newb> after $x/b[4];
+variable $y :=  element {"x"}{$x}/*;
+
+<result>
+  <child-of>
+  {
+    np:child-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x/b[1])))),
+    np:child-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x/newb[1])))),
+    np:child-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x/b[4]/c[1])))),
+    np:child-of(xs:anyURI(string(np:node-position($x/b[1]))), xs:anyURI(string(np:node-position($x)))),
+    np:child-of(xs:anyURI(string(np:node-position($x/b[4]/c[1]))), xs:anyURI(string(np:node-position($x)))),    
+    np:child-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x)))),
+    np:child-of(xs:anyURI(string(np:node-position($x/b[1]))), xs:anyURI(string(np:node-position($y)))),
+    np:child-of(xs:anyURI(string(np:node-position($xxx))), xs:anyURI(string(np:node-position($yyy/b[1]))))
+  }
+  </child-of>
+  <attribute-of>
+  {
+    np:attribute-of(xs:anyURI(string(np:node-position($x/b[4]))), xs:anyURI(string(np:node-position($x/b[4]/@attr)))),
+    np:attribute-of(xs:anyURI(string(np:node-position($x/b[4]))), xs:anyURI(string(np:node-position($x/b[4]/c/@attr)))),
+    np:attribute-of(xs:anyURI(string(np:node-position($x/b[4]/@attr))), xs:anyURI(string(np:node-position($x/b[4])))),
+    np:attribute-of(xs:anyURI(string(np:node-position($x/b[4]/c/@attr))), xs:anyURI(string(np:node-position($x/b[4])))),    
+    np:attribute-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x/b[1])))),
+    np:attribute-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x/newb[1])))),    
+    np:attribute-of(xs:anyURI(string(np:node-position($x/b[4]/@attr))), xs:anyURI(string(np:node-position($x/b[4]/@attr)))),
+    np:attribute-of(xs:anyURI(string(np:node-position($x/b[4]))), xs:anyURI(string(np:node-position($y/b[4]/@attr)))),
+    np:attribute-of(xs:anyURI(string(np:node-position($xxx/b[4]))), xs:anyURI(string(np:node-position($yyy/b[4]/@attr))))    
+  }
+  </attribute-of>
+  <parent-of>
+  { 
+    np:parent-of(xs:anyURI(string(np:node-position($x/b[1]))), xs:anyURI(string(np:node-position($x)))),
+    np:parent-of(xs:anyURI(string(np:node-position($x/newb[1]))), xs:anyURI(string(np:node-position($x)))),
+    np:parent-of(xs:anyURI(string(np:node-position($x/b[4]/c[1]))), xs:anyURI(string(np:node-position($x)))),
+    np:parent-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x/b[1])))),
+    np:parent-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x/b[4]/c[1])))),        
+    np:parent-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x)))),
+    np:parent-of(xs:anyURI(string(np:node-position($x/b[1]))), xs:anyURI(string(np:node-position($y)))),
+    np:parent-of(xs:anyURI(string(np:node-position($xxx/b[1]))), xs:anyURI(string(np:node-position($yyy))))
+  }
+  </parent-of>
+  <preceding-in-document-order-of>
+  {
+    np:preceding-in-document-order-of(xs:anyURI(string(np:node-position($x/b[4]/@attr))), xs:anyURI(string(np:node-position($x/b[1])))),
+    np:preceding-in-document-order-of(xs:anyURI(string(np:node-position($x/b[4]/c[1]))), xs:anyURI(string(np:node-position($x/b[1])))),
+    np:preceding-in-document-order-of(xs:anyURI(string(np:node-position($x/b[4]/c[1]))), xs:anyURI(string(np:node-position($x/b[4])))),
+    np:preceding-in-document-order-of(xs:anyURI(string(np:node-position($y))), xs:anyURI(string(np:node-position($x)))),
+    np:preceding-in-document-order-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($y)))),
+    np:preceding-in-document-order-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x)))),
+    np:preceding-in-document-order-of(xs:anyURI(string(np:node-position($x/b[1]))), xs:anyURI(string(np:node-position($x/b[4]/@attr)))),
+    np:preceding-in-document-order-of(xs:anyURI(string(np:node-position($x/b[1]))), xs:anyURI(string(np:node-position($x/b[4]/c[1])))),
+    np:preceding-in-document-order-of(xs:anyURI(string(np:node-position($x/b[4]))), xs:anyURI(string(np:node-position($x/b[4]/c[1])))),
+    np:preceding-in-document-order-of(xs:anyURI(string(np:node-position($xxx/b[4]/@attr))), xs:anyURI(string(np:node-position($yyy/b[1]))))
+  }
+  </preceding-in-document-order-of>
+  <following-in-document-order-of>
+  {
+    np:following-in-document-order-of(xs:anyURI(string(np:node-position($x/b[1]))), xs:anyURI(string(np:node-position($x/b[4]/@attr)))),
+    np:following-in-document-order-of(xs:anyURI(string(np:node-position($x/b[1]))), xs:anyURI(string(np:node-position($x/b[4]/c[1])))),
+    np:following-in-document-order-of(xs:anyURI(string(np:node-position($x/b[4]))), xs:anyURI(string(np:node-position($x/b[4]/c[1])))),
+    np:following-in-document-order-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($y)))),
+    np:following-in-document-order-of(xs:anyURI(string(np:node-position($y))), xs:anyURI(string(np:node-position($x)))),
+    np:following-in-document-order-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x)))),
+    np:following-in-document-order-of(xs:anyURI(string(np:node-position($x/b[4]/@attr))), xs:anyURI(string(np:node-position($x/b[1])))),
+    np:following-in-document-order-of(xs:anyURI(string(np:node-position($x/b[4]/c[1]))), xs:anyURI(string(np:node-position($x/b[1])))),    
+    np:following-in-document-order-of(xs:anyURI(string(np:node-position($x/b[4]/c[1]))), xs:anyURI(string(np:node-position($x/b[4])))),
+    np:following-in-document-order-of(xs:anyURI(string(np:node-position($yyy/b[1]))), xs:anyURI(string(np:node-position($xxx/b[4]/@attr))))
+  }
+  </following-in-document-order-of>
+  <level>
+  {
+    np:level(xs:anyURI(string(np:node-position(document {"x"})))),
+    np:level(xs:anyURI(string(np:node-position(element {"x"}{"x"})))),
+    np:level(xs:anyURI(string(np:node-position($x)))),
+    np:level(xs:anyURI(string(np:node-position($x/b[1])))),
+    np:level(xs:anyURI(string(np:node-position($x/newb[1])))),
+    np:level(xs:anyURI(string(np:node-position($x/newb[2])))),
+    np:level(xs:anyURI(string(np:node-position($x/b/@attr)))),
+    np:level(xs:anyURI(string(np:node-position($x/b/c[1]))))
+  }
+  </level>
+  <sibling-of>
+  {
+    np:sibling-of(xs:anyURI(string(np:node-position($x/b[1]))), xs:anyURI(string(np:node-position($x/b[2])))),
+    np:sibling-of(xs:anyURI(string(np:node-position($x/b[1]))), xs:anyURI(string(np:node-position($x/newb[1])))),
+    np:sibling-of(xs:anyURI(string(np:node-position($x/b[2]))), xs:anyURI(string(np:node-position($x/b[1])))),
+    np:sibling-of(xs:anyURI(string(np:node-position($x))), xs:anyURI(string(np:node-position($x)))),
+    np:sibling-of(xs:anyURI(string(np:node-position($x/b/@attr))), xs:anyURI(string(np:node-position($x/b/@attr2)))),
+    np:sibling-of(xs:anyURI(string(np:node-position($x/b/@attr2))), xs:anyURI(string(np:node-position($x/b/@attr)))),
+    np:sibling-of(xs:anyURI(string(np:node-position($x/b[1]))), xs:anyURI(string(np:node-position($y/b[2])))),
+    np:sibling-of(xs:anyURI(string(np:node-position($xxx/b[1]))), xs:anyURI(string(np:node-position($yyy/b[2]))))
+  }  
+  </sibling-of>
+  <in-same-tree-of>
+  {
+    np:in-same-tree-of(xs:anyURI(string(np:node-position($x/b[1]))), xs:anyURI(string(np:node-position($x/b[2])))),
+    np:in-same-tree-of(xs:anyURI(string(np:node-position($y/b[1]))), xs:anyURI(string(np:node-position($y/b[2])))),
+    np:in-same-tree-of(xs:anyURI(string(np:node-position($x/b[1]))), xs:anyURI(string(np:node-position($y/b[2])))),
+    np:in-same-tree-of(xs:anyURI(string(np:node-position($y/b[2]))), xs:anyURI(string(np:node-position($x/b[1])))),
+    np:in-same-tree-of(xs:anyURI(string(np:node-position($xxx/b[1]))), xs:anyURI(string(np:node-position($yyy/b[2]))))    
+  }
+  </in-same-tree-of>
+  <in-collection>
+  {
+    np:in-collection(xs:anyURI(string(np:node-position($xx/b)))),
+    np:in-collection(xs:anyURI(string(np:node-position($xx/b2)))),
+    np:in-collection(xs:anyURI(string(np:node-position($xx/b/bb)))),
+    np:in-collection(xs:anyURI(string(np:node-position($xx/b2/bb2)))),
+    np:in-collection(xs:anyURI(string(np:node-position($x)))),
+    np:in-collection(xs:anyURI(string(np:node-position($x/b[1])))),
+    np:in-collection(xs:anyURI(string(np:node-position($x/b/@attr)))),
+    np:in-collection(xs:anyURI(string(np:node-position($x/b/c[1]))))
+  }
+  </in-collection>
+  <in-same-collection>
+  {
+    np:in-same-collection-of(xs:anyURI(string(np:node-position($xx/b))),xs:anyURI(string(np:node-position($xx/b)))),
+    np:in-same-collection-of(xs:anyURI(string(np:node-position($xx/b2))),xs:anyURI(string(np:node-position($xx/b2)))),
+    np:in-same-collection-of(xs:anyURI(string(np:node-position($xx/b/bb))),xs:anyURI(string(np:node-position($xx/b/bb)))),
+    np:in-same-collection-of(xs:anyURI(string(np:node-position($xx/b2/bb2))),xs:anyURI(string(np:node-position($xx/b2/bb2)))),
+    np:in-same-collection-of(xs:anyURI(string(np:node-position($xx/b))),xs:anyURI(string(np:node-position($yy/b)))),
+    np:in-same-collection-of(xs:anyURI(string(np:node-position($xx/b2))),xs:anyURI(string(np:node-position($yy/b2)))),
+    np:in-same-collection-of(xs:anyURI(string(np:node-position($xx/b/bb))),xs:anyURI(string(np:node-position($yy/b/bb)))),
+    np:in-same-collection-of(xs:anyURI(string(np:node-position($xx/b2/bb2))),xs:anyURI(string(np:node-position($yy/b2/bb2)))),    
+    np:in-same-collection-of(xs:anyURI(string(np:node-position($x))),xs:anyURI(string(np:node-position($x))))    
+  }
+  </in-same-collection>
+</result>
\ No newline at end of file

=== added file 'test/rbkt/Queries/zorba/nodes/position_3.xq'
--- test/rbkt/Queries/zorba/nodes/position_3.xq	1970-01-01 00:00:00 +0000
+++ test/rbkt/Queries/zorba/nodes/position_3.xq	2011-10-27 20:59:25 +0000
@@ -0,0 +1,32 @@
+import module namespace np = "http://www.zorba-xquery.com/modules/node-position";;
+
+declare function local:test-types($s-info)
+{
+(
+  np:is-attribute($s-info),
+  np:is-comment($s-info),
+  np:is-document($s-info),
+  np:is-element($s-info),
+  np:is-processing-instruction($s-info),
+  np:is-text($s-info)
+)  
+};
+
+variable $doc:=
+document 
+{
+  text{"text"},
+  comment{"comment"},
+  processing-instruction {"processing-instruction"}{"processing-instruction"},
+  element {"element"}{attribute {"attribute"}{"attribute"}}
+};
+
+
+<result>
+  <attr>{local:test-types(np:node-position($doc//attribute()))}</attr>
+  <comm>{local:test-types(np:node-position($doc/comment()))}</comm>
+  <docu>{local:test-types(np:node-position($doc))}</docu>
+  <elem>{local:test-types(np:node-position($doc/element()))}</elem>
+  <proc>{local:test-types(np:node-position($doc/processing-instruction()))}</proc>
+  <text>{local:test-types(np:node-position($doc/text()))}</text>
+</result>   

=== added file 'test/rbkt/Queries/zorba/nodes/position_3_parsed.xq'
--- test/rbkt/Queries/zorba/nodes/position_3_parsed.xq	1970-01-01 00:00:00 +0000
+++ test/rbkt/Queries/zorba/nodes/position_3_parsed.xq	2011-10-27 20:59:25 +0000
@@ -0,0 +1,34 @@
+import module namespace np = "http://www.zorba-xquery.com/modules/node-position";;
+
+declare function local:test-types($s-info)
+{
+  let $s-info2:=xs:anyURI(string($s-info))
+  return
+(
+  np:is-attribute($s-info2),
+  np:is-comment($s-info2),
+  np:is-document($s-info2),
+  np:is-element($s-info2),
+  np:is-processing-instruction($s-info2),
+  np:is-text($s-info2)
+)  
+};
+
+variable $doc:=
+document 
+{
+  text{"text"},
+  comment{"comment"},
+  processing-instruction {"processing-instruction"}{"processing-instruction"},
+  element {"element"}{attribute {"attribute"}{"attribute"}}
+};
+
+
+<result>
+  <attr>{local:test-types(np:node-position($doc//attribute()))}</attr>
+  <comm>{local:test-types(np:node-position($doc/comment()))}</comm>
+  <docu>{local:test-types(np:node-position($doc))}</docu>
+  <elem>{local:test-types(np:node-position($doc/element()))}</elem>
+  <proc>{local:test-types(np:node-position($doc/processing-instruction()))}</proc>
+  <text>{local:test-types(np:node-position($doc/text()))}</text>
+</result>   

=== added file 'test/rbkt/Queries/zorba/nodes/position_4.xq'
--- test/rbkt/Queries/zorba/nodes/position_4.xq	1970-01-01 00:00:00 +0000
+++ test/rbkt/Queries/zorba/nodes/position_4.xq	2011-10-27 20:59:25 +0000
@@ -0,0 +1,84 @@
+import module namespace np = "http://www.zorba-xquery.com/modules/node-position";;
+
+declare function local:get-ordpath($struct)
+{
+replace($struct,'^zorba:\d*\.\d*\.\d*\.','np:')
+};
+
+declare function local:test-generated-ordpath($testa,$testb)
+{
+  let $orda:=local:get-ordpath(np:node-position($testa))
+  let $ordb:=local:get-ordpath(np:node-position($testb))
+  return
+    if ($orda eq $ordb)
+    then concat("OK: ",$orda)    
+    else concat("KO: ",$orda," != ",$ordb)    
+};
+
+variable $test1a:=text{"aaa"};
+variable $test1b:=<aaa/>;
+
+variable $test2a:=<element>aaa</element>;
+variable $test2b:=<element><aaa/></element>;
+
+variable $test3a:=<element><x/>aaa</element>;
+variable $test3b:=<element><x/><aaa/></element>;
+
+variable $test4a:=<element attr="attr">aaa</element>;
+variable $test4b:=<element attr="attr"><aaa/></element>;
+
+variable $test5a:=<element attr="attr"><x/>aaa</element>;
+variable $test5b:=<element attr="attr"><x/><aaa/></element>;
+
+variable $test6a:=<element>aaa</element>;
+variable $test6b:=<element><aaa/></element>;
+
+variable $test7a:=<element><x/>aaa</element>;
+variable $test7b:=<element><x/><aaa/></element>;
+
+variable $test8a:=<element attr="attr">aaa</element>;
+variable $test8b:=<element attr="attr"><aaa/></element>;
+
+variable $test9a:=<element attr="attr"><x/>aaa</element>;
+variable $test9b:=<element attr="attr"><x/><aaa/></element>;
+
+variable $test10a:=<element><bbb/></element>;
+insert node text{"aaa"} as first into $test10a;
+variable $test10b:=<element><bbb/></element>;
+insert node <aaa/> as first into $test10b;
+
+variable $test11a:=<element><x/><bbb/></element>;
+insert node text{"aaa"} after $test11a/x;
+variable $test11b:=<element><x/><bbb/></element>;
+insert node <aaa/> after $test11b/x;
+
+variable $test12a:=<element attr="attr"><bbb/></element>;
+insert node text{"aaa"} as first into $test12a;
+variable $test12b:=<element attr="attr"><bbb/></element>;
+insert node <aaa/> as first into $test12b;
+
+variable $test13a:=<element attr="attr"><x/><bbb/></element>;
+insert node text{"aaa"} after $test13a/x;
+variable $test13b:=<element attr="attr"><x/><bbb/></element>;
+insert node <aaa/> after $test13b/x;
+
+<result>
+  <test1>{local:test-generated-ordpath($test1a,$test1b)}</test1>
+  <test2>{local:test-generated-ordpath($test2a/text(),$test2b/aaa)}</test2>
+  <test3>{local:test-generated-ordpath($test3a/text(),$test3b/aaa)}</test3>
+  <test4>{local:test-generated-ordpath($test4a/text(),$test4b/aaa)}</test4>
+  <test5>{local:test-generated-ordpath($test5a/text(),$test5b/aaa)}</test5>
+  <test6>{local:test-generated-ordpath($test6a/text(),$test6b/aaa)}</test6>
+  <test7>{local:test-generated-ordpath($test7a/text(),$test7b/aaa)}</test7>
+  <test8>{local:test-generated-ordpath($test8a/text(),$test8b/aaa)}</test8>
+  <test9>{local:test-generated-ordpath($test9a/text(),$test9b/aaa)}</test9>
+  <test10>{local:test-generated-ordpath($test10a/text(),$test10b/aaa)}</test10>
+  <test11>{local:test-generated-ordpath($test11a/text(),$test11b/aaa)}</test11>
+  <test12>{local:test-generated-ordpath($test12a/text(),$test12b/aaa)}</test12>
+  <test13>{local:test-generated-ordpath($test13a/text(),$test13b/aaa)}</test13>
+</result>
+
+
+
+
+

=== added file 'test/rbkt/Queries/zorba/nodes/position_4_parsed.xq'
--- test/rbkt/Queries/zorba/nodes/position_4_parsed.xq	1970-01-01 00:00:00 +0000
+++ test/rbkt/Queries/zorba/nodes/position_4_parsed.xq	2011-10-27 20:59:25 +0000
@@ -0,0 +1,81 @@
+import module namespace np = "http://www.zorba-xquery.com/modules/node-position";;
+
+declare function local:get-ordpath($struct)
+{
+replace($struct,'^zorba:\d*\.\d*\.\d*\.','np:')
+};
+
+declare function local:test-generated-ordpath($testa,$testb)
+{
+  let $orda:=local:get-ordpath(xs:anyURI(string(np:node-position($testa))))
+  let $ordb:=local:get-ordpath(xs:anyURI(string(np:node-position($testb))))
+  return
+    if ($orda eq $ordb)
+    then concat("OK: ",$orda)    
+    else concat("KO: ",$orda," != ",$ordb)    
+};
+
+variable $test1a:=text{"aaa"};
+variable $test1b:=<aaa/>;
+
+variable $test2a:=<element>aaa</element>;
+variable $test2b:=<element><aaa/></element>;
+
+variable $test3a:=<element><x/>aaa</element>;
+variable $test3b:=<element><x/><aaa/></element>;
+
+variable $test4a:=<element attr="attr">aaa</element>;
+variable $test4b:=<element attr="attr"><aaa/></element>;
+
+variable $test5a:=<element attr="attr"><x/>aaa</element>;
+variable $test5b:=<element attr="attr"><x/><aaa/></element>;
+
+variable $test6a:=<element>aaa<bbb/></element>;
+variable $test6b:=<element><aaa/><bbb/></element>;
+
+variable $test7a:=<element><x/>aaa<bbb/></element>;
+variable $test7b:=<element><x/><aaa/><bbb/></element>;
+
+variable $test8a:=<element attr="attr">aaa<bbb/></element>;
+variable $test8b:=<element attr="attr"><aaa/><bbb/></element>;
+
+variable $test9a:=<element attr="attr"><x/>aaa<bbb/></element>;
+variable $test9b:=<element attr="attr"><x/><aaa/><bbb/></element>;
+
+variable $test10a:=<element><bbb/></element>;
+insert node text{"aaa"} as first into $test10a;
+variable $test10b:=<element><bbb/></element>;
+insert node <aaa/> as first into $test10b;
+
+variable $test11a:=<element><x/><bbb/></element>;
+insert node text{"aaa"} after $test11a/x;
+variable $test11b:=<element><x/><bbb/></element>;
+insert node <aaa/> after $test11b/x;
+
+variable $test12a:=<element attr="attr"><bbb/></element>;
+insert node text{"aaa"} as first into $test12a;
+variable $test12b:=<element attr="attr"><bbb/></element>;
+insert node <aaa/> as first into $test12b;
+
+variable $test13a:=<element attr="attr"><x/><bbb/></element>;
+insert node text{"aaa"} after $test13a/x;
+variable $test13b:=<element attr="attr"><x/><bbb/></element>;
+insert node <aaa/> after $test13b/x;
+
+<result>
+  <test1>{local:test-generated-ordpath($test1a,$test1b)}</test1>
+  <test2>{local:test-generated-ordpath($test2a/text(),$test2b/aaa)}</test2>
+  <test3>{local:test-generated-ordpath($test3a/text(),$test3b/aaa)}</test3>
+  <test4>{local:test-generated-ordpath($test4a/text(),$test4b/aaa)}</test4>
+  <test5>{local:test-generated-ordpath($test5a/text(),$test5b/aaa)}</test5>
+  <test6>{local:test-generated-ordpath($test6a/text(),$test6b/aaa)}</test6>
+  <test7>{local:test-generated-ordpath($test7a/text(),$test7b/aaa)}</test7>
+  <test8>{local:test-generated-ordpath($test8a/text(),$test8b/aaa)}</test8>
+  <test9>{local:test-generated-ordpath($test9a/text(),$test9b/aaa)}</test9>
+  <test10>{local:test-generated-ordpath($test10a/text(),$test10b/aaa)}</test10>
+  <test11>{local:test-generated-ordpath($test11a/text(),$test11b/aaa)}</test11>
+  <test12>{local:test-generated-ordpath($test12a/text(),$test12b/aaa)}</test12>
+  <test13>{local:test-generated-ordpath($test13a/text(),$test13b/aaa)}</test13>
+</result>
+
+

=== added file 'test/rbkt/Queries/zorba/nodes/position_err.xq'
--- test/rbkt/Queries/zorba/nodes/position_err.xq	1970-01-01 00:00:00 +0000
+++ test/rbkt/Queries/zorba/nodes/position_err.xq	2011-10-27 20:59:25 +0000
@@ -0,0 +1,60 @@
+import module namespace np = "http://www.zorba-xquery.com/modules/node-position";;
+
+declare namespace err="http://www.w3.org/2005/xqt-errors";;
+
+declare namespace zerr = "http://www.zorba-xquery.com/errors";;
+
+try
+{
+np:ancestor-of(xs:anyURI("not a uri"),xs:anyURI("not a uri"))
+}
+catch * 
+{
+<err>
+<err-code>{$err:code}</err-code>
+<err-description>{$err:description}</err-description>
+<err-value>{$err:value}</err-value>
+<err-line>{$err:line-number}</err-line>
+</err>
+},
+
+"
+
+",
+
+try
+{
+np:in-same-tree-of(xs:anyURI("zorba:0.3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333.1.50"),xs:anyURI("zorba:0.0.1.50"))
+}
+catch * 
+{
+<err>
+<err-code>{$err:code}</err-code>
+<err-description>{$err:description}</err-description>
+<err-value>{$err:value}</err-value>
+<err-line>{$err:line-number}</err-line>
+</err>
+},
+
+"
+
+",
+
+try
+{
+np:in-same-tree-of(xs:anyURI("zorba:0..1.50"),xs:anyURI("zorba:0.0.1.50"))
+}
+catch * 
+{
+<err>
+<err-code>{$err:code}</err-code>
+<err-description>{$err:description}</err-description>
+<err-value>{$err:value}</err-value>
+<err-line>{$err:line-number}</err-line>
+</err>
+},
+
+"
+
+"
+


Follow ups