Add -DNDEBUG to makefile.
[SXSI/XMLTree.git] / XMLTree.cpp
index dfda61a..a0815b8 100644 (file)
@@ -1,94 +1,85 @@
 #include "basics.h"\r
-#include <cstring>\r
-#include <sstream>\r
 #include "XMLTree.h"\r
-#include <sys/time.h>\r
-#include <time.h>\r
-#include <sys/stat.h> \r
-#include <unistd.h>\r
-\r
-static double tLoading = 0;\r
-\r
-static unsigned int cLoading = 0;\r
-static struct timeval tmpv1;\r
-static struct timeval tmpv2;\r
-static string mem1;\r
-static string mem2;\r
-\r
-void read_procmem(string& memstr) {\r
-  std::string buf;\r
-  pid_t pid = getpid();\r
-  std::stringstream path;\r
-  path <<  "/proc/" << pid << "/status";\r
-  std::ifstream infile;\r
-  infile.open (path.str().c_str(), std::ifstream::in);\r
-  while (infile.good()){\r
-    getline(infile,buf);\r
-    if (infile.eof()) {\r
-      memstr = "Could not read memory";\r
-      return;\r
-    };\r
-    int idx = buf.find("VmRSS");\r
-    if (idx == 0){\r
-      memstr = buf;\r
-      return;\r
-    };\r
-  };\r
-  memstr = "Could not read memory";\r
-  return;\r
+#include "timings.h"\r
+#include <errno.h>\r
+using std::cout;\r
+using std::endl;\r
+using std::min;\r
+using std::string;\r
+\r
+// functions to convert tag positions to the corresponding tree node and viceversa. \r
+// These are implemented in order to be able to change the tree and Tags representations, \r
+// without affecting the code so much.\r
+// Current implementation corresponds to balanced-parentheses representation for\r
+// the tree, and storing 2 tags per tree node (opening and closing tags).\r
 \r
+\r
+static int bits8 (int t ) {\r
+  int r = bits(t);\r
+  if (r <= 8)\r
+    return 8;\r
+  else if (r <= 16)\r
+    return 16;\r
+  else \r
+    return r;\r
 }\r
 \r
-#define STARTTIMER()   do {                                            \\r
-  gettimeofday(&tmpv1,NULL);                                           \\r
-  read_procmem(mem1);                                                  \\r
-  } while (0)                                                          \\r
 \r
-#define STOPTIMER(x)   do {                                            \\r
-    read_procmem(mem2);                                                        \\r
-    gettimeofday(&tmpv2,NULL);                                         \\r
-    (t##x) = ((tmpv2.tv_sec  - tmpv1.tv_sec) * 1000000.0 +             \\r
-                      (tmpv2.tv_usec  - tmpv1.tv_usec))/1000.0;        \\r
-    (c##x)= (c##x)+1;                                                  \\r
-  } while (0)\r
 \r
-#define PRINTTIME(s,x) do {                                            \\r
-    std::cerr << (s) << " : " << (t##x) << "ms" << std::endl;          \\r
-    std::cerr << "Mem use before: " << mem1 << std::endl;              \\r
-    std::cerr << "Mem use after: " << mem2 << std::endl;               \\r
-    std::cerr.flush();                                                 \\r
-  } while (0)                                                          \\r
 \r
+static treeNode fast_sibling(bp* Par,treeNode x,TagType tag){\r
 \r
-// functions to convert tag positions to the corresponding tree node and viceversa. \r
-// These are implemented in order to be able to change the tree and Tags representations, \r
-// without affecting the code so much.\r
-// Current implementation corresponds to balanced-parentheses representation for\r
-// the tree, and storing 2 tags per tree node (opening and closing tags).\r
+  if (tag == PCDATA_TAG_ID){\r
+    x = x+2;\r
+    return fast_inspect(Par,x)==OP ? x : NULLT;\r
+  } else return fast_next_sibling(Par,x);\r
 \r
-// tag position -> tree node\r
-inline treeNode tagpos2node(int t) \r
- {\r
-    return (treeNode) t;\r
- }\r
+}\r
+\r
+static bool fast_isleaf(bp* Par,treeNode x){\r
+  return (fast_inspect(Par,x+1) == CP ? true : false);\r
+}\r
+\r
+\r
+inline uint get_field_no_power(uint *A, uint len, uint index) {\r
+  \r
+  register uint i=index*len/W, j=index*len-W*i;\r
+  return (j+len <= W) ? (A[i] << (W-j-len)) >> (W-len) : (A[i] >> j) | (A[i+1] << (WW-j-len)) >> (W-len);\r
+\r
+}\r
 \r
-// tree node -> tag position\r
-inline int node2tagpos(treeNode x) \r
+static uint fast_get_field(uint* A,int len, int idx)\r
 {\r
-  return (int)x;\r
+  uint f1, f2;\r
+  switch (len) {\r
+  case 8:\r
+    return (uint) (((uchar*)A)[idx]);\r
+  case 16:\r
+    f2 = ((unsigned short*)A)[idx];\r
+    f1 = ((unsigned short*)A)[idx+1];\r
+    return (f1 << 16) + f2;\r
+  default:\r
+    return   get_field_no_power (A,len,idx);\r
+  };\r
+\r
 }\r
 \r
-// returns NULLT if the test is true\r
-#define NULLT_IF(x)  do { if (x) return NULLT; } while (0)\r
 \r
 \r
-XMLTree::XMLTree( pb * const par, uint npar,  vector<string> * const TN,  TagIdMap * const tim, uint *empty_texts_bmp, TagType *tags,\r
-            TextCollection * const TC, bool dis_tc)\r
 \r
