Fixed and added a few Doxygen comments. Got rid of redundant function
[idzebra-moved-to-github.git] / index / zebraapi.c
1 /* $Id: zebraapi.c,v 1.173 2005-06-02 11:59:53 adam Exp $
2    Copyright (C) 1995-2005
3    Index Data ApS
4
5 This file is part of the Zebra server.
6
7 Zebra is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 Zebra is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Zebra; see the file LICENSE.zebra.  If not, write to the
19 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA.
21 */
22
23 #include <assert.h>
24 #include <stdio.h>
25 #include <limits.h>
26 #ifdef WIN32
27 #include <io.h>
28 #include <process.h>
29 #include <direct.h>
30 #else
31 #include <unistd.h>
32 #endif
33
34 #include <yaz/diagbib1.h>
35 #include <yaz/pquery.h>
36 #include <yaz/sortspec.h>
37 #include "index.h"
38 #include <charmap.h>
39 #include <idzebra/api.h>
40
41 /* simple asserts to validate the most essential input args */
42 #define ASSERTZH assert(zh && zh->service)
43 #define ASSERTZHRES assert(zh && zh->service && zh->res)
44 #define ASSERTZS assert(zs)
45
46 static int log_level = 0;
47 static int log_level_initialized = 0;
48
49 static Res zebra_open_res (ZebraHandle zh);
50 static void zebra_close_res (ZebraHandle zh);
51
52 static void zebra_chdir (ZebraService zs)
53 {
54     const char *dir ;
55     ASSERTZS;
56     yaz_log(log_level, "zebra_chdir");
57     dir = res_get (zs->global_res, "chdir");
58     if (!dir)
59         return;
60     yaz_log (YLOG_DEBUG, "chdir %s", dir);
61 #ifdef WIN32
62     _chdir(dir);
63 #else
64     chdir (dir);
65 #endif
66 }
67
68 static void zebra_flush_reg (ZebraHandle zh)
69 {
70     ASSERTZH;
71     yaz_log(log_level, "zebra_flush_reg");
72     zebra_clearError(zh);
73     zebraExplain_flush (zh->reg->zei, zh);
74     
75     extract_flushWriteKeys (zh, 1 /* final */);
76     zebra_index_merge (zh );
77 }
78
79 static struct zebra_register *zebra_register_open (ZebraService zs, 
80                                                    const char *name,
81                                                    int rw, int useshadow,
82                                                    Res res,
83                                                    const char *reg_path);
84 static void zebra_register_close (ZebraService zs, struct zebra_register *reg);
85
86 ZebraHandle zebra_open (ZebraService zs)
87 {
88     ZebraHandle zh;
89     const char *default_encoding;
90     if (!log_level_initialized)
91     {
92         log_level = yaz_log_module_level("zebraapi");
93         log_level_initialized = 1;
94     }
95
96     yaz_log(log_level, "zebra_open");
97
98     if (!zs)
99         return 0;
100
101     zh = (ZebraHandle) xmalloc(sizeof(*zh));
102     yaz_log (YLOG_DEBUG, "zebra_open zs=%p returns %p", zs, zh);
103
104     zh->service = zs;
105     zh->reg = 0;          /* no register attached yet */
106     zh->sets = 0;
107     zh->destroyed = 0;
108     zh->errCode = 0;
109     zh->errString = 0;
110     zh->res = 0; 
111     zh->user_perm = 0;
112
113     zh->reg_name = xstrdup ("");
114     zh->path_reg = 0;
115     zh->num_basenames = 0;
116     zh->basenames = 0;
117
118     zh->trans_no = 0;
119     zh->trans_w_no = 0;
120
121     zh->lock_normal = 0;
122     zh->lock_shadow = 0;
123
124     zh->shadow_enable = 1;
125
126     default_encoding = res_get_def(zs->global_res, "encoding", "ISO-8859-1");
127
128     zh->iconv_to_utf8 =
129         yaz_iconv_open ("UTF-8", default_encoding);
130     if (zh->iconv_to_utf8 == 0)
131         yaz_log (YLOG_WARN, "iconv: %s to UTF-8 unsupported",
132            default_encoding);
133     zh->iconv_from_utf8 =
134         yaz_iconv_open (default_encoding, "UTF-8");
135     if (zh->iconv_to_utf8 == 0)
136         yaz_log (YLOG_WARN, "iconv: UTF-8 to %s unsupported",
137            default_encoding);
138
139     zh->record_encoding = 0;
140
141     zebra_mutex_cond_lock (&zs->session_lock);
142
143     zh->next = zs->sessions;
144     zs->sessions = zh;
145
146     zebra_mutex_cond_unlock (&zs->session_lock);
147
148     zh->store_data_buf = 0;
149
150     zh->m_limit = zebra_limit_create(1, 0);
151
152     zh->nmem_error = nmem_create();
153
154     return zh;
155 }
156
157 ZebraService zebra_start (const char *configName)
158 {
159     return zebra_start_res(configName, 0, 0);
160 }
161
162 ZebraService zebra_start_res (const char *configName, Res def_res, Res over_res)
163 {
164     Res res;
165
166     if (!log_level_initialized)
167     {
168         log_level = yaz_log_module_level("zebraapi");
169         log_level_initialized = 1;
170     }
171
172     yaz_log(YLOG_LOG, "zebra_start %s %s",configName, ZEBRAVER);
173     assert(configName);
174
175     if ((res = res_open (configName, def_res, over_res)))
176     {
177         const char *passwd_plain = 0;
178         const char *passwd_encrypt = 0;
179         ZebraService zh = xmalloc(sizeof(*zh));
180
181         yaz_log (YLOG_DEBUG, "Read resources `%s'", configName);
182         
183         zh->global_res = res;
184         zh->configName = xstrdup(configName);
185         zh->sessions = 0;
186         
187         zebra_chdir (zh);
188         
189         zebra_mutex_cond_init (&zh->session_lock);
190         passwd_plain = res_get (zh->global_res, "passwd");
191         passwd_encrypt = res_get (zh->global_res, "passwd.c");
192
193         if (!passwd_plain && !passwd_encrypt)
194             zh->passwd_db = NULL;
195         else
196         {
197             zh->passwd_db = passwd_db_open();
198             if (!zh->passwd_db)
199                 yaz_log (YLOG_WARN|YLOG_ERRNO, "passwd_db_open failed");
200             else
201             {
202                 if (passwd_plain)
203                     passwd_db_file_plain(zh->passwd_db, passwd_plain);
204                 if (passwd_encrypt)
205                     passwd_db_file_crypt(zh->passwd_db, passwd_encrypt);
206             }
207         }
208         zh->path_root = res_get (zh->global_res, "root");
209         zh->nmem = nmem_create();
210         zh->record_classes = recTypeClass_create (zh->global_res, zh->nmem);
211         return zh;
212     }
213     return 0;
214 }
215
216 void zebra_filter_info(ZebraService zs, void *cd,
217                         void (*cb)(void *cd, const char *name))
218 {
219     ASSERTZS;
220     assert(cb);
221     recTypeClass_info(zs->record_classes, cd, cb);
222 }
223
224 void zebra_pidfname(ZebraService zs, char *path)
225 {
226     ASSERTZS;
227     zebra_lock_prefix (zs->global_res, path);
228     strcat(path, "zebrasrv.pid");
229 }
230
231 Dict dict_open_res (BFiles bfs, const char *name, int cache, int rw,
232                     int compact_flag, Res res)
233 {
234     int page_size = 4096;
235     char resource_str[200];
236     const char *v;
237     sprintf (resource_str, "dict.%.100s.pagesize", name);
238     assert(bfs);
239     assert(name);
240
241     v = res_get(res, resource_str);
242     if (v)
243     {
244         page_size = atoi(v);
245         yaz_log(YLOG_LOG, "Using custom dictionary page size %d for %s",
246                 page_size, name);
247     }
248     return dict_open(bfs, name, cache, rw, compact_flag, page_size);
249 }
250
251
252 static
253 struct zebra_register *zebra_register_open (ZebraService zs, const char *name,
254                                             int rw, int useshadow, Res res,
255                                             const char *reg_path)
256 {
257     struct zebra_register *reg;
258     int record_compression = REC_COMPRESS_NONE;
259     const char *recordCompression = 0;
260     const char *profilePath;
261     char cwd[1024];
262
263     ASSERTZS;
264     
265     reg = xmalloc(sizeof(*reg));
266
267     assert (name);
268     reg->name = xstrdup (name);
269
270     reg->seqno = 0;
271     reg->last_val = 0;
272
273     assert (res);
274
275     yaz_log (YLOG_DEBUG, "zebra_register_open rw=%d useshadow=%d p=%p n=%s rp=%s",
276              rw, useshadow, reg, name, reg_path ? reg_path : "(none)");
277     
278     reg->dh = data1_createx (DATA1_FLAG_XML);
279     if (!reg->dh)
280     {
281         xfree(reg);
282         return 0;
283     }
284     reg->bfs = bfs_create (res_get (res, "register"), reg_path);
285     if (!reg->bfs)
286     {
287         data1_destroy(reg->dh);
288         xfree(reg);
289         return 0;
290     }
291     if (useshadow)
292     {
293         if (bf_cache (reg->bfs, res_get (res, "shadow")) == ZEBRA_FAIL)
294         {
295             bfs_destroy(reg->bfs);
296             data1_destroy(reg->dh);
297             xfree(reg);
298             return 0;
299         }
300     }
301
302     getcwd(cwd, sizeof(cwd)-1);
303     profilePath = res_get_def(res, "profilePath", DEFAULT_PROFILE_PATH);
304     yaz_log(YLOG_DEBUG, "profilePath=%s cwd=%s", profilePath, cwd);
305
306     data1_set_tabpath (reg->dh, profilePath);
307     data1_set_tabroot (reg->dh, reg_path);
308     reg->recTypes = recTypes_init (zs->record_classes, reg->dh);
309
310     reg->zebra_maps = zebra_maps_open (res, reg_path);
311     reg->rank_classes = NULL;
312
313     reg->key_buf = 0;
314
315     reg->keys.buf_max = 0;
316     reg->keys.buf = 0;
317     reg->keys.codec_handle = iscz1_start();
318
319     reg->sortKeys.buf = 0;
320     reg->sortKeys.buf_max = 0;
321
322     reg->records = 0;
323     reg->dict = 0;
324     reg->sortIdx = 0;
325     reg->isams = 0;
326     reg->matchDict = 0;
327     reg->isamc = 0;
328     reg->isamb = 0;
329     reg->zei = 0;
330     reg->matchDict = 0;
331     reg->key_file_no = 0;
332     reg->ptr_i = 0;
333     
334     zebraRankInstall (reg, rank1_class);
335     zebraRankInstall (reg, rankzv_class);
336
337     recordCompression = res_get_def (res, "recordCompression", "none");
338     if (!strcmp (recordCompression, "none"))
339         record_compression = REC_COMPRESS_NONE;
340     if (!strcmp (recordCompression, "bzip2"))
341         record_compression = REC_COMPRESS_BZIP2;
342
343     if (!(reg->records = rec_open (reg->bfs, rw, record_compression)))
344     {
345         yaz_log (YLOG_WARN, "rec_open failed");
346         return 0;
347     }
348     if (rw)
349     {
350         reg->matchDict = dict_open_res (reg->bfs, GMATCH_DICT, 20, 1, 0, res);
351     }
352     if (!(reg->dict = dict_open_res (reg->bfs, FNAME_DICT, 40, rw, 0, res)))
353     {
354         yaz_log (YLOG_WARN, "dict_open failed");
355         return 0;
356     }
357     if (!(reg->sortIdx = sortIdx_open (reg->bfs, rw)))
358     {
359         yaz_log (YLOG_WARN, "sortIdx_open failed");
360         return 0;
361     }
362     if (res_get_match (res, "isam", "s", ISAM_DEFAULT))
363     {
364         struct ISAMS_M_s isams_m;
365         if (!(reg->isams = isams_open (reg->bfs, FNAME_ISAMS, rw,
366                                       key_isams_m(res, &isams_m))))
367         {
368             yaz_log (YLOG_WARN, "isams_open failed");
369             return 0;
370         }
371     }
372     if (res_get_match (res, "isam", "c", ISAM_DEFAULT))
373     {
374         struct ISAMC_M_s isamc_m;
375         if (!(reg->isamc = isamc_open (reg->bfs, FNAME_ISAMC,
376                                     rw, key_isamc_m(res, &isamc_m))))
377         {
378             yaz_log (YLOG_WARN, "isamc_open failed");
379             return 0;
380         }
381     }
382     if (res_get_match (res, "isam", "b", ISAM_DEFAULT))
383     {
384         struct ISAMC_M_s isamc_m;
385         
386         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
387                                        rw, key_isamc_m(res, &isamc_m), 0)))
388         {
389             yaz_log (YLOG_WARN, "isamb_open failed");
390             return 0;
391         }
392     }
393     if (res_get_match (res, "isam", "bc", ISAM_DEFAULT))
394     {
395         struct ISAMC_M_s isamc_m;
396         
397         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
398                                        rw, key_isamc_m(res, &isamc_m), 1)))
399         {
400             yaz_log (YLOG_WARN, "isamb_open failed");
401             return 0;
402         }
403     }
404     if (res_get_match (res, "isam", "null", ISAM_DEFAULT))
405     {
406         struct ISAMC_M_s isamc_m;
407         
408         if (!(reg->isamb = isamb_open (reg->bfs, "isamb",
409                                        rw, key_isamc_m(res, &isamc_m), -1)))
410         {
411             yaz_log (YLOG_WARN, "isamb_open failed");
412             return 0;
413         }
414     }
415     reg->zei = zebraExplain_open (reg->records, reg->dh,
416                                   res, rw, reg,
417                                   explain_extract);
418     if (!reg->zei)
419     {
420         yaz_log (YLOG_WARN, "Cannot obtain EXPLAIN information");
421         return 0;
422     }
423     reg->active = 2;
424     yaz_log (YLOG_DEBUG, "zebra_register_open ok p=%p", reg);
425     return reg;
426 }
427
428 ZEBRA_RES zebra_admin_shutdown (ZebraHandle zh)
429 {
430     ASSERTZH;
431     yaz_log(log_level, "zebra_admin_shutdown");
432     zebra_clearError(zh);
433
434     zebra_mutex_cond_lock (&zh->service->session_lock);
435     zh->service->stop_flag = 1;
436     zebra_mutex_cond_unlock (&zh->service->session_lock);
437     return ZEBRA_OK;
438 }
439
440 ZEBRA_RES zebra_admin_start (ZebraHandle zh)
441 {
442     ZebraService zs;
443     ASSERTZH;
444     yaz_log(log_level, "zebra_admin_start");
445     zebra_clearError(zh);
446     zs = zh->service;
447     zebra_mutex_cond_lock (&zs->session_lock);
448     zebra_mutex_cond_unlock (&zs->session_lock);
449     return ZEBRA_OK;
450 }
451
452 static void zebra_register_close (ZebraService zs, struct zebra_register *reg)
453 {
454     ASSERTZS;
455     assert(reg);
456     yaz_log(YLOG_DEBUG, "zebra_register_close p=%p", reg);
457     reg->stop_flag = 0;
458     zebra_chdir (zs);
459     if (reg->records)
460     {
461         zebraExplain_close (reg->zei);
462         dict_close (reg->dict);
463         if (reg->matchDict)
464             dict_close (reg->matchDict);
465         sortIdx_close (reg->sortIdx);
466         if (reg->isams)
467             isams_close (reg->isams);
468         if (reg->isamc)
469             isamc_close (reg->isamc);
470         if (reg->isamb)
471             isamb_close (reg->isamb);
472         rec_close (&reg->records);
473     }
474
475     recTypes_destroy (reg->recTypes);
476     zebra_maps_close (reg->zebra_maps);
477     zebraRankDestroy (reg);
478     bfs_destroy (reg->bfs);
479     data1_destroy (reg->dh);
480
481     xfree(reg->sortKeys.buf);
482     xfree(reg->keys.buf);
483     if (reg->keys.codec_handle)
484         iscz1_stop(reg->keys.codec_handle);
485     xfree(reg->key_buf);
486     xfree(reg->name);
487     xfree(reg);
488 }
489
490 ZEBRA_RES zebra_stop(ZebraService zs)
491 {
492     if (!zs)
493         return ZEBRA_OK;
494     yaz_log (log_level, "zebra_stop");
495
496     while (zs->sessions)
497     {
498         zebra_close (zs->sessions);
499     }
500         
501     zebra_mutex_cond_destroy (&zs->session_lock);
502
503     if (zs->passwd_db)
504         passwd_db_close (zs->passwd_db);
505
506     recTypeClass_destroy(zs->record_classes);
507     nmem_destroy(zs->nmem);
508     res_close (zs->global_res);
509     xfree(zs->configName);
510     xfree(zs);
511     return ZEBRA_OK;
512 }
513
514 ZEBRA_RES zebra_close (ZebraHandle zh)
515 {
516     ZebraService zs;
517     struct zebra_session **sp;
518     int i;
519
520     yaz_log(log_level, "zebra_close");
521     if (!zh)
522         return ZEBRA_OK;
523     ASSERTZH;
524     zh->errCode = 0;
525     
526     zs = zh->service;
527     yaz_log (YLOG_DEBUG, "zebra_close zh=%p", zh);
528     resultSetDestroy (zh, -1, 0, 0);
529
530     if (zh->reg)
531         zebra_register_close (zh->service, zh->reg);
532     zebra_close_res (zh);
533
534     xfree(zh->record_encoding);
535
536     for (i = 0; i < zh->num_basenames; i++)
537         xfree(zh->basenames[i]);
538     xfree(zh->basenames);
539
540     if (zh->iconv_to_utf8 != 0)
541         yaz_iconv_close (zh->iconv_to_utf8);
542     if (zh->iconv_from_utf8 != 0)
543         yaz_iconv_close (zh->iconv_from_utf8);
544
545     zebra_mutex_cond_lock (&zs->session_lock);
546     zebra_lock_destroy (zh->lock_normal);
547     zebra_lock_destroy (zh->lock_shadow);
548     sp = &zs->sessions;
549     while (1)
550     {
551         assert (*sp);
552         if (*sp == zh)
553         {
554             *sp = (*sp)->next;
555             break;
556         }
557         sp = &(*sp)->next;
558     }
559     zebra_mutex_cond_unlock (&zs->session_lock);
560     xfree(zh->reg_name);
561     xfree(zh->user_perm);
562     zh->service = 0; /* more likely to trigger an assert */
563
564     zebra_limit_destroy(zh->m_limit);
565
566     nmem_destroy(zh->nmem_error);
567
568     xfree(zh->path_reg);
569     xfree(zh);
570     return ZEBRA_OK;
571 }
572
573 struct map_baseinfo {
574     ZebraHandle zh;
575     NMEM mem;
576     int num_bases;
577     char **basenames;
578     int new_num_bases;
579     char **new_basenames;
580     int new_num_max;
581 };
582
583 static Res zebra_open_res (ZebraHandle zh)
584 {
585     Res res = 0;
586     char fname[512];
587     ASSERTZH;
588     zh->errCode = 0;
589
590     if (zh->path_reg)
591     {
592         sprintf (fname, "%.200s/zebra.cfg", zh->path_reg);
593         res = res_open (fname, zh->service->global_res, 0);
594         if (!res)
595             res = zh->service->global_res;
596     }
597     else if (*zh->reg_name == 0)
598     {
599         res = zh->service->global_res;
600     }
601     else
602     {
603         yaz_log (YLOG_WARN, "no register root specified");
604         return 0;  /* no path for register - fail! */
605     }
606     return res;
607 }
608
609 static void zebra_close_res (ZebraHandle zh)
610 {
611     ASSERTZH;
612     zh->errCode = 0;
613     if (zh->res != zh->service->global_res)
614         res_close (zh->res);
615     zh->res = 0;
616 }
617
618 static void zebra_select_register (ZebraHandle zh, const char *new_reg)
619 {
620     ASSERTZH;
621     zh->errCode = 0;
622     if (zh->res && strcmp (zh->reg_name, new_reg) == 0)
623         return;
624     if (!zh->res)
625     {
626         assert (zh->reg == 0);
627         assert (*zh->reg_name == 0);
628     }
629     else
630     {
631         if (zh->reg)
632         {
633             resultSetInvalidate (zh);
634             zebra_register_close (zh->service, zh->reg);
635             zh->reg = 0;
636         }
637         zebra_close_res(zh);
638     }
639     xfree(zh->reg_name);
640     zh->reg_name = xstrdup (new_reg);
641
642     xfree(zh->path_reg);
643     zh->path_reg = 0;
644     if (zh->service->path_root)
645     {
646         zh->path_reg = xmalloc(strlen(zh->service->path_root) + 
647                                 strlen(zh->reg_name) + 3);
648         strcpy (zh->path_reg, zh->service->path_root);
649         if (*zh->reg_name)
650         {
651             strcat (zh->path_reg, "/");
652             strcat (zh->path_reg, zh->reg_name);
653         }
654     }
655     zh->res = zebra_open_res (zh);
656     
657     if (zh->lock_normal)
658         zebra_lock_destroy (zh->lock_normal);
659     zh->lock_normal = 0;
660
661     if (zh->lock_shadow)
662         zebra_lock_destroy (zh->lock_shadow);
663     zh->lock_shadow = 0;
664
665     if (zh->res)
666     {
667         char fname[512];
668         const char *lock_area  =res_get (zh->res, "lockDir");
669         
670         if (!lock_area && zh->path_reg)
671             res_set (zh->res, "lockDir", zh->path_reg);
672         sprintf (fname, "norm.%s.LCK", zh->reg_name);
673         zh->lock_normal =
674             zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
675         
676         sprintf (fname, "shadow.%s.LCK", zh->reg_name);
677         zh->lock_shadow =
678             zebra_lock_create (res_get(zh->res, "lockDir"), fname, 0);
679
680         if (!zh->lock_normal || !zh->lock_shadow)
681         {
682             if (zh->lock_normal)
683             {
684                 zebra_lock_destroy(zh->lock_normal);
685                 zh->lock_normal = 0;
686             }
687             if (zh->lock_shadow)
688             {
689                 zebra_lock_destroy(zh->lock_shadow);
690                 zh->lock_shadow = 0;
691             }
692             zebra_close_res(zh);
693         }
694     }
695 }
696
697 void map_basenames_func (void *vp, const char *name, const char *value)
698 {
699     struct map_baseinfo *p = (struct map_baseinfo *) vp;
700     int i, no;
701     char fromdb[128], todb[8][128];
702
703     assert(value);
704     assert(name);
705     assert(vp);
706     
707     no =
708         sscanf (value, "%127s %127s %127s %127s %127s %127s %127s %127s %127s",
709                 fromdb, todb[0], todb[1], todb[2], todb[3], todb[4],
710                 todb[5], todb[6], todb[7]);
711     if (no < 2)
712         return ;
713     no--;
714     for (i = 0; i<p->num_bases; i++)
715         if (p->basenames[i] && !STRCASECMP (p->basenames[i], fromdb))
716         {
717             p->basenames[i] = 0;
718             for (i = 0; i < no; i++)
719             {
720                 if (p->new_num_bases == p->new_num_max)
721                     return;
722                 p->new_basenames[(p->new_num_bases)++] = 
723                     nmem_strdup (p->mem, todb[i]);
724             }
725             return;
726         }
727 }
728
729 int zebra_select_default_database(ZebraHandle zh)
730 {
731     if (!zh->res)
732     {
733         /* no database has been selected - so we select based on
734            resource setting (including group)
735         */
736         const char *group = res_get(zh->service->global_res, "group");
737         const char *v = res_get_prefix(zh->service->global_res,
738                                        "database", group, "Default");
739         return zebra_select_database(zh, v);
740     }
741     return 0;
742 }
743
744 void map_basenames (ZebraHandle zh, ODR stream,
745                     int *num_bases, char ***basenames)
746 {
747     struct map_baseinfo info;
748     struct map_baseinfo *p = &info;
749     int i;
750     ASSERTZH;
751     yaz_log(log_level, "map_basenames ");
752     assert(stream);
753
754     info.zh = zh;
755
756     info.num_bases = *num_bases;
757     info.basenames = *basenames;
758     info.new_num_max = 128;
759     info.new_num_bases = 0;
760     info.new_basenames = (char **)
761         odr_malloc (stream, sizeof(*info.new_basenames) * info.new_num_max);
762     info.mem = stream->mem;
763
764     res_trav (zh->service->global_res, "mapdb", &info, map_basenames_func);
765     
766     for (i = 0; i<p->num_bases; i++)
767         if (p->basenames[i] && p->new_num_bases < p->new_num_max)
768         {
769             p->new_basenames[(p->new_num_bases)++] = 
770                 nmem_strdup (p->mem, p->basenames[i]);
771         }
772     *num_bases = info.new_num_bases;
773     *basenames = info.new_basenames;
774     for (i = 0; i<*num_bases; i++)
775         yaz_log (YLOG_DEBUG, "base %s", (*basenames)[i]);
776 }
777
778 ZEBRA_RES zebra_select_database (ZebraHandle zh, const char *basename)
779 {
780     ASSERTZH;
781     yaz_log(log_level, "zebra_select_database %s",basename);
782     assert(basename);
783     return zebra_select_databases (zh, 1, &basename);
784 }
785
786 ZEBRA_RES zebra_select_databases (ZebraHandle zh, int num_bases,
787                                   const char **basenames)
788 {
789     int i;
790     const char *cp;
791     int len = 0;
792     char *new_reg = 0;
793     ASSERTZH;
794     assert(basenames);
795
796     yaz_log(log_level, "zebra_select_databases n=%d [0]=%s",
797                     num_bases,basenames[0]);
798     zh->errCode = 0;
799     
800     if (num_bases < 1)
801     {
802         zh->errCode = YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP;
803         return ZEBRA_FAIL;
804     }
805     for (i = 0; i < zh->num_basenames; i++)
806         xfree(zh->basenames[i]);
807     xfree(zh->basenames);
808     
809     zh->num_basenames = num_bases;
810     zh->basenames = xmalloc(zh->num_basenames * sizeof(*zh->basenames));
811     for (i = 0; i < zh->num_basenames; i++)
812         zh->basenames[i] = xstrdup (basenames[i]);
813
814     cp = strrchr(basenames[0], '/');
815     if (cp)
816     {
817         len = cp - basenames[0];
818         new_reg = xmalloc(len + 1);
819         memcpy (new_reg, basenames[0], len);
820         new_reg[len] = '\0';
821     }
822     else
823         new_reg = xstrdup ("");
824     for (i = 1; i<num_bases; i++)
825     {
826         const char *cp1;
827
828         cp1 = strrchr (basenames[i], '/');
829         if (cp)
830         {
831             if (!cp1)
832             {
833                 zh->errCode = YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP;
834                 return -1;
835             }
836             if (len != cp1 - basenames[i] ||
837                 memcmp (basenames[i], new_reg, len))
838             {
839                 zh->errCode = YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP;
840                 return -1;
841             }
842         }
843         else
844         {
845             if (cp1)
846             {
847                 zh->errCode = YAZ_BIB1_COMBI_OF_SPECIFIED_DATABASES_UNSUPP;
848                 return ZEBRA_FAIL;
849             }
850         }
851     }
852     zebra_select_register (zh, new_reg);
853     xfree(new_reg);
854     if (!zh->res)
855     {
856         zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
857         return ZEBRA_FAIL;
858     }
859     if (!zh->lock_normal || !zh->lock_shadow)
860     {
861         zh->errCode = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
862         return ZEBRA_FAIL;
863     }
864     return ZEBRA_OK;
865 }
866
867 ZEBRA_RES zebra_search_RPN(ZebraHandle zh, ODR o, Z_RPNQuery *query,
868                            const char *setname, zint *hits)
869 {
870     ZEBRA_RES r;
871     ASSERTZH;
872     assert(o);
873     assert(query);
874     assert(hits);
875     assert(setname);
876     yaz_log(log_level, "zebra_search_rpn");
877     zebra_clearError(zh);
878     zh->hits = 0;
879     *hits = 0;
880
881     if (zebra_begin_read(zh) == ZEBRA_FAIL)
882         return ZEBRA_FAIL;
883
884     r = resultSetAddRPN(zh, odr_extract_mem(o), query, 
885                         zh->num_basenames, zh->basenames, setname);
886     zebra_end_read(zh);
887     *hits = zh->hits;
888     return r;
889 }
890
891 ZEBRA_RES zebra_records_retrieve(ZebraHandle zh, ODR stream,
892                                  const char *setname,
893                                  Z_RecordComposition *comp,
894                                  oid_value input_format, int num_recs,
895                                  ZebraRetrievalRecord *recs)
896 {
897     ZebraMetaRecord *poset;
898     int i;
899     ZEBRA_RES ret = ZEBRA_OK;
900     zint *pos_array;
901     ASSERTZH;
902     assert(stream);
903     assert(setname);
904     assert(recs);
905     assert(num_recs>0);
906
907     yaz_log(log_level, "zebra_records_retrieve n=%d", num_recs);
908
909     zebra_clearError(zh);
910     if (!zh->res)
911     {
912         zebra_setError(zh, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
913                        setname);
914         return ZEBRA_FAIL;
915     }
916     
917     if (zebra_begin_read (zh) == ZEBRA_FAIL)
918         return ZEBRA_FAIL;
919
920     pos_array = (zint *) xmalloc(num_recs * sizeof(*pos_array));
921     for (i = 0; i<num_recs; i++)
922         pos_array[i] = recs[i].position;
923     poset = zebra_meta_records_create(zh, setname, num_recs, pos_array);
924     if (!poset)
925     {
926         yaz_log (YLOG_DEBUG, "zebraPosSetCreate error");
927         zebra_setError(zh, YAZ_BIB1_SPECIFIED_RESULT_SET_DOES_NOT_EXIST,
928                        setname);
929         ret = ZEBRA_FAIL;
930     }
931     else
932     {
933         for (i = 0; i<num_recs; i++)
934         {
935             if (poset[i].term)
936             {
937                 recs[i].errCode = 0;
938                 recs[i].format = VAL_SUTRS;
939                 recs[i].len = strlen(poset[i].term);
940                 recs[i].buf = poset[i].term;
941                 recs[i].base = poset[i].db;
942             }
943             else if (poset[i].sysno)
944             {
945                 char *buf;
946                 int len;
947
948                 zebra_get_hit_vector(zh, setname, poset[i].sysno);
949
950                 recs[i].errCode =
951                     zebra_record_fetch(zh, poset[i].sysno, poset[i].score,
952                                        stream, input_format, comp,
953                                        &recs[i].format, &buf, &len,
954                                        &recs[i].base, &recs[i].errString);
955                 recs[i].len = len;
956                 if (len > 0)
957                 {
958                     recs[i].buf = (char*) odr_malloc(stream, len);
959                     memcpy(recs[i].buf, buf, len);
960                 }
961                 else
962                     recs[i].buf = buf;
963                 recs[i].score = poset[i].score;
964                 recs[i].sysno = poset[i].sysno;
965             }
966             else
967             {
968                 if (ret == ZEBRA_OK) /* only need to set it once */
969                     zebra_setError_zint(zh,
970                                         YAZ_BIB1_PRESENT_REQUEST_OUT_OF_RANGE,
971                                         pos_array[i]);
972                 ret = ZEBRA_FAIL;
973                 break;
974             }
975         }
976         zebra_meta_records_destroy(zh, poset, num_recs);
977     }
978     zebra_end_read (zh);
979     xfree(pos_array);
980     return ret;
981 }
982
983 ZEBRA_RES zebra_scan_PQF(ZebraHandle zh, ODR stream, const char *query,
984                          int *position,
985                          int *num_entries, ZebraScanEntry **entries,
986                          int *is_partial)
987 {
988     YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
989     Z_AttributesPlusTerm *zapt;
990     int *attributeSet;
991     ZEBRA_RES res;
992     
993     if (!(zapt = yaz_pqf_scan(pqf_parser, stream, &attributeSet, query)))
994     {
995         res = ZEBRA_FAIL;
996         zh->errCode = YAZ_BIB1_SCAN_MALFORMED_SCAN;
997     }
998     else
999         res = zebra_scan(zh, stream, zapt, VAL_BIB1,
1000                          position, num_entries, entries, is_partial);
1001     yaz_pqf_destroy (pqf_parser);
1002     return res;
1003 }
1004
1005 ZEBRA_RES zebra_scan(ZebraHandle zh, ODR stream, Z_AttributesPlusTerm *zapt,
1006                      oid_value attributeset,
1007                      int *position,
1008                      int *num_entries, ZebraScanEntry **entries,
1009                      int *is_partial)
1010 {
1011     ZEBRA_RES res;
1012     ASSERTZH;
1013     assert(stream);
1014     assert(zapt);
1015     assert(position);
1016     assert(num_entries);
1017     assert(is_partial);
1018     assert(entries);
1019     yaz_log(log_level, "zebra_scan");
1020     zebra_clearError(zh);
1021     if (zebra_begin_read (zh) == ZEBRA_FAIL)
1022     {
1023         *entries = 0;
1024         *num_entries = 0;
1025         return ZEBRA_FAIL;
1026     }
1027     res = rpn_scan (zh, stream, zapt, attributeset,
1028                     zh->num_basenames, zh->basenames, position,
1029                     num_entries, entries, is_partial, 0, 0);
1030     zebra_end_read (zh);
1031     return res;
1032 }
1033
1034 ZEBRA_RES zebra_sort (ZebraHandle zh, ODR stream,
1035                       int num_input_setnames, const char **input_setnames,
1036                       const char *output_setname,
1037                       Z_SortKeySpecList *sort_sequence,
1038                       int *sort_status)
1039 {
1040     ZEBRA_RES res;
1041     ASSERTZH;
1042     assert(stream);
1043     assert(num_input_setnames>0);
1044     assert(input_setnames);
1045     assert(sort_sequence);
1046     assert(sort_status);
1047     yaz_log(log_level, "zebra_sort");
1048     zebra_clearError(zh);
1049     if (zebra_begin_read(zh) == ZEBRA_FAIL)
1050         return ZEBRA_FAIL;
1051     res = resultSetSort(zh, stream->mem, num_input_setnames, input_setnames,
1052                         output_setname, sort_sequence, sort_status);
1053     zebra_end_read(zh);
1054     return res;
1055 }
1056
1057 int zebra_deleteResultSet(ZebraHandle zh, int function,
1058                           int num_setnames, char **setnames,
1059                           int *statuses)
1060 {
1061     int i, status;
1062     ASSERTZH;
1063     assert(statuses);
1064     yaz_log(log_level, "zebra_deleteResultSet n=%d",num_setnames);
1065     zebra_clearError(zh);;
1066     if (zebra_begin_read(zh))
1067         return Z_DeleteStatus_systemProblemAtTarget;
1068     switch (function)
1069     {
1070     case Z_DeleteResultSetRequest_list:
1071         assert(num_setnames>0);
1072         assert(setnames);
1073         resultSetDestroy (zh, num_setnames, setnames, statuses);
1074         break;
1075     case Z_DeleteResultSetRequest_all:
1076         resultSetDestroy (zh, -1, 0, statuses);
1077         break;
1078     }
1079     zebra_end_read (zh);
1080     status = Z_DeleteStatus_success;
1081     for (i = 0; i<num_setnames; i++)
1082         if (statuses[i] == Z_DeleteStatus_resultSetDidNotExist)
1083             status = statuses[i];
1084     return status;
1085 }
1086
1087 int zebra_errCode (ZebraHandle zh)
1088 {
1089     if (zh)
1090     {
1091         yaz_log(log_level, "zebra_errCode: %d",zh->errCode);
1092         return zh->errCode;
1093     }
1094     yaz_log(log_level, "zebra_errCode: o");
1095     return 0; 
1096 }
1097
1098 const char *zebra_errString (ZebraHandle zh)
1099 {
1100     const char *e = 0;
1101     if (zh)
1102         e= diagbib1_str (zh->errCode);
1103     yaz_log(log_level, "zebra_errString: %s",e);
1104     return e;
1105 }
1106
1107 char *zebra_errAdd (ZebraHandle zh)
1108 {
1109     char *a = 0;
1110     if (zh)
1111         a= zh->errString;
1112     yaz_log(log_level, "zebra_errAdd: %s",a);
1113     return a;
1114 }
1115
1116 void zebra_clearError(ZebraHandle zh)
1117 {
1118     if (zh)
1119     {
1120         zh->errCode = 0;
1121         zh->errString = 0;
1122     }
1123 }
1124
1125 ZEBRA_RES zebra_auth (ZebraHandle zh, const char *user, const char *pass)
1126 {
1127     const char *p;
1128     char u[40];
1129     ZebraService zs;
1130
1131     ASSERTZH;
1132     zebra_clearError(zh);
1133     zs= zh->service;
1134     
1135     sprintf(u, "perm.%.30s", user ? user : "anonymous");
1136     p = res_get(zs->global_res, u);
1137     xfree(zh->user_perm);
1138     zh->user_perm = xstrdup(p ? p : "r");
1139
1140     /* users that don't require a password .. */
1141     if (zh->user_perm && strchr(zh->user_perm, 'a'))
1142         return ZEBRA_OK;
1143     
1144     if (!zs->passwd_db || !passwd_db_auth (zs->passwd_db, user, pass))
1145         return ZEBRA_OK;
1146     return ZEBRA_FAIL;
1147 }
1148
1149 ZEBRA_RES zebra_admin_import_begin (ZebraHandle zh, const char *database,
1150                                const char *record_type)
1151 {
1152     ASSERTZH;
1153     yaz_log(log_level, "zebra_admin_import_begin db=%s rt=%s", 
1154                      database, record_type);
1155     zebra_clearError(zh);
1156     if (zebra_select_database(zh, database) == ZEBRA_FAIL)
1157         return ZEBRA_FAIL;
1158     return zebra_begin_trans(zh, 1);
1159 }
1160
1161 ZEBRA_RES zebra_admin_import_end (ZebraHandle zh)
1162 {
1163     ASSERTZH;
1164     yaz_log(log_level, "zebra_admin_import_end");
1165     zebra_clearError(zh);
1166     return zebra_end_trans(zh);
1167 }
1168
1169 ZEBRA_RES zebra_admin_import_segment (ZebraHandle zh, Z_Segment *segment)
1170 {
1171     ZEBRA_RES res = ZEBRA_OK;
1172     SYSNO sysno;
1173     int i;
1174     ASSERTZH;
1175     yaz_log(log_level, "zebra_admin_import_segment");
1176     zebra_clearError(zh);
1177     for (i = 0; i<segment->num_segmentRecords; i++)
1178     {
1179         Z_NamePlusRecord *npr = segment->segmentRecords[i];
1180
1181         if (npr->which == Z_NamePlusRecord_intermediateFragment)
1182         {
1183             Z_FragmentSyntax *fragment = npr->u.intermediateFragment;
1184             if (fragment->which == Z_FragmentSyntax_notExternallyTagged)
1185             {
1186                 Odr_oct *oct = fragment->u.notExternallyTagged;
1187                 sysno = 0;
1188                 
1189                 if ( zebra_update_record(zh, 
1190                                          0, /* record Type */
1191                                          &sysno,
1192                                          0, /* match */
1193                                          0, /* fname */
1194                                          oct->buf, oct->len,
1195                                          0) == ZEBRA_FAIL)
1196                     res = ZEBRA_FAIL;
1197             }
1198         }
1199     }
1200     return res;
1201 }
1202
1203 ZEBRA_RES zebra_admin_exchange_record (ZebraHandle zh,
1204                                        const char *rec_buf,
1205                                        size_t rec_len,
1206                                        const char *recid_buf, size_t recid_len,
1207                                        int action)
1208     /* 1 = insert. Fail it already exists */
1209     /* 2 = replace. Fail it does not exist */
1210     /* 3 = delete. Fail if does not exist */
1211     /* 4 = update. Insert/replace */
1212 {
1213     ZEBRA_RES res;
1214     SYSNO sysno = 0;
1215     char *rinfo = 0;
1216     char recid_z[256];
1217     ASSERTZH;
1218     assert(action>0 && action <=4);
1219     assert(rec_buf);
1220
1221     yaz_log(log_level, "zebra_admin_exchange_record ac=%d", action);
1222     zebra_clearError(zh);
1223
1224     if (!recid_buf || recid_len <= 0 || recid_len >= sizeof(recid_z))
1225         return ZEBRA_FAIL;
1226
1227     memcpy (recid_z, recid_buf, recid_len);
1228     recid_z[recid_len] = 0;
1229
1230     if (zebra_begin_trans(zh, 1) == ZEBRA_FAIL)
1231         return ZEBRA_FAIL;
1232
1233     rinfo = dict_lookup (zh->reg->matchDict, recid_z);
1234     if (rinfo)
1235     {
1236         if (action == 1)  /* fail if insert */
1237         {
1238              zebra_end_trans(zh);
1239              return ZEBRA_FAIL;
1240         }
1241
1242         memcpy (&sysno, rinfo+1, sizeof(sysno));
1243     }
1244     else
1245     {
1246         if (action == 2 || action == 3) /* fail if delete or update */
1247         {
1248             zebra_end_trans(zh);
1249             return ZEBRA_FAIL;
1250         }
1251         action = 1;  /* make it an insert (if it's an update).. */
1252     }
1253     res = buffer_extract_record (zh, rec_buf, rec_len,
1254                                  action == 3 ? 1 : 0 /* delete flag */,
1255                                  0, /* test mode */
1256                                  0, /* recordType */
1257                                  &sysno, 
1258                                  0, /* match */
1259                                  0, /* fname */
1260                            0, /* force update */
1261                                  1  /* allow update */
1262         );
1263     if (action == 1)
1264     {
1265         dict_insert (zh->reg->matchDict, recid_z, sizeof(sysno), &sysno);
1266     }
1267     else if (action == 3)
1268     {
1269         dict_delete (zh->reg->matchDict, recid_z);
1270     }
1271     zebra_end_trans(zh);
1272     return res;
1273 }
1274
1275 int delete_w_handle(const char *info, void *handle)
1276 {
1277     ZebraHandle zh = (ZebraHandle) handle;
1278     ISAM_P pos;
1279     ASSERTZH;
1280
1281     if (*info == sizeof(pos))
1282     {
1283         memcpy (&pos, info+1, sizeof(pos));
1284         isamb_unlink(zh->reg->isamb, pos);
1285     }
1286     return 0;
1287 }
1288
1289 static int delete_SU_handle(void *handle, int ord)
1290 {
1291     ZebraHandle zh = (ZebraHandle) handle;
1292     char ord_buf[20];
1293     int ord_len;
1294
1295     ord_len = key_SU_encode (ord, ord_buf);
1296     ord_buf[ord_len] = '\0';
1297
1298     assert (zh->reg->isamb);
1299     dict_delete_subtree(zh->reg->dict, ord_buf,
1300                         zh, delete_w_handle);
1301     return 0;
1302 }
1303
1304 ZEBRA_RES zebra_drop_database(ZebraHandle zh, const char *db)
1305 {
1306     ZEBRA_RES ret = ZEBRA_OK;
1307     ASSERTZH;
1308     yaz_log(log_level, "zebra_drop_database %s", db);
1309     zebra_clearError(zh);
1310
1311     if (zebra_select_database (zh, db) == ZEBRA_FAIL)
1312         return ZEBRA_FAIL;
1313     if (zebra_begin_trans (zh, 1) == ZEBRA_FAIL)
1314         return ZEBRA_FAIL;
1315     if (zh->reg->isamb)
1316     {
1317         zebraExplain_curDatabase (zh->reg->zei, db);
1318         
1319         zebraExplain_trav_ord(zh->reg->zei, zh, delete_SU_handle);
1320         zebraExplain_removeDatabase(zh->reg->zei, zh);
1321     }
1322     else
1323     {
1324         yaz_log(YLOG_WARN, "drop database only supported for isam:b");
1325         ret = ZEBRA_FAIL;
1326     }
1327     zebra_end_trans (zh);
1328     return ret;
1329 }
1330
1331 ZEBRA_RES zebra_create_database (ZebraHandle zh, const char *db)
1332 {
1333     ASSERTZH;
1334     yaz_log(log_level, "zebra_create_database %s", db);
1335     assert(db);
1336     zebra_clearError(zh);
1337
1338     if (zebra_select_database (zh, db) == ZEBRA_FAIL)
1339         return ZEBRA_FAIL;
1340     if (zebra_begin_trans (zh, 1))
1341         return ZEBRA_FAIL;
1342
1343     /* announce database */
1344     if (zebraExplain_newDatabase (zh->reg->zei, db, 0 
1345                                   /* explainDatabase */))
1346     {
1347         zebra_end_trans (zh);
1348         zebra_setError(zh, YAZ_BIB1_ES_IMMEDIATE_EXECUTION_FAILED, db);
1349         return ZEBRA_FAIL;
1350     }
1351     return zebra_end_trans (zh);
1352 }
1353
1354 int zebra_string_norm (ZebraHandle zh, unsigned reg_id,
1355                        const char *input_str, int input_len,
1356                        char *output_str, int output_len)
1357 {
1358     WRBUF wrbuf;
1359     ASSERTZH;
1360     assert(input_str);
1361     assert(output_str);
1362     yaz_log(log_level, "zebra_string_norm ");
1363     zebra_clearError(zh);
1364     if (!zh->reg->zebra_maps)
1365         return -1;
1366     wrbuf = zebra_replace(zh->reg->zebra_maps, reg_id, "",
1367                           input_str, input_len);
1368     if (!wrbuf)
1369         return -2;
1370     if (wrbuf_len(wrbuf) >= output_len)
1371         return -3;
1372     if (wrbuf_len(wrbuf))
1373         memcpy (output_str, wrbuf_buf(wrbuf), wrbuf_len(wrbuf));
1374     output_str[wrbuf_len(wrbuf)] = '\0';
1375     return wrbuf_len(wrbuf);
1376 }
1377
1378 static void zebra_set_state (ZebraHandle zh, int val, int seqno)
1379 {
1380     char state_fname[256];
1381     char *fname;
1382     long p = getpid();
1383     FILE *f;
1384     ASSERTZH;
1385     yaz_log(log_level, "zebra_set_state v=%d seq=%d", val, seqno);
1386     zebra_clearError(zh);
1387
1388     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1389     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1390     f = fopen (fname, "w");
1391
1392     yaz_log (YLOG_DEBUG, "zebra_set_state: %c %d %ld", val, seqno, p);
1393     fprintf (f, "%c %d %ld\n", val, seqno, p);
1394     fclose (f);
1395     xfree(fname);
1396 }
1397
1398 static void zebra_get_state (ZebraHandle zh, char *val, int *seqno)
1399 {
1400     char state_fname[256];
1401     char *fname;
1402     FILE *f;
1403
1404     ASSERTZH;
1405     yaz_log(log_level, "zebra_get_state ");
1406     zebra_clearError(zh);
1407     sprintf (state_fname, "state.%s.LCK", zh->reg_name);
1408     fname = zebra_mk_fname (res_get(zh->res, "lockDir"), state_fname);
1409     f = fopen (fname, "r");
1410     *val = 'o';
1411     *seqno = 0;
1412
1413     if (f)
1414     {
1415         fscanf (f, "%c %d", val, seqno);
1416         fclose (f);
1417     }
1418     xfree(fname);
1419 }
1420
1421 ZEBRA_RES zebra_begin_read (ZebraHandle zh)
1422 {
1423     return zebra_begin_trans(zh, 0);
1424 }
1425
1426 ZEBRA_RES zebra_end_read (ZebraHandle zh)
1427 {
1428     return zebra_end_trans(zh);
1429 }
1430
1431 static void read_res_for_transaction(ZebraHandle zh)
1432 {
1433     const char *group = res_get(zh->res, "group");
1434     const char *v;
1435     /* FIXME - do we still use groups ?? */
1436     
1437     zh->m_group = group;
1438     v = res_get_prefix(zh->res, "followLinks", group, "1");
1439     zh->m_follow_links = atoi(v);
1440
1441     zh->m_record_id = res_get_prefix(zh->res, "recordId", group, 0);
1442     zh->m_record_type = res_get_prefix(zh->res, "recordType", group, 0);
1443
1444     v = res_get_prefix(zh->res, "storeKeys", group, "1");
1445     zh->m_store_keys = atoi(v);
1446
1447     v = res_get_prefix(zh->res, "storeData", group, "1");
1448     zh->m_store_data = atoi(v);
1449
1450     v = res_get_prefix(zh->res, "explainDatabase", group, "0");
1451     zh->m_explain_database = atoi(v);
1452
1453     v = res_get_prefix(zh->res, "openRW", group, "1");
1454     zh->m_flag_rw = atoi(v);
1455
1456     v = res_get_prefix(zh->res, "fileVerboseLimit", group, "100000");
1457     zh->m_file_verbose_limit = atoi(v);
1458 }
1459
1460 ZEBRA_RES zebra_begin_trans(ZebraHandle zh, int rw)
1461 {
1462     ASSERTZH;
1463     zebra_select_default_database(zh);
1464     if (!zh->res)
1465     {
1466         zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1467                        "zebra_begin_trans: no database selected");
1468         return ZEBRA_FAIL;
1469     }
1470     ASSERTZHRES;
1471     yaz_log(log_level, "zebra_begin_trans rw=%d",rw);
1472
1473     if (zh->user_perm)
1474     {
1475         if (rw && !strchr(zh->user_perm, 'w'))
1476         {
1477             zebra_setError(
1478                 zh,
1479                 YAZ_BIB1_ES_PERMISSION_DENIED_ON_ES_CANNOT_MODIFY_OR_DELETE,
1480                 0);
1481             return ZEBRA_FAIL;
1482         }
1483     }
1484
1485     assert (zh->res);
1486     if (rw)
1487     {
1488         int pass;
1489         int seqno = 0;
1490         char val = '?';
1491         const char *rval = 0;
1492         
1493         (zh->trans_no++);
1494         if (zh->trans_w_no)
1495         {
1496             read_res_for_transaction(zh);
1497             return 0;
1498         }
1499         if (zh->trans_no != 1)
1500         {
1501             zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1502                            "zebra_begin_trans: no write trans within read");
1503             return ZEBRA_FAIL;
1504         }
1505         if (zh->reg)
1506         {
1507             resultSetInvalidate (zh);
1508             zebra_register_close (zh->service, zh->reg);
1509         }
1510         zh->trans_w_no = zh->trans_no;
1511
1512         zebra_clearError(zh);
1513         
1514         zh->records_inserted = 0;
1515         zh->records_updated = 0;
1516         zh->records_deleted = 0;
1517         zh->records_processed = 0;
1518         
1519 #if HAVE_SYS_TIMES_H
1520         times (&zh->tms1);
1521 #endif
1522         /* lock */
1523         if (zh->shadow_enable)
1524             rval = res_get (zh->res, "shadow");
1525         
1526         for (pass = 0; pass < 2; pass++)
1527         {
1528             if (rval)
1529             {
1530                 zebra_lock_r (zh->lock_normal);
1531                 zebra_lock_w (zh->lock_shadow);
1532             }
1533             else
1534             {
1535                 zebra_lock_w (zh->lock_normal);
1536                 zebra_lock_w (zh->lock_shadow);
1537             }
1538             
1539             zebra_get_state (zh, &val, &seqno);
1540             if (val == 'c')
1541             {
1542                 yaz_log (YLOG_WARN, "previous transaction didn't finish commit");
1543                 zebra_unlock (zh->lock_shadow);
1544                 zebra_unlock (zh->lock_normal);
1545                 zebra_commit (zh);
1546                 continue;
1547             }
1548             else if (val == 'd')
1549             {
1550                 if (rval)
1551                 {
1552                     BFiles bfs = bfs_create (res_get (zh->res, "shadow"),
1553                                              zh->path_reg);
1554                     yaz_log (YLOG_WARN, "previous transaction didn't reach commit");
1555                     bf_commitClean (bfs, rval);
1556                     bfs_destroy (bfs);
1557             }
1558                 else
1559                 {
1560                     yaz_log (YLOG_WARN, "your previous transaction didn't finish");
1561                 }
1562             }
1563             break;
1564         }
1565         if (pass == 2)
1566         {
1567             yaz_log (YLOG_FATAL, "zebra_begin_trans couldn't finish commit");
1568             abort();
1569             return ZEBRA_FAIL;
1570         }
1571         zebra_set_state (zh, 'd', seqno);
1572         
1573         zh->reg = zebra_register_open (zh->service, zh->reg_name,
1574                                        1, rval ? 1 : 0, zh->res,
1575                                        zh->path_reg);
1576         if (zh->reg)
1577             zh->reg->seqno = seqno;
1578         else
1579         {
1580             zebra_set_state (zh, 'o', seqno);
1581             
1582             zebra_unlock (zh->lock_shadow);
1583             zebra_unlock (zh->lock_normal);
1584
1585             zh->trans_no--;
1586             zh->trans_w_no = 0;
1587
1588             zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1589                            "zebra_begin_trans: cannot open register");
1590             yaz_log(YLOG_FATAL, "%s", zh->errString);
1591             return ZEBRA_FAIL;
1592         }
1593     }
1594     else
1595     {
1596         int dirty = 0;
1597         char val;
1598         int seqno;
1599         
1600         (zh->trans_no)++;
1601         
1602         if (zh->trans_no != 1)
1603         {
1604             zebra_flush_reg (zh);
1605             return ZEBRA_OK;
1606         }
1607         zebra_clearError(zh);
1608 #if HAVE_SYS_TIMES_H
1609         times (&zh->tms1);
1610 #endif
1611         if (!zh->res)
1612         {
1613             (zh->trans_no)--;
1614             zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
1615             return ZEBRA_FAIL;
1616         }
1617         if (!zh->lock_normal || !zh->lock_shadow)
1618         {
1619             (zh->trans_no)--;
1620             zh->errCode = YAZ_BIB1_TEMPORARY_SYSTEM_ERROR;
1621             return ZEBRA_FAIL;
1622         }
1623         zebra_get_state (zh, &val, &seqno);
1624         if (val == 'd')
1625             val = 'o';
1626         
1627         if (!zh->reg)
1628             dirty = 1;
1629         else if (seqno != zh->reg->seqno)
1630         {
1631             yaz_log (YLOG_DEBUG, "reopen seqno cur/old %d/%d",
1632                      seqno, zh->reg->seqno);
1633             dirty = 1;
1634         }
1635         else if (zh->reg->last_val != val)
1636         {
1637             yaz_log (YLOG_DEBUG, "reopen last cur/old %d/%d",
1638                      val, zh->reg->last_val);
1639             dirty = 1;
1640         }
1641         if (!dirty)
1642             return ZEBRA_OK;
1643         
1644         if (val == 'c')
1645             zebra_lock_r (zh->lock_shadow);
1646         else
1647             zebra_lock_r (zh->lock_normal);
1648         
1649         if (zh->reg)
1650         {
1651             resultSetInvalidate (zh);
1652             zebra_register_close (zh->service, zh->reg);
1653         }
1654         zh->reg = zebra_register_open (zh->service, zh->reg_name,
1655                                        0, val == 'c' ? 1 : 0,
1656                                        zh->res, zh->path_reg);
1657         if (!zh->reg)
1658         {
1659             zebra_unlock (zh->lock_normal);
1660             zebra_unlock (zh->lock_shadow);
1661             zh->trans_no--;
1662             zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
1663             return ZEBRA_FAIL;
1664         }
1665         zh->reg->last_val = val;
1666         zh->reg->seqno = seqno;
1667     }
1668     read_res_for_transaction(zh);
1669     return ZEBRA_OK;
1670 }
1671
1672 ZEBRA_RES zebra_end_trans (ZebraHandle zh)
1673 {
1674     ZebraTransactionStatus dummy;
1675     ASSERTZH;
1676     yaz_log(log_level, "zebra_end_trans");
1677     return zebra_end_transaction(zh, &dummy);
1678 }
1679
1680 ZEBRA_RES zebra_end_transaction (ZebraHandle zh, ZebraTransactionStatus *status)
1681 {
1682     char val;
1683     int seqno;
1684     const char *rval;
1685
1686     ASSERTZH;
1687     assert(status);
1688     yaz_log(log_level, "zebra_end_transaction");
1689
1690     status->processed = 0;
1691     status->inserted  = 0;
1692     status->updated   = 0;
1693     status->deleted   = 0;
1694     status->utime     = 0;
1695     status->stime     = 0;
1696
1697     if (!zh->res || !zh->reg)
1698     {
1699         zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1700                        "zebra_end_trans: no open transaction");
1701         return ZEBRA_FAIL;
1702     }
1703     if (zh->trans_no != zh->trans_w_no)
1704     {
1705         zh->trans_no--;
1706         if (zh->trans_no != 0)
1707             return ZEBRA_OK;
1708
1709         /* release read lock */
1710
1711         zebra_unlock (zh->lock_normal);
1712         zebra_unlock (zh->lock_shadow);
1713     }
1714     else
1715     {   /* release write lock */
1716         zh->trans_no--;
1717         zh->trans_w_no = 0;
1718         
1719         yaz_log (YLOG_DEBUG, "zebra_end_trans");
1720         rval = res_get (zh->res, "shadow");
1721         
1722         zebraExplain_runNumberIncrement (zh->reg->zei, 1);
1723         
1724         zebra_flush_reg (zh);
1725         
1726         resultSetInvalidate (zh);
1727
1728         zebra_register_close (zh->service, zh->reg);
1729         zh->reg = 0;
1730         
1731         yaz_log (YLOG_LOG, "Records: "ZINT_FORMAT" i/u/d "
1732                         ZINT_FORMAT"/"ZINT_FORMAT"/"ZINT_FORMAT, 
1733                  zh->records_processed, zh->records_inserted,
1734                  zh->records_updated, zh->records_deleted);
1735         
1736         status->processed = (int) zh->records_processed;
1737         status->inserted = (int) zh->records_inserted;
1738         status->updated = (int) zh->records_updated;
1739         status->deleted = (int) zh->records_deleted;
1740         
1741         zebra_get_state (zh, &val, &seqno);
1742         if (val != 'd')
1743         {
1744             BFiles bfs = bfs_create (rval, zh->path_reg);
1745             yaz_log (YLOG_DEBUG, "deleting shadow val=%c", val);
1746             bf_commitClean (bfs, rval);
1747             bfs_destroy (bfs);
1748         }
1749         if (!rval)
1750             seqno++;
1751         zebra_set_state (zh, 'o', seqno);
1752         
1753         zebra_unlock (zh->lock_shadow);
1754         zebra_unlock (zh->lock_normal);
1755         
1756     }
1757 #if HAVE_SYS_TIMES_H
1758     times (&zh->tms2);
1759     yaz_log (log_level, "user/system: %ld/%ld",
1760           (long) (zh->tms2.tms_utime - zh->tms1.tms_utime),
1761           (long) (zh->tms2.tms_stime - zh->tms1.tms_stime));
1762     
1763     status->utime = (long) (zh->tms2.tms_utime - zh->tms1.tms_utime);
1764     status->stime = (long) (zh->tms2.tms_stime - zh->tms1.tms_stime);
1765 #endif
1766     return ZEBRA_OK;
1767 }
1768
1769 int zebra_repository_update (ZebraHandle zh, const char *path)
1770 {
1771     ASSERTZH;
1772     assert(path);
1773     zebra_clearError(zh);
1774     yaz_log (log_level, "updating %s", path);
1775     repositoryUpdate (zh, path);
1776     return zh->errCode;
1777 }
1778
1779 int zebra_repository_delete (ZebraHandle zh, const char *path)
1780 {
1781     ASSERTZH;
1782     assert(path);
1783     zebra_clearError(zh);
1784     yaz_log (log_level, "deleting %s", path);
1785     repositoryDelete (zh, path);
1786     return zh->errCode;
1787 }
1788
1789 int zebra_repository_show (ZebraHandle zh, const char *path)
1790 {
1791     ASSERTZH;
1792     assert(path);
1793     yaz_log(log_level, "zebra_repository_show");
1794     zebra_clearError(zh);
1795     repositoryShow (zh, path);
1796     return zh->errCode;
1797 }
1798
1799 static int zebra_commit_ex(ZebraHandle zh, int clean_only)
1800 {
1801     int seqno;
1802     char val;
1803     const char *rval;
1804     BFiles bfs;
1805     ASSERTZH;
1806     zebra_clearError(zh);
1807
1808     zebra_select_default_database(zh);
1809     if (!zh->res)
1810     {
1811         zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
1812         return -1;
1813     }
1814     rval = res_get (zh->res, "shadow");    
1815     if (!rval)
1816     {
1817         yaz_log (YLOG_WARN, "Cannot perform commit - No shadow area defined");
1818         return 0;
1819     }
1820
1821     zebra_lock_w (zh->lock_normal);
1822     zebra_lock_r (zh->lock_shadow);
1823
1824     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1825
1826     zebra_get_state (zh, &val, &seqno);
1827
1828     if (rval && *rval)
1829         bf_cache (bfs, rval);
1830     if (bf_commitExists (bfs))
1831     {
1832         if (clean_only)
1833             zebra_set_state (zh, 'd', seqno);
1834         else
1835         {
1836             zebra_set_state (zh, 'c', seqno);
1837             
1838             yaz_log (YLOG_DEBUG, "commit start");
1839             bf_commitExec (bfs);
1840 #ifndef WIN32
1841             sync ();
1842 #endif
1843         }
1844         yaz_log (YLOG_DEBUG, "commit clean");
1845         bf_commitClean (bfs, rval);
1846         seqno++;
1847         zebra_set_state (zh, 'o', seqno);
1848     }
1849     else
1850     {
1851         yaz_log (log_level, "nothing to commit");
1852     }
1853     bfs_destroy (bfs);
1854
1855     zebra_unlock (zh->lock_shadow);
1856     zebra_unlock (zh->lock_normal);
1857     return 0;
1858 }
1859
1860 ZEBRA_RES zebra_clean(ZebraHandle zh)
1861 {
1862     ASSERTZH;
1863     yaz_log(log_level, "zebra_clean");
1864     return zebra_commit_ex(zh, 1);
1865 }
1866
1867 ZEBRA_RES zebra_commit(ZebraHandle zh)
1868 {
1869     ASSERTZH;
1870     yaz_log(log_level, "zebra_commit");
1871     return zebra_commit_ex(zh, 0);
1872 }
1873
1874 ZEBRA_RES zebra_init(ZebraHandle zh)
1875 {
1876     const char *rval;
1877     BFiles bfs = 0;
1878     ASSERTZH;
1879     yaz_log(log_level, "zebra_init");
1880     zebra_clearError(zh);
1881
1882     zebra_select_default_database(zh);
1883     if (!zh->res)
1884     {
1885         zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR,
1886                        "cannot select default database");
1887         return ZEBRA_FAIL;
1888     }
1889     rval = res_get (zh->res, "shadow");
1890
1891     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1892     if (!bfs)
1893     {
1894         zebra_setError(zh, YAZ_BIB1_TEMPORARY_SYSTEM_ERROR, "bfs_create");
1895         return ZEBRA_FAIL;
1896     }
1897     if (rval && *rval)
1898         bf_cache (bfs, rval);
1899     
1900     bf_reset (bfs);
1901     bfs_destroy (bfs);
1902     zebra_set_state (zh, 'o', 0);
1903     return ZEBRA_OK;
1904 }
1905
1906 ZEBRA_RES zebra_compact(ZebraHandle zh)
1907 {
1908     BFiles bfs;
1909     ASSERTZH;
1910     yaz_log(log_level, "zebra_compact");
1911     zebra_clearError(zh);
1912     if (!zh->res)
1913     {
1914         zh->errCode = YAZ_BIB1_DATABASE_UNAVAILABLE;
1915         return ZEBRA_FAIL;
1916     }
1917     bfs = bfs_create (res_get (zh->res, "register"), zh->path_reg);
1918     inv_compact (bfs);
1919     bfs_destroy (bfs);
1920     return ZEBRA_OK;
1921 }
1922
1923 void zebra_result(ZebraHandle zh, int *code, char **addinfo)
1924 {
1925     ASSERTZH;
1926     yaz_log(log_level, "zebra_result");
1927     *code = zh->errCode;
1928     *addinfo = zh->errString;
1929 }
1930
1931 void zebra_shadow_enable(ZebraHandle zh, int value)
1932 {
1933     ASSERTZH;
1934     yaz_log(log_level, "zebra_shadow_enable");
1935     zebra_clearError(zh);
1936     zh->shadow_enable = value;
1937 }
1938
1939 ZEBRA_RES zebra_octet_term_encoding(ZebraHandle zh, const char *encoding)
1940 {
1941     ASSERTZH;
1942     assert(encoding);
1943     yaz_log(log_level, "zebra_octet_term_encoding");
1944     zebra_clearError(zh);
1945
1946     if (zh->iconv_to_utf8 != 0)
1947         yaz_iconv_close(zh->iconv_to_utf8);
1948     if (zh->iconv_from_utf8 != 0)
1949         yaz_iconv_close(zh->iconv_from_utf8);
1950     
1951     zh->iconv_to_utf8 =
1952         yaz_iconv_open ("UTF-8", encoding);
1953     if (zh->iconv_to_utf8 == 0)
1954         yaz_log (YLOG_WARN, "iconv: %s to UTF-8 unsupported", encoding);
1955     zh->iconv_from_utf8 =
1956         yaz_iconv_open (encoding, "UTF-8");
1957     if (zh->iconv_to_utf8 == 0)
1958         yaz_log (YLOG_WARN, "iconv: UTF-8 to %s unsupported", encoding);
1959
1960     return ZEBRA_OK;
1961 }
1962
1963 ZEBRA_RES zebra_record_encoding (ZebraHandle zh, const char *encoding)
1964 {
1965     ASSERTZH;
1966     yaz_log(log_level, "zebra_record_encoding");
1967     zebra_clearError(zh);
1968     xfree(zh->record_encoding);
1969     zh->record_encoding = 0;
1970     if (encoding)
1971         zh->record_encoding = xstrdup (encoding);
1972     return ZEBRA_OK;
1973 }
1974
1975 void zebra_set_resource(ZebraHandle zh, const char *name, const char *value)
1976 {
1977     ASSERTZH;
1978     assert(name);
1979     assert(value);
1980     yaz_log(log_level, "zebra_set_resource %s:%s", name, value);
1981     zebra_clearError(zh);
1982     res_set(zh->res, name, value);
1983 }
1984
1985 const char *zebra_get_resource(ZebraHandle zh,
1986                                const char *name, const char *defaultvalue)
1987 {
1988     const char *v;
1989     ASSERTZH;
1990     assert(name);
1991     assert(defaultvalue);
1992     v = res_get_def (zh->res, name, (char *)defaultvalue);
1993     zebra_clearError(zh);
1994     yaz_log(log_level, "zebra_get_resource %s:%s", name, v);
1995     return v;
1996 }
1997
1998 /* moved from zebra_api_ext.c by pop */
1999 /* FIXME: Should this really be public??? -Heikki */
2000
2001 int zebra_trans_no (ZebraHandle zh)
2002 {
2003     ASSERTZH;
2004     yaz_log(log_level, "zebra_trans_no");
2005     return zh->trans_no;
2006 }
2007
2008 int zebra_get_shadow_enable (ZebraHandle zh)
2009 {
2010     ASSERTZH;
2011     yaz_log(log_level, "zebra_get_shadow_enable");
2012     return zh->shadow_enable;
2013 }
2014
2015 void zebra_set_shadow_enable (ZebraHandle zh, int value)
2016 {
2017     ASSERTZH;
2018     yaz_log(log_level, "zebra_set_shadow_enable %d",value);
2019     zh->shadow_enable = value;
2020 }
2021
2022 /* Used by Perl API.. Added the record buffer dup to zebra_records_retrieve
2023    so that it's identicical to the original api_records_retrieve */
2024 void api_records_retrieve (ZebraHandle zh, ODR stream,
2025                            const char *setname, Z_RecordComposition *comp,
2026                            oid_value input_format, int num_recs,
2027                            ZebraRetrievalRecord *recs)
2028 {
2029     zebra_records_retrieve(zh, stream, setname, comp, input_format,
2030                            num_recs, recs);
2031 }
2032
2033 /* ---------------------------------------------------------------------------
2034   Record insert(=update), delete 
2035
2036   If sysno is provided, then it's used to identify the record.
2037   If not, and match_criteria is provided, then sysno is guessed
2038   If not, and a record is provided, then sysno is got from there
2039 NOTE: Now returns 0 at success and updates sysno, which is an int*
2040   20-jun-2003 Heikki
2041 */
2042
2043 int zebra_add_record(ZebraHandle zh,
2044                      const char *buf, int buf_size)
2045 {
2046     SYSNO sysno = 0;
2047     return zebra_update_record(zh, 0, &sysno, 0, 0, buf, buf_size, 0);
2048 }
2049
2050 ZEBRA_RES zebra_insert_record (ZebraHandle zh, 
2051                                const char *recordType,
2052                                SYSNO *sysno, const char *match,
2053                                const char *fname,
2054                                const char *buf, int buf_size, int force_update)
2055 {
2056     ZEBRA_RES res;
2057     ASSERTZH;
2058     assert(sysno);
2059     assert(buf);
2060     yaz_log(log_level, "zebra_insert_record sysno=" ZINT_FORMAT, *sysno);
2061
2062     if (buf_size < 1)
2063         buf_size = strlen(buf);
2064
2065     if (zebra_begin_trans(zh, 1) == ZEBRA_FAIL)
2066         return ZEBRA_FAIL;
2067     res = buffer_extract_record (zh, buf, buf_size, 
2068                                  0, /* delete_flag  */
2069                                  0, /* test_mode */
2070                                  recordType,
2071                                  sysno,   
2072                                  match, fname,
2073                                  0, 
2074                                  0); /* allow_update */
2075     zebra_end_trans(zh); 
2076     return res; 
2077 }
2078
2079 ZEBRA_RES zebra_update_record (ZebraHandle zh, 
2080                                const char *recordType,
2081                                SYSNO* sysno, const char *match,
2082                                const char *fname,
2083                                const char *buf, int buf_size,
2084                                int force_update)
2085 {
2086     ZEBRA_RES res;
2087     ASSERTZH;
2088     assert(sysno);
2089     assert(buf);
2090
2091     yaz_log(log_level, "zebra_update_record sysno=" ZINT_FORMAT, *sysno);
2092
2093     if (buf_size < 1) buf_size = strlen(buf);
2094
2095     if (zebra_begin_trans(zh, 1) == ZEBRA_FAIL)
2096         return ZEBRA_FAIL;
2097     res = buffer_extract_record (zh, buf, buf_size, 
2098                                  0, /* delete_flag */
2099                                  0, /* test_mode */
2100                                  recordType,
2101                                  sysno,   
2102                                  match, fname,
2103                                  force_update, 
2104                                  1); /* allow_update */
2105     zebra_end_trans(zh); 
2106     return res; 
2107 }
2108
2109 ZEBRA_RES zebra_delete_record (ZebraHandle zh, 
2110                                const char *recordType,
2111                                SYSNO *sysno, const char *match,
2112                                const char *fname,
2113                                const char *buf, int buf_size,
2114                                int force_update) 
2115 {
2116     ZEBRA_RES res;
2117     ASSERTZH;
2118     assert(sysno);
2119     assert(buf);
2120     yaz_log(log_level, "zebra_delete_record sysno=" ZINT_FORMAT, *sysno);
2121
2122     if (buf_size < 1) buf_size = strlen(buf);
2123
2124     if (zebra_begin_trans(zh, 1) == ZEBRA_FAIL)
2125         return ZEBRA_FAIL;
2126     res = buffer_extract_record (zh, buf, buf_size,
2127                                  1, /* delete_flag */
2128                                  0, /* test_mode */
2129                                  recordType,
2130                                  sysno,
2131                                  match,fname,
2132                                  force_update,
2133                                  1); /* allow_update */
2134     zebra_end_trans(zh);
2135     return res;
2136 }
2137
2138 /* ---------------------------------------------------------------------------
2139   Searching 
2140 */
2141
2142 ZEBRA_RES zebra_search_PQF(ZebraHandle zh, const char *pqf_query,
2143                            const char *setname, zint *hits)
2144 {
2145     zint lhits = 0;
2146     ZEBRA_RES res = ZEBRA_OK;
2147     Z_RPNQuery *query;
2148     ODR odr = odr_createmem(ODR_ENCODE);
2149     ASSERTZH;
2150     assert(pqf_query);
2151     assert(setname);
2152
2153     yaz_log(log_level, "zebra_search_PQF s=%s q=%s", setname, pqf_query);
2154     
2155     query = p_query_rpn (odr, PROTO_Z3950, pqf_query);
2156     
2157     if (!query)
2158     {
2159         yaz_log (YLOG_WARN, "bad query %s\n", pqf_query);
2160         zh->errCode = YAZ_BIB1_MALFORMED_QUERY;
2161         res = ZEBRA_FAIL;
2162     }
2163     else
2164         res = zebra_search_RPN(zh, odr, query, setname, &lhits);
2165     
2166     odr_destroy(odr);
2167
2168     yaz_log(log_level, "Hits: " ZINT_FORMAT, lhits);
2169
2170     if (hits)
2171         *hits = lhits;
2172
2173     return res;
2174 }
2175
2176 /* ---------------------------------------------------------------------------
2177   Sort - a simplified interface, with optional read locks.
2178 */
2179 int zebra_sort_by_specstr (ZebraHandle zh, ODR stream,
2180                            const char *sort_spec,
2181                            const char *output_setname,
2182                            const char **input_setnames) 
2183 {
2184     int num_input_setnames = 0;
2185     int sort_status = 0;
2186     Z_SortKeySpecList *sort_sequence;
2187     ASSERTZH;
2188     assert(stream);
2189     assert(sort_spec);
2190     assert(output_setname);
2191     assert(input_setnames);
2192     sort_sequence = yaz_sort_spec (stream, sort_spec);
2193     yaz_log(log_level, "sort (FIXME) ");
2194     if (!sort_sequence)
2195     {
2196         yaz_log(YLOG_WARN, "invalid sort specs '%s'", sort_spec);
2197         zh->errCode = YAZ_BIB1_CANNOT_SORT_ACCORDING_TO_SEQUENCE;
2198         return -1;
2199     }
2200     
2201     /* we can do this, since the perl typemap code for char** will 
2202        put a NULL at the end of list */
2203     while (input_setnames[num_input_setnames]) num_input_setnames++;
2204
2205     if (zebra_begin_read (zh))
2206         return -1;
2207     
2208     resultSetSort (zh, stream->mem, num_input_setnames, input_setnames,
2209                    output_setname, sort_sequence, &sort_status);
2210     
2211     zebra_end_read(zh);
2212     return sort_status;
2213 }
2214
2215 /* ---------------------------------------------------------------------------
2216   Get BFS for Zebra system (to make alternative storage methods)
2217 */
2218 struct BFiles_struct *zebra_get_bfs(ZebraHandle zh)
2219 {
2220     if (zh && zh->reg)
2221         return zh->reg->bfs;
2222     return 0;
2223 }
2224
2225
2226 /* ---------------------------------------------------------------------------
2227   Set limit for search/scan
2228 */
2229 ZEBRA_RES zebra_set_limit(ZebraHandle zh, int complement_flag, zint *ids)
2230 {
2231     ASSERTZH;
2232     zebra_limit_destroy(zh->m_limit);
2233     zh->m_limit = zebra_limit_create(complement_flag, ids);
2234     return ZEBRA_OK;
2235 }
2236
2237 /*
2238   Set Error code + addinfo
2239 */
2240 void zebra_setError(ZebraHandle zh, int code, const char *addinfo)
2241 {
2242     zh->errCode = code;
2243     nmem_reset(zh->nmem_error);
2244     zh->errString = addinfo ? nmem_strdup(zh->nmem_error, addinfo) : 0;
2245 }
2246
2247 void zebra_setError_zint(ZebraHandle zh, int code, zint i)
2248 {
2249     char vstr[60];
2250     sprintf(vstr, ZINT_FORMAT, i);
2251
2252     zh->errCode = code;
2253     nmem_reset(zh->nmem_error);
2254     zh->errString = nmem_strdup(zh->nmem_error, vstr);
2255 }
2256