2a1da8446a816ab17117963aea34bc785b4945ca
[SXSI/XMLTree.git] / XMLTree.cpp
1 #include "XMLTree.h"\r
2 #include <cstring>\r
3 \r
4 // functions to convert tag positions to the corresponding tree node and viceversa. \r
5 // These are implemented in order to be able to change the tree and Tags representations, \r
6 // without affecting the code so much.\r
7 // Current implementation corresponds to balanced-parentheses representation for\r
8 // the tree, and storing 2 tags per tree node (opening and closing tags).\r
9 \r
10 // tag position -> tree node\r
11 inline treeNode tagpos2node(int t) {\r
12    return (treeNode)t;\r
13 }\r
14 \r
15 // tree node -> tag position\r
16 inline int node2tagpos(treeNode x) {\r
17    return (int)x;\r
18 }\r
19 \r
20 \r
21 //KIM OJO to prevent suprious "unused result" warnings\r
22 \r
23 inline void ufread(void *ptr, size_t size, size_t nmemb, FILE *stream){\r
24   size_t res;\r
25   res = fread(ptr,size,nmemb,stream);\r
26   if (res < nmemb)\r
27     throw "ufread I/O error";\r
28 \r
29   return;\r
30 }\r
31 \r
32 inline void ufwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream){\r
33   size_t res;\r
34   res = fwrite(ptr,size,nmemb,stream);\r
35   if (res < nmemb)\r
36     throw "ufwrite I/O error";\r
37   return;\r
38 }\r
39 \r
40 // OJO to fail cleanly while doing a realloc\r
41 // if we can't realloc we are pretty much screwed anyway but\r
42 // it makes the code clearer to not have a bunch of if (!ptr) { printf("..."); exit(1); };\r
43 inline void * urealloc(void *ptr, size_t size){\r
44 \r
45   void * dest = realloc(ptr,size);\r
46   //don't fail if we requested size 0\r
47   if (dest == NULL && size > 0 )\r
48     throw std::bad_alloc();\r
49   return dest;\r
50 \r
51 }\r
52 \r
53 inline void * ucalloc(size_t nmemb, size_t size){\r
54 \r
55   void * dest = calloc(nmemb,size);\r
56   //don't fail if we requested size 0\r
57   if (dest == NULL && nmemb > 0 && size > 0 )\r
58     throw std::bad_alloc();\r
59   return dest;\r
60 \r
61 }\r
62 \r
63 inline void * umalloc(size_t size){\r
64   void * dest = malloc(size);\r
65   if (dest == NULL && size > 0)\r
66     throw std::bad_alloc();\r
67   return dest;\r
68 }\r
69 \r
70 void XMLTree::print_stats() {\r
71         uint total_space = Tags->size()+sizeof(static_sequence*);\r
72         total_space += sizeof(uint*)+sizeof(uint)*(2+uint_len(tags_blen,tags_len));\r
73         cout << "Space usage for XMLTree:" << endl\r
74                 << " - tags static_sequence: " << Tags->size()+sizeof(static_sequence*) << endl\r
75                 << " - tags access array:    " << sizeof(uint*)+sizeof(uint)*(2+uint_len(tags_blen,tags_len)) << endl\r
76                 << " ... add Diego structures ... " << endl\r
77                 << " *total* " << total_space << endl;\r
78 }\r
79 \r
80 // Save: saves XML tree data structure to file. \r
81 void XMLTree::Save(unsigned char *filename) \r
82  {\r
83 \r
84     FILE *fp;\r
85     char filenameaux[1024];\r
86     int i;\r
87    \r
88     sprintf(filenameaux, "%s.srx", filename);\r
89     fp = fopen(filenameaux, "w");\r
90     if (fp == NULL) {\r
91        printf("Error: cannot create file %s to store the tree structure of XML collection\n", filenameaux);\r
92        exit(1);\r
93     } \r
94     \r
95     // first stores the tree topology\r
96     saveTree(Par, fp);\r
97  \r
98     // stores the table with tag names\r
99     ufwrite(&ntagnames, sizeof(int), 1, fp);\r
100     for (i=0; i<ntagnames;i++)\r
101       fprintf(fp, "%s\n",TagName[i]);\r
102     \r
103     \r
104     // stores the flags\r
105     ufwrite(&indexing_empty_texts, sizeof(bool), 1, fp);\r
106     ufwrite(&initialized, sizeof(bool), 1, fp);\r
107     ufwrite(&finished, sizeof(bool), 1, fp);\r
108     ufwrite(&disable_tc, sizeof(bool),1,fp);\r
109     \r
110     if (!indexing_empty_texts) EBVector->save(fp);\r
111     \r
112     // stores the tags\r
113     Tags->save(fp);\r
114                 ufwrite(&tags_blen,sizeof(uint),1,fp);\r
115                 ufwrite(&tags_len,sizeof(uint),1,fp);\r
116                 ufwrite(tags_fix,sizeof(uint),uint_len(tags_blen,tags_len),fp);\r
117 \r
118     // stores the texts   \r
119     if (!disable_tc) {\r
120       Text->Save(fp);\r
121       int st = CachedText.size();\r
122       ufwrite(&st, sizeof(int),1,fp);\r
123       for (int i = 0; i< CachedText.size(); i++){\r
124         st = CachedText.at(i).size();\r
125         ufwrite(&st, sizeof(int),1,fp);\r
126         ufwrite(CachedText.at(i).c_str(),sizeof(char),1+CachedText.at(i).size(),fp);\r
127       };\r
128     };\r
129     fclose(fp);\r
130 \r
131  }\r
132 \r
133 \r
134 // Load: loads XML tree data structure from file. Returns\r
135 // a pointer to the loaded data structure\r
136 XMLTree *XMLTree::Load(unsigned char *filename, int sample_rate_text) \r
137  {\r
138 \r
139     FILE *fp;\r
140     char buffer[1024];\r
141     XMLTree *XML_Tree;\r
142     int i;\r
143     size_t s_tree = 0;\r
144     long s_text = 0;\r
145     size_t s_tags = 0;\r
146 \r
147     // first load the tree topology\r
148     sprintf(buffer, "%s.srx", filename);\r
149     fp = fopen(buffer, "r");\r
150     if (fp == NULL) {\r
151        printf("Error: cannot open file %s to load the tree structure of XML collection\n", buffer);\r
152        exit(1);\r
153     } \r
154 \r
155     XML_Tree = new XMLTree();\r
156 \r
157     XML_Tree->Par = (bp *)umalloc(sizeof(bp));\r
158 \r
159     loadTree(XML_Tree->Par, fp); \r
160 \r
161     s_tree += sizeof(bp);\r
162 \r
163     // stores the table with tag names\r
164     ufread(&XML_Tree->ntagnames, sizeof(int), 1, fp);\r
165     \r
166     s_tree += sizeof(int);\r
167 \r
168     XML_Tree->TagName = (unsigned char **)umalloc(XML_Tree->ntagnames*sizeof(unsigned char *));\r
169     \r
170     s_tags += sizeof(unsigned char*)*XML_Tree->ntagnames;\r
171 \r
172 \r
173     for (i=0; i<XML_Tree->ntagnames;i++) {\r
174       \r
175       // OJO Kim is it needed ?\r
176       int k = feof(fp);\r
177 \r
178       \r
179        // fscanf chokes on "\n" which is the case for the root element\r
180        char * r = fgets(buffer,1023,fp);\r
181        //       int r = fscanf(fp, "%s\n",buffer);\r
182        if (r==NULL)\r
183          throw "Cannot read tag list";\r
184 \r
185        // strlen is actually the right size, since there is a trailing '\n'\r
186        int len = strlen((const char*)buffer);\r
187        XML_Tree->TagName[i] = (unsigned char *)ucalloc(len,sizeof(char));\r
188        strncpy((char *)XML_Tree->TagName[i], (const char *)buffer,len - 1);\r
189        s_tags+= len*sizeof(char);\r
190     }\r
191         \r
192     // loads the flags\r
193 \r
194     ufread(&(XML_Tree->indexing_empty_texts), sizeof(bool), 1, fp);\r
195     ufread(&(XML_Tree->initialized), sizeof(bool), 1, fp);\r
196     ufread(&(XML_Tree->finished), sizeof(bool), 1, fp);\r
197     ufread(&(XML_Tree->disable_tc), sizeof(bool), 1, fp);\r
198     \r
199     s_tree+=sizeof(bool)*4;\r
200 \r
201     if (!(XML_Tree->indexing_empty_texts)) XML_Tree->EBVector = static_bitsequence_rrr02::load(fp);\r
202     \r
203     s_tree+= XML_Tree->EBVector->size();\r
204     \r
205     // loads the tags\r
206     XML_Tree->Tags = static_sequence::load(fp);\r
207                 ufread(&XML_Tree->tags_blen,sizeof(uint),1,fp);\r
208                 ufread(&XML_Tree->tags_len,sizeof(uint),1,fp);\r
209                 XML_Tree->tags_fix = new uint[uint_len(XML_Tree->tags_blen,XML_Tree->tags_len)];\r
210                 ufread(XML_Tree->tags_fix,sizeof(uint),uint_len(XML_Tree->tags_blen,XML_Tree->tags_len),fp);\r
211                 s_tree+=2*sizeof(uint)+sizeof(uint)*uint_len(XML_Tree->tags_blen,XML_Tree->tags_len);\r
212     s_tree+= XML_Tree->Tags->size();\r
213 \r
214                 /// FIXME:UGLY tests!\r
215                 uint * seq = new uint[XML_Tree->tags_len];\r
216                 for(uint i=0;i<XML_Tree->tags_len;i++)\r
217                         seq[i] = get_field(XML_Tree->tags_fix,XML_Tree->tags_blen,i);\r
218                 cout << "Tags test: " << XML_Tree->Tags->test(seq,XML_Tree->tags_len) << endl;\r
219                 delete [] seq;\r
220                 /// End ugly tests\r
221 \r
222     s_text = ftell(fp);\r
223 \r
224     // loads the texts\r
225     if (!XML_Tree->disable_tc){\r
226       XML_Tree->Text = TextCollection::Load(fp,sample_rate_text);\r
227       int sst;\r
228       int st;\r
229       ufread(&sst, sizeof(int),1,fp);\r
230       for (int i=0;i<sst;i++){\r
231         ufread(&st, sizeof(int),1,fp);\r
232         char* str = (char*) malloc(sizeof(char)*st+1);\r
233         ufread(str,sizeof(char),st+1,fp);\r
234         string cppstr = str;\r
235         XML_Tree->CachedText.push_back(cppstr);\r
236         free(str);\r
237       };\r
238 \r
239     }\r
240     else {\r
241       XML_Tree->Text = NULL;\r
242     }\r
243     s_text = ftell(fp) - s_text;\r
244 \r
245     \r
246 \r
247 \r
248     fclose(fp);\r
249 \r
250     /*std::cerr << "Tree part is " << s_tree/1024 << " Kbytes,\n"\r
251               << "with node->tagid part " << XML_Tree->Tags->size()/1024+(uint_len(XML_Tree->tags_blen,XML_Tree->tags_len)*sizeof(uint))/1024  << "Kbytes \n"\r
252               << "size of Tag part : " << XML_Tree->Tags->length () << " elements\n"\r
253               << "sizof(unsigned int)* " <<  XML_Tree->Tags->length () << " = " << \r
254       sizeof(unsigned int) * XML_Tree->Tags->length () / 1024 << " Kbytes\n"\r
255               << "Tag part is " << s_tags/1024 << " Kbytes,\n"\r
256               << "Text collection is " << s_text/1024 << " Kbytes \n";*/\r
257                 XML_Tree->print_stats();\r
258     return XML_Tree;\r
259  }\r
260 \r
261 \r
262 // ~XMLTree: frees memory of XML tree.\r
263 XMLTree::~XMLTree() \r
264  { \r
265     int i;\r
266 \r
267     destroyTree(Par);\r
268     free(Par); // frees the memory of struct Par\r
269    \r
270     for (i=0; i<ntagnames;i++) \r
271        free(TagName[i]);\r
272     \r
273     free(TagName);\r
274 \r
275     if (!indexing_empty_texts) {\r
276        //EBVector->~static_bitsequence_rrr02();\r
277        delete EBVector;\r
278        EBVector = NULL;\r
279     }\r
280 \r
281     //Tags->~static_sequence_wvtree();\r
282     delete Tags;\r
283     Tags = NULL;\r
284 \r
285     //Text->~TextCollection();\r
286     delete TextBuilder; \r
287     TextBuilder = NULL;\r
288     delete Text; \r
289     Text = NULL;\r
290 \r
291     initialized = false;\r
292     finished = false;\r
293  }\r
294 \r
295 // root(): returns the tree root.\r
296 treeNode XMLTree::Root() \r
297  {\r
298     if (!finished) {\r
299        fprintf(stderr, "Root() : Error: data structure has not been constructed properly\n");\r
300        exit(1);\r
301     }\r
302     return root_node(Par);\r
303  }\r
304 \r
305 // SubtreeSize(x): the number of nodes (and attributes) in the subtree of node x.\r
306 int XMLTree::SubtreeSize(treeNode x) \r
307  {\r
308     if (!finished) {\r
309        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
310        exit(1);\r
311     }\r
312     return subtree_size(Par, x);\r
313  }\r
314 \r
315 // SubtreeTags(x,tag): the number of occurrences of tag within the subtree of node x.\r
316 int XMLTree::SubtreeTags(treeNode x, TagType tag) \r
317  {\r
318     if (!finished) {\r
319        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
320        exit(1);\r
321     }\r
322     if (x == Root())\r
323       x = first_child(Par,x);\r
324     \r
325 \r
326     int s = x + 2*subtree_size(Par, x) - 1;\r
327  \r
328     return Tags->rank(tag, s) - Tags->rank(tag, node2tagpos(x)-1);\r
329  }\r
330 \r
331 // IsLeaf(x): returns whether node x is leaf or not. In the succinct representation\r
332 // this is just a bit inspection.\r
333 bool XMLTree::IsLeaf(treeNode x) \r
334  {\r
335     return isleaf(Par, x);\r
336  } \r
337 \r
338 // IsAncestor(x,y): returns whether node x is ancestor of node y.\r
339 bool XMLTree::IsAncestor(treeNode x, treeNode y) \r
340  {\r
341     if (!finished) {\r
342        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
343        exit(1);\r
344     }\r
345 \r
346     return is_ancestor(Par, x, y);\r
347  }\r
348 \r
349 // IsChild(x,y): returns whether node x is parent of node y.\r
350 bool XMLTree::IsChild(treeNode x, treeNode y) \r
351  {\r
352     if (!finished) {\r
353        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
354        exit(1);\r
355     }\r
356 \r
357     if (!is_ancestor(Par, x, y)) return false;\r
358     return depth(Par, x) == (depth(Par, y) + 1);\r
359  }\r
360 bool XMLTree::IsFirstChild(treeNode x){\r
361   return ((x != NULLT)&&(x==Root() || prev_sibling(Par,x) == NULLT));\r
362 }\r
363 // NumChildren(x): number of children of node x. Constant time with the data structure\r
364 // of Sadakane.\r
365 int XMLTree::NumChildren(treeNode x) \r
366  {\r
367     if (!finished) {\r
368        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
369        exit(1);\r
370     }\r
371 \r
372     return degree(Par, x);\r
373  }\r
374 \r
375 // ChildNumber(x): returns i if node x is the i-th children of its parent.\r
376 int XMLTree::ChildNumber(treeNode x) \r
377  {\r
378     if (!finished) {\r
379        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
380        exit(1);\r
381     }\r
382 \r
383     return child_rank(Par, x);\r
384  }\r
385 \r
386 // Depth(x): depth of node x, a simple binary rank on the parentheses sequence.\r
387 int XMLTree::Depth(treeNode x) \r
388  {\r
389     if (!finished) {\r
390        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
391        exit(1);\r
392     }\r
393 \r
394     return depth(Par, x);\r
395  }\r
396 \r
397 // Preorder(x): returns the preorder number of node x, just counting the tree\r
398 // nodes (i.e., tags, it disregards the texts in the tree).\r
399 int XMLTree::Preorder(treeNode x) \r
400  {\r
401     if (!finished) {\r
402        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
403        exit(1);\r
404     }\r
405 \r
406     return preorder_rank(Par, x);\r
407  }\r
408 \r
409 // Postorder(x): returns the postorder number of node x, just counting the tree\r
410 // nodes (i.e., tags, it disregards the texts in the tree).\r
411 int XMLTree::Postorder(treeNode x) \r
412  {\r
413     if (!finished) {\r
414        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
415        exit(1);\r
416     }\r
417     return postorder_rank(Par, x);\r
418  }\r
419 \r
420 // Tag(x): returns the tag identifier of node x.\r
421 TagType XMLTree::Tag(treeNode x) \r
422  {\r
423     if (!finished) {\r
424        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
425        exit(1);\r
426     }\r
427     \r
428     return get_field(tags_fix,tags_blen,node2tagpos(x)); //Tags->access(node2tagpos(x));\r
429  }\r
430 \r
431 // DocIds(x): returns the range of text identifiers that descend from node x.\r
432 // returns {NULLT, NULLT} when there are no texts descending from x.\r
433 range XMLTree::DocIds(treeNode x) \r
434  {\r
435     if (!finished) {\r
436        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
437        exit(1);\r
438     }\r
439 \r
440     range r;\r
441     if (x == NULLT)\r
442       {\r
443         r.min = NULLT;\r
444         r.max = NULLT;\r
445         return r;\r
446       };\r
447         \r
448       \r
449     if (indexing_empty_texts) { // faster, no rank needed\r
450        r.min = x;\r
451        r.max = x+2*subtree_size(Par, x)-2;\r
452     }\r
453     else { // we are not indexing empty texts, we need rank\r
454        int min = EBVector->rank1(x-1);                          \r
455        int max = EBVector->rank1(x+2*subtree_size(Par, x)-2); \r
456        if (min==max) { // range is empty, no texts within the subtree of x\r
457           r.min = NULLT;\r
458           r.max = NULLT;\r
459        }\r
460        else { // the range is non-empty, there are texts within the subtree of x\r
461           r.min = min+1;\r
462           r.max = max;\r
463        }\r
464     }\r
465     return r;\r
466  }\r
467 \r
468 // Parent(x): returns the parent node of node x.\r
469 treeNode XMLTree::Parent(treeNode x) \r
470  {\r
471     if (!finished) {\r
472        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
473        exit(1);\r
474     }\r
475     if (x == Root())\r
476       return NULLT;\r
477     else\r
478       return parent(Par, x);\r
479  }\r
480 \r
481 // Child(x,i): returns the i-th child of node x, assuming it exists.\r
482 treeNode XMLTree::Child(treeNode x, int i) \r
483 {\r
484     if (!finished) {\r
485        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
486        exit(1);\r
487     }\r
488 \r
489     if (i <= OPTD) return naive_child(Par, x, i);\r
490     else return child(Par, x, i);\r
491  }\r
492 \r
493 // FirstChild(x): returns the first child of node x, assuming it exists. Very fast in BP.\r
494 treeNode XMLTree::FirstChild(treeNode x) \r
495  {\r
496     if (!finished) {\r
497        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
498        exit(1);\r
499     }\r
500 \r
501     return first_child(Par, x);\r
502  }\r
503 \r
504 treeNode XMLTree::LastChild(treeNode x) \r
505 {\r
506   if (x == Root() || isleaf(Par,x) || x == NULLT)\r
507     return x;\r
508   else\r
509   return find_open(Par,find_close(Par,parent(Par,x))-1);\r
510 }\r
511 \r
512 // NextSibling(x): returns the next sibling of node x, assuming it exists.\r
513 treeNode XMLTree::NextSibling(treeNode x) \r
514  {\r
515     if (!finished) {\r
516        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
517        exit(1);\r
518     }\r
519     if (x == Root() || x==NULLT)\r
520       return NULLT;\r
521     \r
522     return next_sibling(Par, x);\r
523  }\r
524 \r
525 // PrevSibling(x): returns the previous sibling of node x, assuming it exists.\r
526 treeNode XMLTree::PrevSibling(treeNode x) \r
527  {\r
528     if (!finished) {\r
529        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
530        exit(1);\r
531     }\r
532 \r
533     return prev_sibling(Par, x);\r
534  }\r
535 \r
536 // TaggedChild(x,i,tag): returns the i-th child of node x tagged tag, or NULLT if there is none.\r
537 // Because of the balanced-parentheses representation of the tree, this operation is not supported\r
538 // efficiently, just iterating among the children of node x until finding the desired child.\r
539 treeNode XMLTree::TaggedChild(treeNode x, int i, TagType tag) \r
540  {\r
541     if (!finished) {\r
542        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
543        exit(1);\r
544     }\r
545 \r
546     treeNode child;\r
547    \r
548     child = first_child(Par, x); // starts at first child of node x\r
549     if (child==(treeNode)-1) return NULLT; // node x is a leaf, there is no such child\r
550     while (child!=(treeNode)-1) {\r
551        if (get_field(tags_fix,tags_blen,node2tagpos(child)) /*Tags->access(node2tagpos(child))*/ == tag) { // current child is labeled with tag of interest\r
552           i--;\r
553           if (i==0) return child; // we have seen i children of x tagged tag, this is the one we are looking for\r
554        }\r
555        child = next_sibling(Par, x); // OK, let's try with the next child\r
556     }\r
557     return NULLT; // no such child was found  \r
558  }\r
559 \r
560 // TaggedDesc(x,tag): returns the first node tagged tag with larger preorder than x and within\r
561 // the subtree of x. Returns NULLT if there is none.\r
562 treeNode XMLTree::TaggedDesc(treeNode x, TagType tag) \r
563  {\r
564     if (!finished) {\r
565        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
566        exit(1);\r
567     }\r
568 \r
569     //int r, s;\r
570     treeNode y;\r
571     if (isleaf(Par,x))\r
572       return NULLT;\r
573 \r
574                 int s = (int) Tags->select_next(tag,node2tagpos(x));\r
575     /*r = (int) Tags->rank(tag, node2tagpos(x));\r
576     s = (int) Tags->select(tag, r+1);*/\r
577     if (s == -1) return NULLT; // there is no such node\r
578     y = tagpos2node(s); // transforms the tag position into a node position\r
579     if (!is_ancestor(Par, x, y)) return NULLT; // the next node tagged tag (in preorder) is not within the subtree of x.\r
580     else return y;\r
581  }\r
582 \r
583 treeNode XMLTree::TaggedDescOnly(treeNode x,TagType *desctags, unsigned int dtlen)\r
584 {\r
585 \r
586   treeNode res,y;\r
587   if (isleaf(Par,x))\r
588     return NULLT;\r
589   \r
590   res=NULLT;\r
591   for (unsigned int i = 0; i < dtlen; i ++ )\r
592     {\r
593       y = TaggedDesc(x,desctags[i]);\r
594       res = (res == NULLT) || (( res != NULLT) && (y =! NULLT) && y < res) ? y : res;\r
595       \r
596     };\r
597   \r
598   return res;\r
599   \r
600 }\r
601 \r
602 \r
603 treeNode XMLTree::TaggedBelow(treeNode x, TagType *childtags, unsigned int ctlen,\r
604                               TagType *desctags, unsigned int dtlen)\r
605 {\r
606   treeNode fs,y,res;\r
607   TagType tag;\r
608 \r
609   if (isleaf(Par,x))\r
610     return NULLT;\r
611   \r
612   res = NULLT;\r
613   fs = first_child(Par,x);\r
614   while (fs != NULLT) {\r
615     tag = get_field(tags_fix,tags_blen,node2tagpos(fs));\r
616         \r
617     /* Check for first_child */\r
618     for (unsigned int i = 0; i < ctlen; i++) {\r
619       if (childtags[i] == tag)\r
620         return fs;\r
621     };\r
622     \r
623     for (unsigned int i = 0; i < dtlen; i++)\r
624       if (desctags[i] == tag)\r
625         return fs;  \r
626     \r
627     /* check in the descendants */\r
628     res = NULLT;\r
629     for (unsigned int i = 0; i < dtlen; i ++ ){\r
630       /* maybe inline by hand */\r
631       y = TaggedDesc(fs,desctags[i]);\r
632       res = (res==NULLT || (y != NULLT) &&(y < res)) ? y : res;   \r
633     };\r
634     if (res != NULLT)\r
635       return res;\r
636     \r
637     fs = next_sibling(Par,fs);\r
638   };\r
639   return res;\r
640     \r
641 }\r
642 treeNode XMLTree::TaggedFollOnly(treeNode x,TagType *folltags, unsigned int ftlen,treeNode root)\r
643 {\r
644 \r
645   treeNode res,y,lim;\r
646   lim = find_close(Par,root);   \r
647   res=NULLT;\r
648   for (unsigned int i = 0; i < ftlen; i ++ )\r
649     {\r
650       y = TaggedFoll(x,folltags[i]);\r
651       res = (res == NULLT) || (( res != NULLT) && (y =! NULLT) && y < res) ? y : res;\r
652       \r
653     };\r
654   \r
655   return res < lim ? res : NULLT;\r
656   \r
657 }\r
658 \r
659 treeNode XMLTree::TaggedDescOrFollOnly(treeNode x,TagType *folltags, unsigned int ftlen,treeNode root)\r
660 {\r
661 \r
662   treeNode res,y,lim;\r
663   //int r,s;\r
664   lim = find_close(Par,root);   \r
665   res=NULLT;\r
666   for (unsigned int i = 0; i < ftlen; i ++ )\r
667     {\r
668 \r
669                         int s = (int) Tags->select_next(folltags[i],node2tagpos(x));\r
670       /*r = (int) Tags->rank(folltags[i], node2tagpos(x));\r
671       s = (int) Tags->select(folltags[i], r+1);*/\r
672       if (s == -1) \r
673         y = NULLT; // there is no such node\r
674       else {\r
675         y = tagpos2node(s); \r
676         if (y >= lim)\r
677           y = NULLT;\r
678       };\r
679       res = (res == NULLT) || (( res != NULLT) && (y =! NULLT) && y < res) ? y : res;\r
680       \r
681     };\r
682   \r
683   return res < lim ? res : NULLT;\r
684   \r
685 }\r
686 \r
687 \r
688 // TaggedNext(x,tag): returns the first node tagged tag with larger preorder than x \r
689 // Returns NULLT if there is none.\r
690 treeNode XMLTree::TaggedNext(treeNode x, TagType *childtags, unsigned int ctlen,\r
691                              TagType *folltags, unsigned int flen,treeNode root)\r
692  {\r
693    treeNode y,old_y,lim,res;\r
694    TagType tag;\r
695    if (x == NULLT || x == Root())\r
696      return NULLT;\r
697 \r
698 \r
699    lim = find_close(Par,root);   \r
700 \r
701    res = NULLT;\r
702   \r
703    y = next_sibling(Par,x);\r
704    while (y != NULLT) {\r
705      tag = get_field(tags_fix,tags_blen,node2tagpos(y));\r
706      for(unsigned int i = 0; i < ctlen;i++)\r
707        if (childtags[i] == tag)\r
708          return y;\r
709      \r
710      for(unsigned int i = 0; i < flen;i++)\r
711        if (folltags[i] == tag)\r
712          return y;\r
713 \r
714      res = TaggedBelow(y,NULL,0,folltags,flen);\r
715      if (res != NULLT)\r
716        return res;\r
717      \r
718      y = next_sibling(Par,y);\r
719    };\r
720    //Found nothing in the following sibling of x.\r
721    res = NULLT;\r
722    for(unsigned int i = 0; i < flen;i++){\r
723      y = TaggedFoll(x,folltags[i]);\r
724      res = (y!= x && (res == NULLT || (y != NULLT && y < res)))? y : res;\r
725    };\r
726   \r
727    return res < lim ? res : NULLT;\r
728    \r
729  }\r
730 \r
731 \r
732 // TaggedPrec(x,tag): returns the first node tagged tag with smaller preorder than x and not an\r
733 // ancestor of x. Returns NULLT if there is none.\r
734 treeNode XMLTree::TaggedPrec(treeNode x, TagType tag) \r
735  {\r
736     if (!finished) {\r
737        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
738        exit(1);\r
739     }\r
740     \r
741     int r, s;\r
742     treeNode node_s, root;\r
743     r = (int)Tags->rank(tag, node2tagpos(x)-1);\r
744     if (r==0) return NULLT; // there is no such node.\r
745     s = (int)Tags->select(tag, r);\r
746     root = root_node(Par);\r
747     node_s = tagpos2node(s);\r
748     while (is_ancestor(Par, node_s, x) && (node_s!=root)) { // the one that we found is an ancestor of x\r
749        r--;\r
750        if (r==0) return NULLT; // there is no such node\r
751        s = (int)Tags->select(tag, r);  // we should use select_prev instead when provided\r
752        node_s = tagpos2node(s);\r
753     }\r
754     return NULLT; // there is no such node \r
755  }\r
756 \r
757 \r
758 // TaggedFoll(x,tag): returns the first node tagged tag with larger preorder than x and not in\r
759 // the subtree of x. Returns NULLT if there is none.\r
760 treeNode XMLTree::TaggedFoll(treeNode x, TagType tag)\r
761  {\r
762     if (!finished) {\r
763        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
764        exit(1);\r
765     }\r
766 \r
767     //int r, s;\r
768     if (x ==NULLT || x == Root())\r
769        return NULLT;\r
770      \r
771                 int s = (int) Tags->select_next(tag,find_close(Par,x));\r
772     /*r = (int) Tags->rank(tag, find_close(Par, x));\r
773     s = (int) Tags->select(tag, r+1);  // select returns -1 in case that there is no r+1-th tag. */\r
774     if (s==-1) return NULLT;\r
775     else return tagpos2node(s);\r
776  } \r
777 \r
778 // TaggedFoll(x,tag): returns the first node tagged tag with larger preorder than x and not in\r
779 // the subtree of x. Returns NULLT if there is none.\r
780 treeNode XMLTree::TaggedFollBelow(treeNode x, TagType tag, treeNode root)\r
781  {\r
782 \r
783     //int r, s;\r
784     int lim = node2tagpos(find_close(Par,root));\r
785     if (x ==NULLT || x == Root())\r
786        return NULLT;\r
787                    \r
788                 int s = (int) Tags->select_next(tag,find_close(Par,x));\r
789     /*r = (int) Tags->rank(tag,find_close(Par,x));\r
790     s = (int) Tags->select(tag, r+1);  // select returns -1 in case that there is no r+1-th tag.*/\r
791     if (s==-1 || s >= lim) \r
792       return NULLT;\r
793     else \r
794       return tagpos2node(s);\r
795  } \r
796 \r
797 \r
798 // TaggedFollowingSibling(x,tag): returns the first node tagged tag with larger preorder than x and not in\r
799 // the subtree of x. Returns NULLT if there is none.\r
800 treeNode XMLTree::TaggedFollowingSibling(treeNode x, TagType tag) \r
801  {\r
802     if (!finished) {\r
803        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
804        exit(1);\r
805     }\r
806 \r
807     //int r, s;\r
808     treeNode ns = next_sibling(Par,x);\r
809 \r
810     if (x == NULLT || x == Root() || ns == -1)\r
811       return NULLT;\r
812 \r
813                 int s = (int) Tags->select_next(tag,node2tagpos(ns)-1);\r
814     /*r = (int) Tags->rank(tag, node2tagpos(ns)-1);\r
815     s = (int) Tags->select(tag, r+1);  // select returns -1 in case that there is no r+1-th tag.*/\r
816     if (s==-1) return NULLT;\r
817     else return tagpos2node(s);\r
818  }\r
819 \r
820 \r
821 // TaggedAncestor(x, tag): returns the closest ancestor of x tagged tag. Return\r
822 // NULLT is there is none.\r
823 treeNode XMLTree::TaggedAncestor(treeNode x, TagType tag)\r
824  {\r
825     if (!finished) {\r
826        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
827        exit(1);\r
828     }\r
829     \r
830     if (x == NULLT || x == Root())\r
831        return NULLT;\r
832     \r
833     treeNode s = parent(Par, x), r = Root();\r
834     while (s != r) {\r
835        if (get_field(tags_fix,tags_blen,node2tagpos(s)) /*Tags->access(node2tagpos(s))*/ == tag) return s;\r
836        s = parent(Par, s);\r
837     }\r
838     return NULLT;\r
839  }\r
840 \r
841 \r
842 // PrevText(x): returns the document identifier of the text to the left \r
843 // of node x, or NULLT if x is the root node or the text is empty.\r
844 // Assumes Doc ids start from 0.\r
845 DocID XMLTree::PrevText(treeNode x) \r
846  {\r
847     if (!finished) {\r
848        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
849        exit(1);\r
850     }\r
851 \r
852     if (x == Root()) return NULLT;\r
853     if (indexing_empty_texts)  // faster, no rank needed\r
854        return (DocID)x-1;\r
855     else { // we are not indexing empty texts, rank is needed\r
856        if (EBVector->access(x-1) == 0) \r
857           return (DocID)NULLT;  // there is no text to the left of node (text is empty)\r
858        else\r
859           return (DocID)EBVector->rank1(x-1)-1;  //-1 because document ids start from 0\r
860     }\r
861  }\r
862 \r
863 // NextText(x): returns the document identifier of the text to the right\r
864 // of node x, or NULLT if x is the root node. Assumes Doc ids start from 0.\r
865 DocID XMLTree::NextText(treeNode x) \r
866  {\r
867     if (!finished) {\r
868        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
869        exit(1);\r
870     }\r
871 \r
872     if (x == Root()) return NULLT;\r
873     if (indexing_empty_texts)  // faster, no rank needed\r
874        return (DocID)x+2*subtree_size(Par, x)-1;\r
875     else { // we are not indexing empty texts, rank is needed\r
876        int p = x+2*subtree_size(Par, x)-1;\r
877        if (EBVector->access(p) == 0) // there is no text to the right of node\r
878           return (DocID)NULLT;\r
879        else\r
880           return (DocID)EBVector->rank1(p)-1; //-1 because document ids start from 0\r
881     }\r
882  }\r
883 \r
884 // MyText(x): returns the document identifier of the text below node x, \r
885 // or NULLT if x is not a leaf node or the text is empty. Assumes Doc \r
886 // ids start from 0.\r
887 DocID XMLTree::MyText(treeNode x) \r
888  {\r
889     if (!finished) {\r
890        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
891        exit(1);\r
892     }\r
893 \r
894     if (!IsLeaf(x)) return NULLT;\r
895     if (indexing_empty_texts) // faster, no rank needed\r
896        return (DocID)x;\r
897     else { // we are not indexing empty texts, rank is needed\r
898        if (EBVector->access(x) == 0)  // there is no text below node x\r
899           return (DocID)NULLT;\r
900        else\r
901           return (DocID)EBVector->rank1(x)-1; //-1 because document ids start from 0\r
902     } \r
903  }\r
904 \r
905 // TextXMLId(d): returns the preorder of document with identifier d in the tree consisting of\r
906 // all tree nodes and all text nodes. Assumes that the tree root has preorder 1.\r
907 int XMLTree::TextXMLId(DocID d) \r
908  {\r
909     if (!finished) {\r
910        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
911        exit(1);\r
912     }\r
913 \r
914     if (indexing_empty_texts) \r
915        return d + rank_open(Par, d)+1; // +1 because root has preorder 1\r
916     else { // slower, needs rank and select\r
917        int s = EBVector->select1(d+1);\r
918        return rank_open(Par, s) + d + 1; // +1 because root has preorder 1\r
919     }\r
920  }\r
921 \r
922 // NodeXMLId(x): returns the preorder of node x in the tree consisting \r
923 // of all tree nodes and all text nodes. Assumes that the tree root has\r
924 // preorder 0;\r
925 int XMLTree::NodeXMLId(treeNode x) \r
926  {\r
927     if (!finished) {\r
928        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
929        exit(1);\r
930     }\r
931 \r
932     if (indexing_empty_texts)\r
933        return x - 1 + rank_open(Par, x);\r
934     else {\r
935        if (x == Root()) return 1; // root node has preorder 1\r
936        else\r
937           return rank_open(Par, x) + EBVector->rank1(x-1);\r
938     }\r
939  }\r
940 \r
941 // ParentNode(d): returns the parent node of document identifier d.\r
942 treeNode XMLTree::ParentNode(DocID d) \r
943  {\r
944     if (!finished) {\r
945        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
946        exit(1);\r
947     }\r
948     \r
949     if (d == NULLT)\r
950       return NULLT;\r
951     \r
952     int s;\r
953     // OJO : Kim : I added the d+1. before that, else branch was \r
954     // EBVector->select1(d)\r
955     // and gave wrong results (I'm really poking a bear with a stick here).\r
956     if (indexing_empty_texts) s = d;\r
957     else s = EBVector->select1(d+1);\r
958     \r
959     if (inspect(Par,s) == CP) // is a closing parenthesis\r
960        return parent(Par, find_open(Par, s));\r
961     else // is an opening parenthesis\r
962        return (treeNode)s;\r
963      \r
964  }\r
965 treeNode XMLTree::PrevNode(DocID d) \r
966  {\r
967     if (!finished) {\r
968        fprintf(stderr, "Error: data structure has not been constructed properly\n");\r
969        exit(1);\r
970     }\r
971     \r
972     if (d == NULLT)\r
973       return NULLT;\r
974     \r
975     int s;\r
976     \r
977     if (indexing_empty_texts) s = d;\r
978     else s = EBVector->select1(d+1);\r
979     if (s == -1)\r
980       return NULLT;\r
981     \r
982     if (inspect(Par,s) == CP) // is a closing parenthesis\r
983       return find_open(Par, s);\r
984     else // is an opening parenthesis\r
985       return NULLT;\r
986     \r
987  }\r
988 \r
989 \r
990 // OpenDocument(empty_texts): it starts the construction of the data structure for\r
991 // the XML document. Parameter empty_texts indicates whether we index empty texts\r
992 // in document or not. Returns a non-zero value upon success, NULLT in case of error.\r
993 int XMLTree::OpenDocument(bool empty_texts, int sample_rate_text,bool dtc)\r
994  {\r
995     initialized = true;\r
996     finished = false;\r
997     found_attributes = false;\r
998     npar = 0;\r
999     parArraySize = 1;\r
1000     ntagnames = 4;    \r
1001     disable_tc = dtc;\r
1002     \r
1003     indexing_empty_texts = empty_texts;\r
1004     \r
1005     par_aux = (pb *)umalloc(sizeof(pb)*parArraySize);\r
1006     \r
1007     tags_aux = (TagType *) umalloc(sizeof(TagType));\r
1008     \r
1009     TagName = (unsigned char **) umalloc(4*sizeof(unsigned char*));\r
1010 \r
1011     TagName[0] = (unsigned char *) umalloc(4*sizeof(unsigned char));\r
1012 \r
1013     strcpy((char *) TagName[0], "<@>");\r
1014 \r
1015     TagName[1] = (unsigned char *) umalloc(4*sizeof(unsigned char));\r
1016 \r
1017     strcpy((char *) TagName[1], "<$>");\r
1018     \r
1019     //OJO need to put these in the table too.\r
1020     TagName[2] = (unsigned char *) umalloc(5*sizeof(unsigned char));\r
1021 \r
1022     strcpy((char *) TagName[2], "/<@>");\r
1023 \r
1024     TagName[3] = (unsigned char *) umalloc(5*sizeof(unsigned char));\r
1025 \r
1026     strcpy((char *) TagName[3], "/<$>");\r
1027 \r
1028 \r
1029     if (!indexing_empty_texts) \r
1030       empty_texts_aux = (unsigned int *)umalloc(sizeof(unsigned int));\r
1031        \r
1032     if (disable_tc)\r
1033         TextBuilder = 0;\r
1034     else \r
1035         TextBuilder = new TextCollectionBuilder((unsigned)sample_rate_text);\r
1036     Text = 0;\r
1037     \r
1038     return 1;  // indicates success in the initialization of the data structure\r
1039  }\r
1040 \r
1041 // CloseDocument(): it finishes the construction of the data structure for the XML\r
1042 // document. Tree and tags are represented in the final form, dynamic data \r
1043 // structures are made static, and the flag "finished" is set to true. After that, \r
1044 // the data structure can be queried.\r
1045 int XMLTree::CloseDocument()\r
1046  {\r
1047     if (!initialized) {  // data structure has not been initialized properly\r
1048        fprintf(stderr, "Error: data structure has not been initialized properly (by calling method OpenDocument)\n");\r
1049        return NULLT;\r
1050     }\r
1051     \r
1052     // closing parenthesis for the tree root\r
1053     par_aux = (pb *)urealloc(par_aux, sizeof(pb)*(1+npar/(8*sizeof(pb))));\r
1054     \r
1055     // creates the data structure for the tree topology\r
1056     Par = (bp *)umalloc(sizeof(bp));\r
1057     bp_construct(Par, npar, par_aux, OPT_DEGREE|0);    \r
1058     // creates structure for tags\r
1059 \r
1060     // If we found an attribute then "<@>" is present in the tree\r
1061     // if we didn't then it is not. "<$>" is never present in the tree\r
1062                 uint max_tag = 0;\r
1063                 for(uint i=0;i<(uint)npar-1;i++)\r
1064                         max_tag = max(max_tag,tags_aux[i]);\r
1065                 //max_tag++;\r
1066                 //tags_aux = (TagType *) urealloc(tags_aux, sizeof(TagType)*(npar + 1));\r
1067                 //tags_aux[npar++] = max_tag;\r
1068     //int ntagsize = found_attributes ? 2*ntagnames-1 : 2*ntagnames - 2;\r
1069     int ntagsize = 2*ntagnames + 2;\r
1070 \r
1071     //static_bitsequence_builder * bmb = new static_bitsequence_builder_brw32(20);\r
1072     //static_permutation_builder * pmb = new static_permutation_builder_mrrr(PERM_SAMPLE, bmb);\r
1073     //static_sequence_builder * ssb = new static_sequence_builder_gmr_chunk(bmb, pmb);\r
1074                 static_bitsequence_builder * bmb = new static_bitsequence_builder_sdarray();\r
1075                 alphabet_mapper *am = new alphabet_mapper_none();\r
1076                 //wt_coder * wc = new wt_coder_huff((uint*)tags_aux,npar,am);\r
1077                 //Tags = new static_sequence_wvtree((uint*)tags_aux,npar,wc ,bmb, am);\r
1078     //Tags = new static_sequence_gmr((uint *) tags_aux, (uint) npar,ntagsize, bmb, ssb);\r
1079                 Tags = new static_sequence_bs((uint*)tags_aux,npar,am,bmb);\r
1080                 \r
1081                 cout << "Tags test: " << Tags->test((uint*)tags_aux,npar) << endl;\r
1082 \r
1083                 tags_blen = bits(max_tag);\r
1084                 tags_len = (uint)npar;\r
1085                 tags_fix = new uint[uint_len(tags_blen,tags_len)];\r
1086                 for(uint i=0;i<(uint)npar;i++)\r
1087                         set_field(tags_fix,tags_blen,i,tags_aux[i]);\r
1088     \r
1089     delete bmb;\r
1090     //delete pmb;\r
1091     //delete ssb;\r
1092 \r
1093     \r
1094     // makes the text collection static\r
1095     if (!disable_tc)\r
1096     {\r
1097         assert(Text == 0);\r
1098         assert(TextBuilder != 0);\r
1099         Text = TextBuilder->InitTextCollection();\r
1100         delete TextBuilder;\r
1101         TextBuilder = 0;\r
1102     }\r
1103 \r
1104     // creates the data structure marking the non-empty texts (just in the case it is necessary)\r
1105     if (!indexing_empty_texts)  {\r
1106        EBVector = new static_bitsequence_rrr02((uint *)empty_texts_aux,(ulong)npar,(uint)32);\r
1107        free (empty_texts_aux);\r
1108        empty_texts_aux = NULL;\r
1109     }\r
1110    \r
1111     // OJO was leaked before, found by valgrind\r
1112     free(tags_aux);\r
1113 \r
1114     tags_aux = NULL;\r
1115 \r
1116     finished = true;\r
1117                 print_stats();\r
1118 \r
1119     return 1; // indicates success in the inicialization\r
1120  }\r
1121 \r
1122 \r
1123 // NewOpenTag(tagname): indicates the event of finding a new opening tag in the document.\r
1124 // Tag name is given. Returns a non-zero value upon success, and returns NULLT\r
1125 // in case of failing when trying to insert the new tag.\r
1126 int XMLTree::NewOpenTag(unsigned char *tagname)\r
1127  {\r
1128     int i;\r
1129 \r
1130     if (!initialized) {  // data structure has not been initialized properly\r
1131        fprintf(stderr, "Error: you cannot insert a new opening tag without first calling method OpenDocument first\n");\r
1132        return NULLT;\r
1133     }\r
1134     \r
1135     // inserts a new opening parentheses in the bit sequence\r
1136     if (sizeof(pb)*8*parArraySize == npar) { // no space left for the new parenthesis\r
1137        par_aux = (pb *)urealloc(par_aux, sizeof(pb)*2*parArraySize);\r
1138        parArraySize *= 2;\r
1139     }\r
1140     \r
1141     setbit(par_aux,npar,OP);  // marks a new opening parenthesis\r
1142 \r
1143     // transforms the tagname into a tag identifier. If the tag is new, we insert\r
1144     // it in the table.\r
1145     for (i=0; i<ntagnames; i++)\r
1146       if (strcmp((const char *)tagname,(const char *)TagName[i])==0) break;\r
1147  \r
1148 \r
1149     // NewOpenTag("<@>") was called\r
1150     if (i==0) \r
1151       found_attributes=true;\r
1152 \r
1153     if (i==ntagnames) { // the tag is a new one, then we insert it\r
1154        TagName = (unsigned char **)urealloc(TagName, sizeof(char *)*(ntagnames+1));\r
1155        \r
1156        if (!TagName) {\r
1157           fprintf(stderr, "Error: not enough memory\n");\r
1158           return NULLT;\r
1159        }\r
1160        \r
1161        ntagnames++;\r
1162        TagName[i] = (unsigned char *)umalloc(sizeof(unsigned char)*(strlen((const char *)tagname)+1));\r
1163        strcpy((char *)TagName[i], (const char *)tagname);\r
1164     } \r
1165     tags_aux = (TagType *) urealloc(tags_aux, sizeof(TagType)*(npar + 1));\r
1166 \r
1167     tags_aux[npar] = i; // inserts the new tag id within the preorder sequence of tags\r
1168     \r
1169     npar++;\r
1170     \r
1171     return 1;\r
1172     \r
1173  }\r
1174 \r
1175 \r
1176 // NewClosingTag(tagname): indicates the event of finding a new closing tag in the document.\r
1177 // Tag name is given. Returns a non-zero value upon success, and returns NULLT\r
1178 // in case of failing when trying to insert the new tag.\r
1179 int XMLTree::NewClosingTag(unsigned char *tagname)\r
1180  {\r
1181     int i;\r
1182 \r
1183     if (!initialized) {  // data structure has not been initialized properly\r
1184        fprintf(stderr, "Error: you cannot insert a new closing tag without first calling method OpenDocument first\n");\r
1185        return NULLT;\r
1186     }\r
1187     \r
1188     // inserts a new closing parentheses in the bit sequence\r
1189     if (sizeof(pb)*8*parArraySize == npar) { // no space left for the new parenthesis\r
1190        par_aux = (pb *)urealloc(par_aux, sizeof(pb)*2*parArraySize);\r
1191        parArraySize *= 2;\r
1192     }\r
1193     \r
1194     setbit(par_aux,npar,CP);  // marks a new closing parenthesis\r
1195 \r
1196     // transforms the tagname into a tag identifier. If the tag is new, we insert\r
1197     // it in the table.\r
1198     for (i=0; i<ntagnames; i++)\r
1199        if ((strcmp((const char *)tagname,(const char *)(TagName[i]+1))==0) && (TagName[i][0]=='/')) break;\r
1200  \r
1201     if (i==ntagnames) { // the tag is a new one, then we insert it\r
1202        TagName = (unsigned char **)urealloc(TagName, sizeof(char *)*(ntagnames+1));\r
1203        \r
1204        ntagnames++;\r
1205        TagName[i] = (unsigned char *)umalloc(sizeof(char)*(strlen((const char *)tagname)+2));\r
1206        TagName[i][0] = '/';\r
1207        strcpy((char *)&(TagName[i][1]), (const char *)tagname);\r
1208     } \r
1209 \r
1210     tags_aux = (TagType *)urealloc(tags_aux, sizeof(TagType)*(npar + 1));\r
1211 \r
1212     tags_aux[npar] = i; // inserts the new tag id within the preorder sequence of tags\r
1213     \r
1214     npar++;\r
1215 \r
1216     return 1; // success\r
1217     \r
1218  }\r
1219 \r
1220 \r
1221 // NewText(s): indicates the event of finding a new (non-empty) text s in the document.\r
1222 // The new text is inserted within the text collection. Returns a non-zero value upon\r
1223 // success, NULLT in case of error.\r
1224 int XMLTree::NewText(unsigned char *s)\r
1225  {\r
1226     if (!initialized) {  // data structure has not been initialized properly\r
1227        fprintf(stderr, "Error: you cannot insert a new text without first calling method OpenDocument first\n");\r
1228        return NULLT;\r
1229     }\r
1230 \r
1231     if (disable_tc) {\r
1232       XMLTree::NewEmptyText();\r
1233       return 1;\r
1234     };\r
1235 \r
1236     if (!indexing_empty_texts) {\r
1237        empty_texts_aux = (unsigned int *)urealloc(empty_texts_aux, sizeof(pb)*(1+(npar-1)/(8*sizeof(pb))));\r
1238               bitset(empty_texts_aux, npar-1);  // marks the non-empty text with a 1 in the bit vector\r
1239     }\r
1240     \r
1241     TextBuilder->InsertText(s);\r
1242     string cpps = (char*) s;\r
1243     CachedText.push_back(cpps); \r
1244     \r
1245     return 1; // success\r
1246  }\r
1247 \r
1248 // NewEmptyText(): indicates the event of finding a new empty text in the document.\r
1249 // In case of indexing empty and non-empty texts, we insert the empty texts into the\r
1250 // text collection. In case of indexing only non-empty texts, it just indicates an\r
1251 // empty text in the bit vector of empty texts. Returns a non-zero value upon\r
1252 // success, NULLT in case of error.\r
1253 int XMLTree::NewEmptyText() \r
1254  {\r
1255     unsigned char c = 0;\r
1256     if (!initialized) {  // data structure has not been initialized properly\r
1257        fprintf(stderr, "Error: you cannot insert a new empty text without first calling method OpenDocument first\n");\r
1258        return NULLT;\r
1259     }\r
1260 \r
1261     if (!indexing_empty_texts) {\r
1262        empty_texts_aux = (unsigned int *)urealloc(empty_texts_aux, sizeof(pb)*(1+(npar-1)/(8*sizeof(pb))));\r
1263        \r
1264        bitclean(empty_texts_aux, npar-1);  // marks the empty text with a 0 in the bit vector\r
1265     }\r
1266     else TextBuilder->InsertText(&c); // we insert the empty text just in case we index all the texts\r
1267     \r
1268     return 1; // success    \r
1269  }\r
1270 \r
1271 \r
1272 // GetTagId: returns the tag identifier corresponding to a given tag name.\r
1273 // Returns NULLT in case that the tag name does not exists.\r
1274 TagType XMLTree::GetTagId(unsigned char *tagname)\r
1275  {\r
1276     int i;\r
1277     // this should be changed for more efficient processing\r
1278     for (i=0; i<ntagnames; i++)\r
1279        if (strcmp((const char *)tagname,(const char *)TagName[i])==0) break; \r
1280     if (i==ntagnames) return (TagType)-1; //ntagnames; //(TagType)NULLT; // tagname does not exists in the table\r
1281     else return i;\r
1282  }\r
1283 \r
1284 \r
1285 // GetTagName(tagid): returns the tag name of a given tag identifier.\r
1286 // Returns NULL in case that the tag identifier is not valid.\r
1287 unsigned char *XMLTree::GetTagName(TagType tagid)\r
1288  {\r
1289     unsigned char *s;\r
1290                 if(tagid==(uint)-1) return NULL;\r
1291     if (tagid >= ntagnames) return NULL; // invalid tag identifier\r
1292     s = (unsigned char *)umalloc((strlen((const char *)TagName[tagid])+1)*sizeof(unsigned char));\r
1293     strcpy((char *)s, (const char *)TagName[tagid]);\r
1294     return s;\r
1295  }\r
1296 \r
1297 \r
1298 //KIM : OJO need the two following methods\r
1299 \r
1300 const unsigned char *XMLTree::GetTagNameByRef(TagType tagid)\r
1301  {\r
1302                 if(tagid==(uint)-1) return NULL;\r
1303     if (tagid >= ntagnames) return NULL; // invalid tag identifier\r
1304     return ((const unsigned char*)  TagName[tagid]);\r
1305  }\r
1306 \r
1307 \r
1308 \r
1309 TagType XMLTree::RegisterTag(unsigned char *tagname)\r
1310 {\r
1311   if (!finished)\r
1312     return NULLT;\r
1313   \r
1314   TagType id = XMLTree::GetTagId(tagname);\r
1315   if (id == NULLT){\r
1316     id = ntagnames;\r
1317     ntagnames = ntagnames + 1;    \r
1318     TagName = (unsigned char **) urealloc(TagName,ntagnames*(sizeof(unsigned char*)));\r
1319     TagName[id] = (unsigned char *) umalloc(sizeof(unsigned char)*strlen( (const char*) tagname)+1);\r
1320     strcpy((char*)TagName[id], (const char *)tagname);  \r
1321   };\r
1322 \r
1323   return id;\r
1324 }\r