+XMLTree::XMLTree( pb * const par, uint npar,  vector<string> * const TN,  TagIdMap * const tim, \r
+                 uint *empty_texts_bmp, TagType *tags,\r
+                 TextCollection * const TC, bool dis_tc)\r
  {\r
+   buffer = 0;\r
     // creates the data structure for the tree topology\r
     Par = (bp *)umalloc(sizeof(bp));\r
-    bp_construct(Par, npar, (pb*) par, OPT_DEGREE|0);    \r
+    STARTTIMER();\r
+    bp_construct(Par, npar, (pb*) par, OPT_DEGREE|0);\r
+    STOPTIMER(Building);\r
+    PRINTTIME("Building parenthesis struct", Building);\r
+    STARTTIMER();\r
+\r
    \r
     // creates structure for tags\r
 \r
@@ -96,32 +87,43 @@ XMLTree::XMLTree( pb * const par, uint npar,  vector<string> * const TN,  TagIdM
     tIdMap = (TagIdMap *) tim;\r
     \r
     uint max_tag = TN->size() - 1;\r
+    \r
       \r
     static_bitsequence_builder *bmb = new static_bitsequence_builder_sdarray();\r
     alphabet_mapper *am = new alphabet_mapper_none();\r
     Tags = new static_sequence_bs((uint*)tags,npar,am,bmb);\r
     \r
-    cout << "Tags test: " << Tags->test((uint*)tags,npar) << endl;\r
+    //cout << "Tags test: " << Tags->test((uint*)tags,npar) << endl;\r
 \r
-    tags_blen = bits(max_tag);\r
+    //Ensures that for small tag numbers, we are on an 8bit boundary.\r
+    //Makes tag access way faster with negligeable waste of space.\r
+    tags_blen = bits8(max_tag);\r
+    std::cerr << "Tags blen is " << tags_blen << "\n";\r
     tags_len = (uint)npar;\r
     tags_fix = new uint[uint_len(tags_blen,tags_len)];\r
     for(uint i=0;i<(uint)npar;i++)\r
        set_field(tags_fix,tags_blen,i,tags[i]);\r
-\r
     delete bmb;    \r
     free(tags);\r
     tags = NULL;\r
+\r
+    STOPTIMER(Building);\r
+    PRINTTIME("Building Tag Structure", Building);\r
     \r
     Text = (TextCollection*) TC;\r
 \r
 \r
     EBVector = new static_bitsequence_rrr02(empty_texts_bmp,npar,32);\r
+    //EBVector = new static_bitsequence_sdarray(empty_texts_bmp,npar);\r
     free(empty_texts_bmp);\r
     empty_texts_bmp = NULL;\r
 \r
     \r
     disable_tc = dis_tc;\r
+    stream = NULL;\r
+    stream_fd = 0;\r
+    std::cerr << "Number of distinct tags " << TagName->size() << "\n";\r
+    //std::cerr.flush();\r
  }\r
 \r
 \r
@@ -147,7 +149,11 @@ XMLTree::~XMLTree()
 \r
     delete EBVector;\r
     EBVector = NULL;\r
-\r
+    if (stream != NULL){\r
+      fclose(stream);\r
+      stream = NULL;\r
+      stream_fd = 0;\r
+    };\r
 \r
  }\r
 \r
@@ -164,7 +170,7 @@ void XMLTree::print_stats()
  }\r
 \r
 // Save: saves XML tree data structure to file. \r
-void XMLTree::Save(int fd) \r
+void XMLTree::Save(int fd, char *filename\r
  {\r
     FILE *fp;\r
     char filenameaux[1024];\r
@@ -196,23 +202,22 @@ void XMLTree::Save(int fd)
     \r
     // stores the texts   \r
     if (!disable_tc) {\r
-      Text->Save(fp);\r
+        Text->Save(fp, filename);\r
     };\r
-\r
-\r
  }\r
 \r
 \r
 // Load: loads XML tree data structure from file. Returns\r
 // a pointer to the loaded data structure\r
-XMLTree *XMLTree::Load(int fd) \r
+XMLTree *XMLTree::Load(int fd, char *filename, bool load_tc,int sample_factor\r
  {\r
+\r
     FILE *fp;\r
     char buffer[1024];\r
     XMLTree *XML_Tree;\r
     int i;\r
 \r
-\r
+    buffer[1023] = '\0';\r
 \r
     fp = fdopen(fd, "r");\r
 \r
@@ -226,23 +231,21 @@ XMLTree *XMLTree::Load(int fd)
     PRINTTIME("Loading parenthesis struct", Loading);\r
     STARTTIMER();\r
 \r
-    XML_Tree->TagName = new vector<string>();\r
-    XML_Tree->tIdMap = new std::unordered_map<string,int>();\r
-    \r
-    string s;\r
+    XML_Tree->TagName = new std::vector<std::string>();\r
+    XML_Tree->tIdMap = new std::unordered_map<std::string,int>();\r
+    std::string s;\r
     int ntags;\r
     \r
     // Load the tag names\r
     ufread(&ntags, sizeof(int), 1, fp);\r
 \r
     for (i=0; i<ntags;i++) {\r
-      char * r = fgets(buffer,1023,fp);\r
-       if (r==NULL)\r
+       if (fgets(buffer,1022,fp) != buffer)\r
         throw "Cannot read tag list";\r
-       s = (const char*) buffer;\r
+       s = buffer;\r
        // remove the trailing \n\r
        s.erase(s.size()-1);       \r
-       XML_Tree->TagName->push_back(s);\r
+       XML_Tree->TagName->push_back(s);       \r
        XML_Tree->tIdMap->insert(std::make_pair(s,i));\r
        \r
     };\r
@@ -253,55 +256,60 @@ XMLTree *XMLTree::Load(int fd)
     // loads the tag structure\r
     XML_Tree->Tags = static_sequence::load(fp);\r
     ufread(&XML_Tree->tags_blen,sizeof(uint),1,fp);\r
+    std::cerr << "tags_blen is "<< XML_Tree->tags_blen <<"\n";    \r
     ufread(&XML_Tree->tags_len,sizeof(uint),1,fp);\r
     XML_Tree->tags_fix = new uint[uint_len(XML_Tree->tags_blen,XML_Tree->tags_len)];\r
     ufread(XML_Tree->tags_fix,sizeof(uint),uint_len(XML_Tree->tags_blen,XML_Tree->tags_len),fp);\r
 \r
     // TODO ask francisco about this\r
     /// FIXME:UGLY tests!\r
-    uint * seq = new uint[XML_Tree->tags_len];\r
-    for(uint i=0;i<XML_Tree->tags_len;i++)\r
-      seq[i] = get_field(XML_Tree->tags_fix,XML_Tree->tags_blen,i);\r
+    //uint * seq = new uint[XML_Tree->tags_len];\r
+    //for(uint i=0;i<XML_Tree->tags_len;i++)\r
+    //  seq[i] = get_field(XML_Tree->tags_fix,XML_Tree->tags_blen,i);\r
     //cout << "Tags test: " << XML_Tree->Tags->test(seq,XML_Tree->tags_len) << endl;\r
-    XML_Tree->Tags->test(seq,XML_Tree->tags_len);\r
-    delete [] seq;\r
+    //XML_Tree->Tags->test(seq,XML_Tree->tags_len);\r
+    //delete [] seq;\r
     /// End ugly tests\r
     \r
     STOPTIMER(Loading);\r
+    std::cerr << (uint_len(XML_Tree->tags_blen,XML_Tree->tags_len)*sizeof(uint))/(1024*1024) << " MB for tag sequence" << std::endl;\r
     PRINTTIME("Loading tag struct", Loading);\r
     STARTTIMER();\r
 \r
     // loads the flags\r
     \r
     ufread(&(XML_Tree->disable_tc), sizeof(bool), 1, fp);\r
-\r
+    if (load_tc) {\r
     XML_Tree->EBVector = static_bitsequence_rrr02::load(fp);\r
-\r
+    //XML_Tree->EBVector = static_bitsequence_sdarray::load(fp);\r
 \r
     STOPTIMER(Loading);\r
     PRINTTIME("Loading text bitvector struct", Loading);\r
     STARTTIMER();\r
 \r
     // Not used  \r
-    int sample_rate_text = 64;\r
     // loads the texts\r
     if (!XML_Tree->disable_tc){\r
-      XML_Tree->Text = TextCollection::Load(fp,sample_rate_text);\r
+        XML_Tree->Text = TextCollection::Load(fp, filename, TextCollection::index_mode_default, sample_factor);\r
     }\r
     else XML_Tree->Text = NULL;\r
     STOPTIMER(Loading);\r
     PRINTTIME("Loading TextCollection", Loading);\r
-    STARTTIMER();\r
+    STARTTIMER(); \r
+    }\r
+    else {\r
+      XML_Tree->EBVector = NULL;\r
+      XML_Tree->Text = NULL;\r
+      XML_Tree->disable_tc = true;\r
+    };\r
 \r
+    XML_Tree->stream = NULL;\r
+    XML_Tree->stream_fd = 0;\r
+    \r
     return XML_Tree;\r
  }\r
 \r
 \r
-// root(): returns the tree root.\r
-inline treeNode XMLTree::Root() \r
- {\r
-   return 0; //root_node(Par);\r
- }\r
 \r
 // SubtreeSize(x): the number of nodes (and attributes) in the subtree of node x.\r
 int XMLTree::SubtreeSize(treeNode x) \r
@@ -313,40 +321,61 @@ int XMLTree::SubtreeSize(treeNode x)
 int XMLTree::SubtreeTags(treeNode x, TagType tag) \r
  {\r
     if (x == Root())\r
-      x = first_child(Par,x);\r
+      x = fast_first_child(Par,x);\r
     \r
 \r
     int s = x + 2*subtree_size(Par, x) - 1;\r
  \r
-    return Tags->rank(tag, s) - Tags->rank(tag, node2tagpos(x)-1);\r
+    return (Tags->rank(tag, s) - Tags->rank(tag, node2tagpos(x)-1))+1;\r
+ }\r
+int XMLTree::SubtreeElements(treeNode x) \r
+ {\r
+    \r
+    int size = subtree_size(Par,x);\r
+    if (x == Root()){\r
+      x = fast_first_child(Par,x);\r
+      size = size - 1;\r
+    };\r
+\r
+    int s = x + 2*size - 1;\r
+    int ntext = Tags->rank(PCDATA_TAG_ID, s) - Tags->rank(PCDATA_TAG_ID, node2tagpos(x)-1);\r
+    size = size - ntext;\r
+    treeNode fin = fast_find_close(Par,x);\r
+    treeNode y = Tags->select_next(ATTRIBUTE_TAG_ID,node2tagpos(x));\r
+    while (y != NULLT && y < fin){\r
+      size -= SubtreeSize(y);\r
+      y = Tags->select_next(ATTRIBUTE_TAG_ID,node2tagpos(y));\r
+    };\r
+    return size;    \r
  }\r
 \r
 // IsLeaf(x): returns whether node x is leaf or not. In the succinct representation\r
 // this is just a bit inspection.\r
 bool XMLTree::IsLeaf(treeNode x) \r
  {\r
-    return isleaf(Par, x);\r
+   NULLT_IF(x==NULLT);\r
+   return fast_isleaf(Par, x);\r
  } \r
 \r
 // IsAncestor(x,y): returns whether node x is ancestor of node y.\r
 bool XMLTree::IsAncestor(treeNode x, treeNode y) \r
  {\r
-    return is_ancestor(Par, x, y);\r
+    return fast_is_ancestor(Par, x, y);\r
  }\r
 \r
 // IsChild(x,y): returns whether node x is parent of node y.\r
 bool XMLTree::IsChild(treeNode x, treeNode y) \r
  {\r
-    if (!is_ancestor(Par, x, y)) return false;\r
+    if (!fast_is_ancestor(Par, x, y)) return false;\r
     return depth(Par, x) == (depth(Par, y) + 1);\r
  }\r
 \r
 // IsFirstChild(x): returns whether node x is the first child of its parent.\r
-bool XMLTree::IsFirstChild(treeNode x)\r
+/*bool XMLTree::IsFirstChild(treeNode x)\r
  {\r
     return ((x != NULLT)&&(x==Root() || prev_sibling(Par,x) == (treeNode)-1));\r
  }\r
-\r
+*/\r
 \r
 // NumChildren(x): number of children of node x. Constant time with the data structure\r
 // of Sadakane.\r
@@ -380,47 +409,45 @@ int XMLTree::Postorder(treeNode x)
  {\r
     return postorder_rank(Par, x);\r
  }\r
-\r
+/*\r
 // Tag(x): returns the tag identifier of node x.\r
 TagType XMLTree::Tag(treeNode x) \r
  {\r
-    return get_field(tags_fix,tags_blen,node2tagpos(x));\r
+    return fast_get_field(tags_fix,tags_blen,node2tagpos(x));\r
  }\r
-\r
+*/\r
 // DocIds(x): returns the range of text identifiers that descend from node x.\r
 // returns {NULLT, NULLT} when there are no texts descending from x.\r
 range XMLTree::DocIds(treeNode x) \r
  {\r
-    range r;\r
-    if (x == NULLT) {\r
-       r.min = NULLT;\r
-       r.max = NULLT;\r
-       return r;\r
-    };\r
-        \r
-    \r
-    int min = EBVector->rank1(x-1);                          \r
-    int max = EBVector->rank1(x+2*subtree_size(Par, x)-2); \r
-    if (min==max) { // range is empty, no texts within the subtree of x\r
-      r.min = NULLT;\r
-      r.max = NULLT;\r
-    }\r
-    else { // the range is non-empty, there are texts within the subtree of x\r
-      r.min = min+1;\r
-      r.max = max;\r
-    }\r
-    return r;\r
-\r
+   range r;\r
+   if (x == NULLT) {\r
+     r.min = NULLT;\r
+     r.max = NULLT;\r
+     return r;\r
+   };\r
+   int min = EBVector->rank1(x-1);                          \r
+   int max = EBVector->rank1(x+2*subtree_size(Par, x)-2); \r
+   if (min==max) { // range is empty, no texts within the subtree of x\r
+     r.min = NULLT;\r
+     r.max = NULLT;\r
+   }\r
+   else { // the range is non-empty, there are texts within the subtree of x\r
+     r.min = min+1;\r
+     r.max = max;\r
+   }\r
+   return r;\r
  }\r
 \r
 // Parent(x): returns the parent node of node x.\r
+/*\r
 treeNode XMLTree::Parent(treeNode x) \r
  {\r
     if (x == Root())\r
       return NULLT;\r
     else\r
-      return parent(Par, x);\r
- }\r
+      return  parent(Par, x);;\r
+ }*/\r
 \r
 // Child(x,i): returns the i-th child of node x, assuming it exists.\r
 treeNode XMLTree::Child(treeNode x, int i) \r
@@ -430,47 +457,69 @@ treeNode XMLTree::Child(treeNode x, int i)
 }\r
 \r
 // FirstChild(x): returns the first child of node x, assuming it exists. Very fast in BP.\r
+/*\r
 treeNode XMLTree::FirstChild(treeNode x) \r
  {\r
    NULLT_IF(x==NULLT);\r
-   return first_child(Par, x);\r
+   return fast_first_child(Par, x);\r
  }\r
-\r
+*/\r
+/*\r
 treeNode XMLTree::FirstElement(treeNode x) \r
  {\r
    NULLT_IF(x==NULLT);\r
-   treeNode fc = first_child(Par, x);\r
-   //<$> is 2\r
-   return ((fc == NULLT || Tag(fc) != PCDATA_TAG_ID) ? fc : next_sibling(Par,fc));\r
-\r
+   x = fast_first_child(Par, x);\r
+   NULLT_IF(x == NULLT);\r
+   switch (Tag(x)){\r
+  \r
+   case PCDATA_TAG_ID:\r
+     x = x+2;\r
+     return (fast_inspect(Par,x)==OP)? x : NULLT;\r
+     \r
+   case ATTRIBUTE_TAG_ID:  \r
+     x = fast_next_sibling(Par,x);\r
+     if (x != NULLT && Tag(x) == PCDATA_TAG_ID){\r
+       x = x+2;\r
+       return (fast_inspect(Par,x)==OP)? x : NULLT;\r
+     } \r
+     else return x;     \r
+   default:\r
+     return x;\r
+   }\r
  }\r
-\r
+*//*\r
 treeNode XMLTree::NextElement(treeNode x) \r
 {\r
-   NULLT_IF(x==NULLT);\r
-   treeNode ns = next_sibling(Par, x);\r
-   return ((ns == NULLT || Tag(ns) != PCDATA_TAG_ID) ? ns : next_sibling(Par,ns));\r
-}\r
+  NULLT_IF(x==NULLT);\r
+  x = fast_next_sibling(Par, x);\r
+  NULLT_IF(x == NULLT);   \r
+  if (Tag(x) == PCDATA_TAG_ID){\r
+    x = x+2;\r
+     return (fast_inspect(Par,x)==OP)? x : NULLT;\r
+  }\r
+  else return x;  \r
+  }*/\r
 \r
 // LastChild(x): returns the last child of node x.\r
 treeNode XMLTree::LastChild(treeNode x)\r
  {\r
-   NULLT_IF(x==NULLT || x == Root() || isleaf(Par,x));\r
-   return find_open(Par, find_close(Par, x)-1);\r
+   NULLT_IF(x == NULLT || fast_isleaf(Par,x));\r
+   return find_open(Par, fast_find_close(Par, x)-1);\r
  }\r
 \r
-\r
 // NextSibling(x): returns the next sibling of node x, assuming it exists.\r
-treeNode XMLTree::NextSibling(treeNode x) \r
+/*treeNode XMLTree::NextSibling(treeNode x) \r
  {\r
    NULLT_IF(x==NULLT || x == Root() );\r
-   return next_sibling(Par, x);\r
+   x = fast_find_close(Par,x)+1;\r
+   return (fast_inspect(Par,x) == CP ? NULLT : x);\r
  }\r
+*/\r
 \r
 // PrevSibling(x): returns the previous sibling of node x, assuming it exists.\r
 treeNode XMLTree::PrevSibling(treeNode x) \r
  {\r
-   NULLT_IF(x==NULLT || x == Root());\r
+   NULLT_IF(x==NULLT);\r
    return prev_sibling(Par, x);\r
  }\r
 \r
@@ -480,85 +529,88 @@ treeNode XMLTree::PrevSibling(treeNode x)
 treeNode XMLTree::TaggedChild(treeNode x, TagType tag) \r
  {\r
    \r
-   NULLT_IF(x==NULLT || isleaf(Par,x));\r
-\r
+   NULLT_IF(x==NULLT || fast_isleaf(Par,x));\r
    treeNode child;   \r
-   child = first_child(Par, x); // starts at first child of node x\r
-   if (get_field(tags_fix,tags_blen,node2tagpos(child)) == tag)\r
+   child = fast_first_child(Par, x); // starts at first child of node x\r
+   if (Tag(child) == tag)\r
      return child;\r
    else\r
-     return TaggedFollSibling(child,tag);\r
+     return TaggedFollowingSibling(child,tag);\r
  }\r
 \r
 // TaggedSibling(x,tag): returns the first sibling of node x tagged tag, or NULLT if there is none.\r
-treeNode XMLTree::TaggedFollSibling(treeNode x, TagType tag)\r
+treeNode XMLTree::TaggedFollowingSibling(treeNode x, TagType tag)\r
 {\r
   NULLT_IF(x==NULLT);\r
-  treeNode sibling = next_sibling(Par, x); \r
+  treeNode sibling = fast_next_sibling(Par, x);\r
+  TagType ctag;\r
   while (sibling != NULLT) {\r
-    if (get_field(tags_fix,tags_blen,node2tagpos(sibling)) == tag) // current sibling is labeled with tag of interest\r
+    ctag = Tag(sibling);\r
+    if (ctag == tag) // current sibling is labeled with tag of interest\r
       return sibling; \r
-    sibling = next_sibling(Par, sibling); // OK, let's try with the next sibling\r
+    sibling = fast_sibling(Par, sibling, ctag); // OK, let's try with the next sibling\r
   }\r
   return NULLT; // no such sibling was found   \r
 }\r
 \r
-treeNode XMLTree::SelectChild(treeNode x, std::unordered_set<int> *tags)\r
+treeNode XMLTree::SelectChild(treeNode x, TagIdSet *tags)\r
 {\r
   \r
-  NULLT_IF(x==NULLT || isleaf(Par,x));\r
+  NULLT_IF(x==NULLT || fast_isleaf(Par,x));\r
   int i;\r
-  treeNode child = first_child(Par, x);  \r
-  TagType t = get_field(tags_fix, tags_blen, node2tagpos(child));\r
-  std::unordered_set<int>::const_iterator tagit = tags->find(t);\r
-  if (tagit != tags->end()) return child;  \r
-  return SelectFollSibling(child,tags);\r
+  treeNode child = fast_first_child(Par, x);  \r
+  TagType t;\r
+  while (child != NULLT) {\r
+    t = Tag(child);\r
+    if (tags->find(t) != tags->end()) return child;\r
+    child = fast_sibling(Par, child,t);\r
+  }\r
+  return NULLT;  \r
 }\r
 \r
 \r
-treeNode XMLTree::SelectFollSibling(treeNode x, std::unordered_set<int> *tags)\r
+treeNode XMLTree::SelectFollowingSibling(treeNode x, TagIdSet *tags)\r
 {\r
 \r
    NULLT_IF(x==NULLT);\r
    int i;\r
    TagType t;\r
-   treeNode sibling = next_sibling(Par, x);\r
-   std::unordered_set<int>::const_iterator tagit;\r
+   treeNode sibling = fast_next_sibling(Par, x);\r
    while (sibling != NULLT) {\r
-     t = get_field(tags_fix, tags_blen, node2tagpos(sibling));\r
-     tagit = tags->find(t);\r
-     if (tagit != tags->end()) return sibling;\r
-     sibling = next_sibling(Par, sibling);\r
+     t = Tag(sibling);\r
+     if (tags->find(t) != tags->end()) return sibling;\r
+     sibling = fast_sibling(Par, sibling,t);\r
    }\r
    return NULLT;    \r
  }\r
 \r
 \r
-// TaggedDesc(x,tag): returns the first node tagged tag with larger preorder than x and within\r
+// TaggedDescendant(x,tag): returns the first node tagged tag with larger preorder than x and within\r
 // the subtree of x. Returns NULLT if there is none.\r
-treeNode XMLTree::TaggedDesc(treeNode x, TagType tag) \r
+/*\r
+treeNode XMLTree::TaggedDescendant(treeNode x, TagType tag) \r
  {\r
-   NULLT_IF(x==NULLT || isleaf(Par,x));\r
+   //NULLT_IF(x==NULLT || fast_isleaf(Par,x));\r
 \r
    int s = (int) Tags->select_next(tag,node2tagpos(x));\r
    NULLT_IF (s == -1);\r
 \r
    treeNode y = tagpos2node(s); // transforms the tag position into a node position\r
    \r
-   return (is_ancestor(Par,x,y) ? y : NULLT);\r
+   return (fast_is_ancestor(Par,x,y) ? y : NULLT);\r
  }\r
+*/\r
 \r
-\r
-treeNode XMLTree::SelectDesc(treeNode x, std::unordered_set<int> *tags)\r
+treeNode XMLTree::SelectDescendant(treeNode x, TagIdSet *tags)\r
  {\r
-   NULLT_IF (x ==NULLT || isleaf(Par,x));\r
+   NULLT_IF (x ==NULLT || fast_isleaf(Par,x));\r
    int i;\r
    treeNode min = NULLT;\r
-   treeNode fc = first_child(Par,x);\r
+   treeNode fc = fast_first_child(Par,x);\r
    treeNode aux;\r
-   std::unordered_set<int>::const_iterator tagit;\r
+   TagIdSet::const_iterator tagit;\r
    for (tagit = tags->begin(); tagit != tags->end(); tagit++) {\r
-     aux = TaggedDesc(x, (TagType) *tagit);\r
+     aux = TaggedDescendant(x, (TagType) *tagit);\r
      if (aux == fc) return fc;\r
      if (aux == NULLT) continue;\r
      if ((min == NULLT) || (aux < min)) min = aux;\r
@@ -570,7 +622,7 @@ treeNode XMLTree::SelectDesc(treeNode x, std::unordered_set<int> *tags)
 \r
 // TaggedPrec(x,tag): returns the first node tagged tag with smaller preorder than x and not an\r
 // ancestor of x. Returns NULLT if there is none.\r
-treeNode XMLTree::TaggedPrec(treeNode x, TagType tag) \r
+treeNode XMLTree::TaggedPreceding(treeNode x, TagType tag) \r
  {    \r
     int r, s;\r
     treeNode node_s, root;\r
@@ -579,7 +631,7 @@ treeNode XMLTree::TaggedPrec(treeNode x, TagType tag)
     s = (int)Tags->select(tag, r);\r
     root = root_node(Par);\r
     node_s = tagpos2node(s);\r
-    while (is_ancestor(Par, node_s, x) && (node_s!=root)) { // the one that we found is an ancestor of x\r
+    while (fast_is_ancestor(Par, node_s, x) && (node_s!=root)) { // the one that we found is an ancestor of x\r
        r--;\r
        if (r==0) return NULLT; // there is no such node\r
        s = (int)Tags->select(tag, r);  // we should use select_prev instead when provided\r
@@ -591,43 +643,93 @@ treeNode XMLTree::TaggedPrec(treeNode x, TagType tag)
 \r
 // TaggedFoll(x,tag): returns the first node tagged tag with larger preorder than x and not in\r
 // the subtree of x. Returns NULLT if there is none.\r
-treeNode XMLTree::TaggedFoll(treeNode x, TagType tag)\r
+treeNode XMLTree::TaggedFollowing(treeNode x, TagType tag)\r
  {\r
-   NULLT_IF (x ==NULLT || x == Root());\r
-   \r
-   return tagpos2node(Tags->select_next(tag,find_close(Par, x)));\r
+   NULLT_IF (x ==NULLT || x == Root());   \r
+   return tagpos2node(Tags->select_next(tag,fast_find_close(Par, x)));\r
 \r
  } \r
 \r
 // TaggedFollBelow(x,tag,root): returns the first node tagged tag with larger preorder than x \r
 // and not in the subtree of x. Returns NULLT if there is none.\r
-treeNode XMLTree::TaggedFollBelow(treeNode x, TagType tag, treeNode root)\r
+/*\r
+treeNode XMLTree::TaggedFollowingBelow(treeNode x, TagType tag, treeNode ancestor)\r
 {\r
+  // NULLT_IF (x == NULLT || x == Root() || x == ancestor); \r
 \r
-  NULLT_IF (x == NULLT || x == Root());\r
+  //Special optimisation, test for the following sibling first\r
+  treeNode close = fast_find_close(Par, x);\r
+  treeNode s = tagpos2node(Tags->select_next(tag, close));\r
   \r
-  treeNode s = tagpos2node(Tags->select_next(tag, find_close(Par, x)));\r
+  if (ancestor == Root() || s==NULLT || s < fast_find_close(Par,ancestor)) return s;\r
+  else return NULLT;\r
+} \r
+*/\r
+\r
+treeNode XMLTree::TaggedFollowingBefore(treeNode x, TagType tag, treeNode closing)\r
+{\r
+\r
+  NULLT_IF (x == NULLT || x == Root());\r
   \r
-  if (root == Root()) return s;\r
-  NULLT_IF (s == NULLT || s >= find_close(Par, root));\r
+  treeNode s = tagpos2node(Tags->select_next(tag, fast_find_close(Par, x)));  \r
+  NULLT_IF (s == NULLT || s >= closing);\r
   \r
   return s;\r
 } \r
 \r
 /* Here we inline TaggedFoll to find the min globally, and only at the end\r
    we check if the min is below the context node */\r
-treeNode XMLTree::SelectFollBelow(treeNode x, std::unordered_set<int> *tags, treeNode root)\r
+treeNode XMLTree::SelectFollowingBelow(treeNode x, TagIdSet *tags, treeNode ancestor)\r
  {\r
 \r
    NULLT_IF(x==NULLT || x==Root());\r
+\r
+   treeNode close = fast_find_close(Par,x);\r
+   treeNode ns = close+1;\r
+   if ( (fast_inspect(Par,ns) == OP) && (tags->find(Tag(ns)) != tags->end()))\r
+     return ns;\r
+\r
    int i;\r
    treeNode min = NULLT;\r
-   treeNode ns = next_sibling(Par, x);\r
    treeNode aux;\r
-   std::unordered_set<int>::const_iterator tagit;\r
+  \r
+\r
+   TagIdSet::const_iterator tagit;\r
    for (tagit = tags->begin(); tagit != tags->end(); tagit++) {\r
 \r
-     aux = tagpos2node(Tags->select_next(*tagit, find_close(Par, x)));\r
+     aux = tagpos2node(Tags->select_next(*tagit, close));\r
+     \r
+     // The next sibling of x is guaranteed to be below ctx\r
+     // and is the node with lowest preorder which is after ctx.\r
+     // if we find it, we return early;         \r
+     if (aux == NULLT) continue;\r
+     if ((min == NULLT) || (aux < min)) min = aux;\r
+   };\r
+     \r
+   // found the smallest node in preorder which is after x.\r
+   // if ctx is the root node, just return what we found.\r
+\r
+   if (ancestor == Root()) return min;\r
+   // else check whether if is in below the ctx node\r
+\r
+   NULLT_IF (min == NULLT || min >= fast_find_close(Par, ancestor));\r
+   \r
+   return min;\r
+   \r
+ }\r
+treeNode XMLTree::SelectFollowingBefore(treeNode x, TagIdSet *tags, treeNode closing)\r
+ {\r
+\r
+   NULLT_IF(x==NULLT || x==Root());\r
+   int i;\r
+   treeNode min = NULLT;\r
+   treeNode ns = fast_next_sibling(Par, x);\r
+   treeNode close = ns - 1;\r
+   treeNode aux;\r
+   TagIdSet::const_iterator tagit;\r
+   for (tagit = tags->begin(); tagit != tags->end(); tagit++) {\r
+\r
+     aux = tagpos2node(Tags->select_next(*tagit, close));\r
      \r
      // The next sibling of x is guaranteed to be below ctx\r
      // and is the node with lowest preorder which is after ctx.\r
@@ -641,10 +743,7 @@ treeNode XMLTree::SelectFollBelow(treeNode x, std::unordered_set<int> *tags, tre
    // found the smallest node in preorder which is after x.\r
    // if ctx is the root node, just return what we found.\r
 \r
-   if (root == Root()) return min;\r
-   // else check whether if is in below the ctx node\r
-\r
-   NULLT_IF (min == NULLT || min >= find_close(Par, root));\r
+   NULLT_IF (min == NULLT || min >= closing);\r
    \r
    return min;\r
    \r
@@ -660,7 +759,7 @@ treeNode XMLTree::TaggedAncestor(treeNode x, TagType tag)
     \r
     treeNode s = parent(Par, x), r = Root();\r
     while (s != r) {\r
-       if (get_field(tags_fix,tags_blen,node2tagpos(s)) /*Tags->access(node2tagpos(s))*/ == tag) return s;\r
+      if (Tag(s) == tag) return s;\r
        s = parent(Par, s);\r
     }\r
     return NULLT;\r
@@ -677,12 +776,19 @@ DocID XMLTree::MyText(treeNode x)
   // seems faster than testing EBVector->access(x);\r
 \r
   if (tag == PCDATA_TAG_ID || tag == ATTRIBUTE_DATA_TAG_ID)\r
+    //if (EBVector->access(x))\r
     return (DocID) (EBVector->rank1(x)-1); //-1 because document ids start from 0\r
   else \r
     return (DocID) NULLT;\r
   \r
 }\r
-\r
+// MyText(x): returns the document identifier of the text below node x, \r
+// or NULLT if x is not a leaf node or the text is empty. Assumes Doc \r
+// ids start from 0.\r
+DocID XMLTree::MyTextUnsafe(treeNode x) \r
+{\r
+  return (DocID) (EBVector->rank1(x)-1); //-1 because document ids start from 0\r
+}\r
 // TextXMLId(d): returns the preorder of document with identifier d in the tree consisting of\r
 // all tree nodes and all text nodes. Assumes that the tree root has preorder 1.\r
 int XMLTree::TextXMLId(DocID d) \r
@@ -729,7 +835,7 @@ unsigned char *XMLTree::GetTagName(TagType tagid)
     unsigned char *s;\r
     if ( tagid < 0 || tagid >= TagName->size())\r
       return (unsigned char *) "<INVALID TAG>";\r
-    strcpy((char *)s, TagName->at(tagid).c_str());\r
+    strcpy((char *)s, (*TagName)[tagid].c_str());\r
     \r
     return (s == NULL ? (unsigned char*) "<INVALID TAG>" : s);\r
  }\r
@@ -742,7 +848,7 @@ const unsigned char *XMLTree::GetTagNameByRef(TagType tagid)
    if ( tagid < 0 || tagid >= TagName->size())\r
      return (unsigned char *) "<INVALID TAG>";\r
    \r
-   return (const unsigned char *) TagName->at(tagid).c_str();\r
+   return (const unsigned char *) (*TagName)[tagid].c_str();\r
    \r
  }\r
 \r
@@ -753,11 +859,130 @@ TagType XMLTree::RegisterTag(unsigned char *tagname)
     TagType id = XMLTree::GetTagId(tagname);\r
     if (id == NULLT) {\r
       string s = (char *) tagname;      \r
-      REGISTER_TAG(TagName,tIdMap,s);\r
-      \r
+      REGISTER_TAG(TagName,tIdMap,s);      \r
     };\r
     \r
     return id;\r
  }\r
 \r
 \r
+treeNode XMLTree::Closing(treeNode x) {\r
+  return fast_find_close(Par,x); \r
+}\r
+bool XMLTree::IsOpen(treeNode x) { return fast_inspect(Par,x); }\r
+\r
+//WARNING this uses directly the underlying implementation for plain text\r
+\r
+\r
+void XMLTree::Print(int fd,treeNode x, bool no_text){\r
+  \r
+  int newfd = dup(fd);\r
+  stream = fdopen(newfd,"wa");\r
+  if (stream == 0){\r
+    perror(NULL);\r
+    return;\r
+  };\r
+\r
+  if (buffer == 0)\r
+    buffer = new string();\r
+\r
+  FILE* fp = stream;\r
+  treeNode fin = fast_find_close(Par,x);\r
+  treeNode n = x;\r
+  TagType tag = Tag(n);\r
+  uchar * tagstr;\r
+  range r = DocIds(x);\r
+  treeNode first_idx;\r
+  treeNode first_text = (tag == PCDATA_TAG_ID ?  x : ParentNode(r.min-1));\r
+  treeNode first_att =  NULLT;\r
+  \r
+  if (first_att  == NULLT)\r
+  first_idx = first_text;\r
+  else if (first_text == NULLT)\r
+  first_idx = first_att;\r
+  else\r
+   first_idx = min(first_att,first_text);\r
+   \r
+   uchar * current_text=NULL;\r
+   if (first_idx != NULLT)\r
+   current_text = GetText(MyText(first_idx));\r
+   size_t read = 0;\r
+   std::vector<uchar*> st;\r
+ while (n <= fin){\r
+   if (fast_inspect(Par,n)){\r
+     if (tag == PCDATA_TAG_ID  ) {       \r
+\r
+       if (no_text)\r
+        myfputs("<$/>",fp);\r
+       else{\r
+        read = myfprintf((const char*) current_text, fp);\r
+        current_text += (read + 1);\r
+       };\r
+       n+=2; // skip closing $\r
+       tag = Tag(n);\r
+      \r
+     }\r
+     else {\r
+       myfputc('<',fp);\r
+       tagstr = (uchar*) GetTagNameByRef(tag);\r
+       myfputs((const char*) tagstr ,fp);\r
+       n++;\r
+       if (fast_inspect(Par,n)) {\r
+        st.push_back(tagstr);\r
+        tag = Tag(n);\r
+        if (tag == ATTRIBUTE_TAG_ID){\r
+          n++;\r
+          if (no_text) myfputs("><@@>",fp);\r
+          while (fast_inspect(Par,n)){\r
+            if (no_text) {\r
+              myfputc('<',fp);\r
+              myfputs((const char*) &(GetTagNameByRef(Tag(n))[3]),fp);\r
+              myfputc('>',fp);\r
+              myfputs("<$@/></",fp);\r
+              myfputs((const char*) &(GetTagNameByRef(Tag(n))[3]),fp);\r
+              myfputc('>',fp);\r
+              n+= 4;\r
+            }\r
+            else {\r
+              myfputc(' ',fp);\r
+              myfputs((const char*) &(GetTagNameByRef(Tag(n))[3]),fp);\r
+              n++;\r
+              myfputs("=\"",fp);\r
+              read = myfprintf((const char*) current_text,fp);\r
+              current_text += (read + 1);\r
+              myfputc('"',fp);\r
+              n+=3;\r
+            }\r
+          };\r
+          if (no_text) \r
+            myfputs("</@@>",fp);\r
+          else myfputc('>',fp);\r
+          n++;\r
+          tag=Tag(n);\r
+        }\r
+        else {\r
+          myfputc('>',fp);\r
+        };\r
+       }\r
+       else {// <foo /> tag\r
+        myfputs("/>",fp);\r
+        n++;\r
+        tag=Tag(n);     \r
+       };     \r
+     };\r
+   }\r
+   else\r
+     do {\r
+       myfputs("</",fp);\r
+       myfputs((const char*)st.back(),fp);\r
+       myfputc('>', fp);\r
+       st.pop_back();\r
+       n++;\r
+     }while (!fast_inspect(Par,n) && !st.empty());\r
+   tag=Tag(n);\r
+ };\r
+ myfputc('\n',fp);\r
+ mybufferflush(fp);\r
+ //fflush(fp);\r
+ fclose(fp);\r
+}\r