When dealing with records, odr_choice_enable_bias function is used to
[ir-tcl-moved-to-github.git] / ir-tcl.c
1 /*
2  * IR toolkit for tcl/tk
3  * (c) Index Data 1995-1996
4  * See the file LICENSE for details.
5  * Sebastian Hammer, Adam Dickmeiss
6  *
7  * $Log: ir-tcl.c,v $
8  * Revision 1.96  1996-10-08 13:02:50  adam
9  * When dealing with records, odr_choice_enable_bias function is used to
10  * prevent decoding of externals.
11  *
12  * Revision 1.95  1996/09/13  10:51:49  adam
13  * Bug fix: ir_tcl_select_set called Tcl_GetFile at disconnect.
14  *
15  * Revision 1.94  1996/08/21  13:32:53  adam
16  * Implemented saveFile method and extended loadFile method to work with it.
17  *
18  * Revision 1.93  1996/08/16  15:07:45  adam
19  * First work on Explain.
20  *
21  * Revision 1.92  1996/08/09  15:33:07  adam
22  * Modified the code to use tk4.1/tcl7.5 patch level 1. The time-driven
23  * polling is no longer activated on Windows since asynchrounous I/O works
24  * better.
25  *
26  * Revision 1.91  1996/07/03  13:31:11  adam
27  * The xmalloc/xfree functions from YAZ are used to manage memory.
28  *
29  * Revision 1.90  1996/06/27  14:21:00  adam
30  * Yet another Windows port.
31  *
32  * Revision 1.89  1996/06/11  15:27:15  adam
33  * Event type set to connect a little earlier in the do_connect function.
34  *
35  * Revision 1.88  1996/06/03  09:04:22  adam
36  * Changed a few logf calls.
37  *
38  * Revision 1.87  1996/05/29  06:37:51  adam
39  * Function ir_tcl_get_grs_r enhanced so that specific elements can be
40  * extracted.
41  *
42  * Revision 1.86  1996/03/20 13:54:04  adam
43  * The Tcl_File structure is only manipulated in the Tk-event interface
44  * in tkinit.c.
45  *
46  * Revision 1.85  1996/03/15  11:15:48  adam
47  * Modified to use new prototypes for p_query_rpn and p_query_scan.
48  *
49  * Revision 1.84  1996/03/07  12:42:49  adam
50  * Better logging when callback is invoked.
51  *
52  * Revision 1.83  1996/03/05  09:21:09  adam
53  * Bug fix: memory used by GRS records wasn't freed.
54  * Rewrote some of the error handling code - the connection is always
55  * closed before failback is called.
56  * If failback is defined the send APDU methods (init, search, ...) will
57  * return OK but invoke failback (as is the case if the write operation
58  * fails).
59  * Bug fix: ref_count in assoc object could grow if fraction of PDU was
60  * read.
61  *
62  * Revision 1.82  1996/02/29  15:30:21  adam
63  * Export of IrTcl functionality to extensions.
64  *
65  * Revision 1.81  1996/02/26  18:38:32  adam
66  * Work on export of set methods.
67  *
68  * Revision 1.80  1996/02/23  17:31:39  adam
69  * More functions made available to the wais tcl extension.
70  *
71  * Revision 1.79  1996/02/23  13:41:38  adam
72  * Work on public access to simple ir class system.
73  *
74  * Revision 1.78  1996/02/21  10:16:08  adam
75  * Simplified select handling. Only one function ir_tcl_select_set has
76  * to be externally defined.
77  *
78  * Revision 1.77  1996/02/20  17:52:58  adam
79  * Uses the YAZ oid system to name record syntax object identifiers.
80  *
81  * Revision 1.76  1996/02/20  16:09:51  adam
82  * Bug fix: didn't set element set names stamp correctly on result
83  * set records when element set names were set to the empty string.
84  *
85  * Revision 1.75  1996/02/19  15:41:53  adam
86  * Better log messages.
87  * Minor improvement of connect method.
88  *
89  * Revision 1.74  1996/02/05  17:58:03  adam
90  * Ported ir-tcl to use the beta releases of tcl7.5/tk4.1.
91  *
92  * Revision 1.73  1996/01/29  11:35:19  adam
93  * Bug fix: cs_type member renamed to comstackType to avoid conflict with
94  * cs_type macro defined by YAZ.
95  *
96  * Revision 1.72  1996/01/19  17:45:34  quinn
97  * Added debugging output
98  *
99  * Revision 1.71  1996/01/19  16:22:38  adam
100  * New method: apduDump - returns information about last incoming APDU.
101  *
102  * Revision 1.70  1996/01/10  09:18:34  adam
103  * PDU specific callbacks implemented: initRespnse, searchResponse,
104  *  presentResponse and scanResponse.
105  * Bug fix in the command line shell (tclmain.c) - discovered on OSF/1.
106  *
107  * Revision 1.69  1996/01/04  16:12:12  adam
108  * Setting PDUType renamed to eventType.
109  *
110  * Revision 1.68  1996/01/04  11:05:22  adam
111  * New setting: PDUType - returns type of last PDU returned from the target.
112  * Fixed a bug in configure/Makefile.
113  *
114  * Revision 1.67  1996/01/03  09:00:51  adam
115  * Updated to use new version of Yaz (names changed to avoid C++ conflict).
116  *
117  * Revision 1.66  1995/11/28  17:26:39  adam
118  * Removed Carriage return from ir-tcl.c!
119  * Removed misc. debug logs.
120  *
121  * Revision 1.65  1995/11/28  13:53:00  quinn
122  * Windows port.
123  *
124  * Revision 1.64  1995/11/13  15:39:18  adam
125  * Bug fix: {small,medium}SetElementSetNames weren't set correctly.
126  * Bug fix: idAuthentication weren't set correctly.
127  *
128  * Revision 1.63  1995/11/13  09:55:39  adam
129  * Multiple records at a position in a result-set with differnt
130  * element specs.
131  *
132  * Revision 1.62  1995/10/18  17:20:33  adam
133  * Work on target setup in client.tcl.
134  *
135  * Revision 1.61  1995/10/18  16:42:42  adam
136  * New settings: smallSetElementSetNames and mediumSetElementSetNames.
137  *
138  * Revision 1.60  1995/10/18  15:43:31  adam
139  * In search: mediumSetElementSetNames and smallSetElementSetNames are
140  * set to elementSetNames.
141  *
142  * Revision 1.59  1995/10/17  12:18:58  adam
143  * Bug fix: when target connection closed, the connection was not
144  * properly reestablished.
145  *
146  * Revision 1.58  1995/10/16  17:00:55  adam
147  * New setting: elementSetNames.
148  * Various client improvements. Medium presentation format looks better.
149  *
150  * Revision 1.57  1995/09/21  13:11:51  adam
151  * Support of dynamic loading.
152  * Test script uses load command if necessary.
153  *
154  * Revision 1.56  1995/08/29  15:30:14  adam
155  * Work on GRS records.
156  *
157  * Revision 1.55  1995/08/28  09:43:25  adam
158  * Minor changes. configure only searches for yaz beta 3 and versions after
159  * that.
160  *
161  * Revision 1.54  1995/08/24  12:25:16  adam
162  * Modified to work with yaz 1.0b3.
163  *
164  * Revision 1.53  1995/08/04  12:49:26  adam
165  * Bug fix: reading uninitialized variable p.
166  *
167  * Revision 1.52  1995/08/04  11:32:38  adam
168  * More work on output queue. Memory related routines moved
169  * to mem.c
170  *
171  * Revision 1.51  1995/08/03  13:22:54  adam
172  * Request queue.
173  *
174  * Revision 1.50  1995/07/20  08:09:49  adam
175  * client.tcl: Targets removed from hotTargets list when targets
176  *  are removed/modified.
177  * ir-tcl.c: More work on triggerResourceControl.
178  *
179  * Revision 1.49  1995/06/30  12:39:21  adam
180  * Bug fix: loadFile didn't set record type.
181  * The MARC routines are a little less strict in the interpretation.
182  * Script display.tcl replaces the old marc.tcl.
183  * New interactive script: shell.tcl.
184  *
185  * Revision 1.48  1995/06/27  19:03:50  adam
186  * Bug fix in do_present in ir-tcl.c: p->set_child member weren't set.
187  * nextResultSetPosition used instead of setOffset.
188  *
189  * Revision 1.47  1995/06/25  10:25:04  adam
190  * Working on triggerResourceControl. Description of compile/install
191  * procedure moved to ir-tcl.sgml.
192  *
193  * Revision 1.46  1995/06/22  13:15:06  adam
194  * Feature: SUTRS. Setting getSutrs implemented.
195  * Work on display formats.
196  * Preferred record syntax can be set by the user.
197  *
198  * Revision 1.45  1995/06/20  08:07:30  adam
199  * New setting: failInfo.
200  * Working on better cancel mechanism.
201  *
202  * Revision 1.44  1995/06/19  17:01:20  adam
203  * Minor changes.
204  *
205  * Revision 1.43  1995/06/19  13:06:08  adam
206  * New define: IR_TCL_VERSION.
207  *
208  * Revision 1.42  1995/06/19  08:08:52  adam
209  * client.tcl: hotTargets now contain both database and target name.
210  * ir-tcl.c: setting protocol edited. Errors in callbacks are logged
211  * by logf(LOG_WARN, ...) calls.
212  *
213  * Revision 1.41  1995/06/16  12:28:16  adam
214  * Implemented preferredRecordSyntax.
215  * Minor changes in diagnostic handling.
216  * Record list deleted when connection closes.
217  *
218  * Revision 1.40  1995/06/14  13:37:18  adam
219  * Setting recordType implemented.
220  * Setting implementationVersion implemented.
221  * Settings implementationId / implementationName edited.
222  *
223  * Revision 1.39  1995/06/08  10:26:32  adam
224  * Bug fix in ir_strdup.
225  *
226  * Revision 1.38  1995/06/01  16:36:47  adam
227  * About buttons. Minor bug fixes.
228  *
229  * Revision 1.37  1995/06/01  07:31:20  adam
230  * Rename of many typedefs -> IrTcl_...
231  *
232  * Revision 1.36  1995/05/31  13:09:59  adam
233  * Client searches/presents may be interrupted.
234  * New moving book-logo.
235  *
236  * Revision 1.35  1995/05/31  08:36:33  adam
237  * Bug fix in client.tcl: didn't save options on clientrc.tcl.
238  * New method: referenceId. More work on scan.
239  *
240  * Revision 1.34  1995/05/29  10:33:42  adam
241  * README and rename of startup script.
242  *
243  * Revision 1.33  1995/05/29  09:15:11  quinn
244  * Changed CS_SR to PROTO_SR, etc.
245  *
246  * Revision 1.32  1995/05/29  08:44:16  adam
247  * Work on delete of objects.
248  *
249  * Revision 1.31  1995/05/26  11:44:10  adam
250  * Bugs fixed. More work on MARC utilities and queries. Test
251  * client is up-to-date again.
252  *
253  * Revision 1.30  1995/05/26  08:54:11  adam
254  * New MARC utilities. Uses prefix query.
255  *
256  * Revision 1.29  1995/05/24  14:10:22  adam
257  * Work on idAuthentication, protocolVersion and options.
258  *
259  * Revision 1.28  1995/05/23  15:34:48  adam
260  * Many new settings, userInformationField, smallSetUpperBound, etc.
261  * A number of settings are inherited when ir-set is executed.
262  * This version is incompatible with the graphical test client (client.tcl).
263  *
264  * Revision 1.27  1995/05/11  15:34:47  adam
265  * Scan request changed a bit. This version works with RLG.
266  *
267  * Revision 1.26  1995/04/18  16:11:51  adam
268  * First version of graphical Scan. Some work on query-by-form.
269  *
270  * Revision 1.25  1995/04/17  09:37:17  adam
271  * Further development of scan.
272  *
273  * Revision 1.24  1995/04/11  14:16:42  adam
274  * Further work on scan. Response works. Entries aren't saved yet.
275  *
276  * Revision 1.23  1995/04/10  10:50:27  adam
277  * Result-set name defaults to suffix of ir-set name.
278  * Started working on scan. Not finished at this point.
279  *
280  * Revision 1.22  1995/03/31  10:43:03  adam
281  * More robust when getting bad MARC records.
282  *
283  * Revision 1.21  1995/03/31  08:56:37  adam
284  * New button "Search".
285  *
286  * Revision 1.20  1995/03/29  16:07:09  adam
287  * Bug fix: Didn't use setName in present request.
288  *
289  * Revision 1.19  1995/03/28  12:45:23  adam
290  * New ir method failback: called on disconnect/protocol error.
291  * New ir set/get method: protocol: SR / Z3950.
292  * Simple popup and disconnect when failback is invoked.
293  *
294  * Revision 1.18  1995/03/21  15:50:12  adam
295  * Minor changes.
296  *
297  * Revision 1.17  1995/03/21  13:41:03  adam
298  * Comstack cs_create not used too often. Non-blocking connect.
299  *
300  * Revision 1.16  1995/03/21  08:26:06  adam
301  * New method, setName, to specify the result set name (other than Default).
302  * New method, responseStatus, which returns diagnostic info, if any, after
303  * present response / search response.
304  *
305  * Revision 1.15  1995/03/20  15:24:07  adam
306  * Diagnostic records saved on searchResponse.
307  *
308  * Revision 1.14  1995/03/20  08:53:22  adam
309  * Event loop in tclmain.c rewritten. New method searchStatus.
310  *
311  * Revision 1.13  1995/03/17  18:26:17  adam
312  * Non-blocking i/o used now. Database names popup as cascade items.
313  *
314  * Revision 1.12  1995/03/17  15:45:00  adam
315  * Improved target/database setup.
316  *
317  * Revision 1.11  1995/03/16  17:54:03  adam
318  * Minor changes really.
319  *
320  * Revision 1.10  1995/03/15  16:14:50  adam
321  * Blocking arg in cs_create changed.
322  *
323  * Revision 1.9  1995/03/15  13:59:24  adam
324  * Minor changes.
325  *
326  * Revision 1.8  1995/03/15  08:25:16  adam
327  * New method presentStatus to check for error on present. Misc. cleanup
328  * of IrTcl_RecordList manipulations. Full MARC record presentation in
329  * search.tcl.
330  *
331  * Revision 1.7  1995/03/14  17:32:29  adam
332  * Presentation of full Marc record in popup window.
333  *
334  * Revision 1.6  1995/03/12  19:31:55  adam
335  * Pattern matching implemented when retrieving MARC records. More
336  * diagnostic functions.
337  *
338  * Revision 1.5  1995/03/10  18:00:15  adam
339  * Actual presentation in line-by-line format. RPN query support.
340  *
341  * Revision 1.4  1995/03/09  16:15:08  adam
342  * First presentRequest attempts. Hot-target list.
343  *
344  */
345
346 #include <stdlib.h>
347 #include <stdio.h>
348 #ifdef WINDOWS
349
350 #else
351 #include <unistd.h>
352 #endif
353 #include <time.h>
354 #include <assert.h>
355
356 #define CS_BLOCK 0
357
358 #include "ir-tclp.h"
359
360 static void ir_deleteDiags (IrTcl_Diagnostic **dst_list, int *dst_num);
361
362 static void ir_select_notify (ClientData clientData, int r, int w, int e);
363
364 void ir_select_add (int fd, void *obj)
365 {
366     ir_tcl_select_set (ir_select_notify, fd, obj, 1, 0, 0);
367 }
368
369 void ir_select_add_write (int fd, void *obj)
370 {
371     ir_tcl_select_set (ir_select_notify, fd, obj, 1, 1, 0);
372 }
373
374 void ir_select_remove (int fd, void *obj)
375 {
376     ir_tcl_select_set (NULL, fd, obj, 0, 0, 0);
377 }
378
379 void ir_select_remove_write (int fd, void *obj)
380 {
381     ir_tcl_select_set (ir_select_notify, fd, obj, 1, 0, 0);
382 }
383
384 static void delete_IR_record (IrTcl_RecordList *rl)
385 {
386     switch (rl->which)
387     {
388     case Z_NamePlusRecord_databaseRecord:
389         switch (rl->u.dbrec.type)
390         {
391         case VAL_GRS1:
392             ir_tcl_grs_del (&rl->u.dbrec.u.grs1);
393             break;
394         default:
395             break;
396         }
397         xfree (rl->u.dbrec.buf);
398         rl->u.dbrec.buf = NULL;
399         break;
400     case Z_NamePlusRecord_surrogateDiagnostic:
401         ir_deleteDiags (&rl->u.surrogateDiagnostics.list,
402                         &rl->u.surrogateDiagnostics.num);
403         break;
404     }
405     xfree (rl->elements);
406 }
407
408 static IrTcl_RecordList *new_IR_record (IrTcl_SetObj *setobj, 
409                                         int no, int which, 
410                                         const char *elements)
411 {
412     IrTcl_RecordList *rl;
413
414     if (elements && !*elements)
415         elements = NULL;
416     for (rl = setobj->record_list; rl; rl = rl->next)
417     {
418         if (no == rl->no && (!rl->elements || !elements ||
419                              !strcmp(elements, rl->elements)))
420         {
421             delete_IR_record (rl);
422             break;
423         }
424     }
425     if (!rl)
426     {
427         rl = ir_tcl_malloc (sizeof(*rl));
428         rl->next = setobj->record_list;
429         rl->no = no;
430         setobj->record_list = rl;
431     }
432     rl->which = which;
433     ir_tcl_strdup (NULL, &rl->elements, elements);
434     return rl;
435 }
436
437 /* 
438  * ir_tcl_eval
439  */
440 int ir_tcl_eval (Tcl_Interp *interp, const char *command)
441 {
442     char *tmp = ir_tcl_malloc (strlen(command)+1);
443     int r;
444
445     logf (LOG_DEBUG, "Invoking %.23s ...", command);
446     strcpy (tmp, command);
447     r = Tcl_Eval (interp, tmp);
448     if (r == TCL_ERROR)
449     {
450         logf (LOG_WARN, "Tcl error in line %d: %s", interp->errorLine, 
451               interp->result);
452     }
453     Tcl_FreeResult (interp);
454     xfree (tmp);
455     return r;
456 }
457
458 /*
459  * IrTcl_getRecordSyntaxStr: Return record syntax name of object id
460  */
461 static char *IrTcl_getRecordSyntaxStr (enum oid_value value)
462 {
463     int *o;
464     struct oident ent, *entp;
465
466     ent.proto = PROTO_Z3950;
467     ent.oclass = CLASS_RECSYN;
468     ent.value = value;
469
470     o = oid_getoidbyent (&ent);
471     entp = oid_getentbyoid (o);
472     
473     if (!entp)
474         return "";
475     return entp->desc;
476 }
477
478 /*
479  * IrTcl_getRecordSyntaxVal: Return record syntax value of string
480  */
481 static enum oid_value IrTcl_getRecordSyntaxVal (const char *name)
482 {
483     return oid_getvalbyname (name);
484 }
485
486 static IrTcl_RecordList *find_IR_record (IrTcl_SetObj *setobj, int no)
487 {
488     IrTcl_RecordList *rl;
489
490     for (rl = setobj->record_list; rl; rl = rl->next)
491         if (no == rl->no && 
492             (!setobj->recordElements || !rl->elements || 
493              !strcmp (setobj->recordElements, rl->elements)))
494             return rl;
495     return NULL;
496 }
497
498 static void delete_IR_records (IrTcl_SetObj *setobj)
499 {
500     IrTcl_RecordList *rl, *rl1;
501
502     for (rl = setobj->record_list; rl; rl = rl1)
503     {
504         delete_IR_record (rl);
505         rl1 = rl->next;
506         xfree (rl);
507     }
508     setobj->record_list = NULL;
509 }
510
511 /*
512  * ir_tcl_get_set_int: Set/get integer value
513  */
514 int ir_tcl_get_set_int (int *val, Tcl_Interp *interp, int argc, char **argv)
515 {
516     char buf[20];
517     
518     if (argc == 3)
519     {
520         if (Tcl_GetInt (interp, argv[2], val)==TCL_ERROR)
521             return TCL_ERROR;
522     }
523     sprintf (buf, "%d", *val);
524     Tcl_AppendResult (interp, buf, NULL);
525     return TCL_OK;
526 }
527
528 /*
529  * ir_tcl_method: Search for method in table and invoke method handler
530  */
531 int ir_tcl_method (Tcl_Interp *interp, int argc, char **argv,
532                    IrTcl_Methods *tab, int *ret)
533 {
534     IrTcl_Methods *tab_i = tab;
535     IrTcl_Method *t;
536
537     for (tab_i = tab; tab_i->tab; tab_i++)
538         for (t = tab_i->tab; t->name; t++)
539             if (argc <= 0)
540             {
541                 if ((*t->method)(tab_i->obj, interp, argc, argv) == TCL_ERROR)
542                     return TCL_ERROR;
543             }
544             else
545                 if (!strcmp (t->name, argv[1]))
546                 {
547                     *ret = (*t->method)(tab_i->obj, interp, argc, argv);
548                     return TCL_OK;
549                 }
550
551     if (argc <= 0)
552         return TCL_OK;
553 #if 0
554     Tcl_AppendResult (interp, "Bad method: ", argv[1], 
555                       ". Possible methods:", NULL);
556     for (tab_i = tab; tab_i->tab; tab_i++)
557         for (t = tab_i->tab; t->name; t++)
558             Tcl_AppendResult (interp, " ", t->name, NULL);
559 #endif
560     *ret = TCL_ERROR;
561     return TCL_ERROR;
562 }
563
564 /*
565  *  ir_tcl_named_bits: get/set named bits
566  */
567 int ir_tcl_named_bits (struct ir_named_entry *tab, Odr_bitmask *ob,
568                        Tcl_Interp *interp, int argc, char **argv)
569 {
570     struct ir_named_entry *ti;
571     if (argc > 0)
572     {
573         int no;
574         ODR_MASK_ZERO (ob);
575         for (no = 0; no < argc; no++)
576         {
577             for (ti = tab; ti->name; ti++)
578                 if (!strcmp (argv[no], ti->name))
579                 {
580                     ODR_MASK_SET (ob, ti->pos);
581                     break;
582                 }
583             if (!ti->name)
584             {
585                 Tcl_AppendResult (interp, "Bad bit mask: ", argv[no], NULL);
586                 return TCL_ERROR;
587             }
588         }
589         return TCL_OK;
590     }
591     for (ti = tab; ti->name; ti++)
592         if (ODR_MASK_GET (ob, ti->pos))
593             Tcl_AppendElement (interp, ti->name);
594     return TCL_OK;
595 }
596
597 static void set_referenceId (ODR o, Z_ReferenceId **dst, const char *src)
598 {
599     if (!src || !*src)
600         *dst = NULL;
601     else
602     {
603         *dst = odr_malloc (o, sizeof(**dst));
604         (*dst)->size = (*dst)->len = strlen(src);
605         (*dst)->buf = odr_malloc (o, (*dst)->len);
606         memcpy ((*dst)->buf, src, (*dst)->len);
607     }
608 }
609
610 static void get_referenceId (char **dst, Z_ReferenceId *src)
611 {
612     xfree (*dst);
613     if (!src)
614     {
615         *dst = NULL;
616         return;
617     }
618     *dst = ir_tcl_malloc (src->len+1);
619     memcpy (*dst, src->buf, src->len);
620     (*dst)[src->len] = '\0';
621 }
622
623 /* ------------------------------------------------------- */
624
625 /*
626  * do_init_request: init method on IR object
627  */
628 static int do_init_request (void *obj, Tcl_Interp *interp,
629                             int argc, char **argv)
630 {
631     Z_APDU *apdu;
632     IrTcl_Obj *p = obj;
633     Z_InitRequest *req;
634
635     if (argc <= 0)
636         return TCL_OK;
637     logf (LOG_DEBUG, "init %s", *argv);
638     if (!p->cs_link)
639     {
640         interp->result = "init: not connected";
641         return TCL_ERROR;
642     }
643     apdu = zget_APDU (p->odr_out, Z_APDU_initRequest);
644     req = apdu->u.initRequest;
645
646     set_referenceId (p->odr_out, &req->referenceId, p->set_inher.referenceId);
647     req->options = &p->options;
648     req->protocolVersion = &p->protocolVersion;
649     req->preferredMessageSize = &p->preferredMessageSize;
650     req->maximumRecordSize = &p->maximumRecordSize;
651
652     if (p->idAuthenticationGroupId)
653     {
654         Z_IdPass *pass = odr_malloc (p->odr_out, sizeof(*pass));
655         Z_IdAuthentication *auth = odr_malloc (p->odr_out, sizeof(*auth));
656
657         logf (LOG_DEBUG, "using pass authentication");
658
659         auth->which = Z_IdAuthentication_idPass;
660         auth->u.idPass = pass;
661         if (p->idAuthenticationGroupId && *p->idAuthenticationGroupId)
662             pass->groupId = p->idAuthenticationGroupId;
663         else
664             pass->groupId = NULL;
665         if (p->idAuthenticationUserId && *p->idAuthenticationUserId)
666             pass->userId = p->idAuthenticationUserId;
667         else
668             pass->userId = NULL;
669         if (p->idAuthenticationPassword && *p->idAuthenticationPassword)
670             pass->password = p->idAuthenticationPassword;
671         else
672             pass->password = NULL;
673         req->idAuthentication = auth;
674     }
675     else if (!p->idAuthenticationOpen || !*p->idAuthenticationOpen)
676         req->idAuthentication = NULL;
677     else
678     {
679         Z_IdAuthentication *auth = odr_malloc (p->odr_out, sizeof(*auth));
680
681         logf (LOG_DEBUG, "using open authentication");
682         auth->which = Z_IdAuthentication_open;
683         auth->u.open = p->idAuthenticationOpen;
684         req->idAuthentication = auth;
685     }
686     req->implementationId = p->implementationId;
687     req->implementationName = p->implementationName;
688     req->implementationVersion = p->implementationVersion;
689     req->userInformationField = 0;
690
691     return ir_tcl_send_APDU (interp, p, apdu, "init", *argv);
692 }
693
694 /*
695  * do_protocolVersion: Set protocol Version
696  */
697 static int do_protocolVersion (void *obj, Tcl_Interp *interp,
698                                int argc, char **argv)
699 {
700     int version, i;
701     char buf[10];
702     IrTcl_Obj *p = obj;
703
704     if (argc <= 0)
705     {
706         ODR_MASK_ZERO (&p->protocolVersion);
707         ODR_MASK_SET (&p->protocolVersion, 0);
708         ODR_MASK_SET (&p->protocolVersion, 1);
709         return TCL_OK;
710     }
711     if (argc == 3)
712     {
713         if (Tcl_GetInt (interp, argv[2], &version)==TCL_ERROR)
714             return TCL_ERROR;
715         ODR_MASK_ZERO (&p->protocolVersion);
716         for (i = 0; i<version; i++)
717             ODR_MASK_SET (&p->protocolVersion, i);
718     }
719     for (i = 4; --i >= 0; )
720         if (ODR_MASK_GET (&p->protocolVersion, i))
721             break;
722     sprintf (buf, "%d", i+1);
723     interp->result = buf;
724     return TCL_OK;
725 }
726
727 /*
728  * do_options: Set options
729  */
730 static int do_options (void *obj, Tcl_Interp *interp,
731                        int argc, char **argv)
732 {
733     static struct ir_named_entry options_tab[] = {
734     { "search", 0 },
735     { "present", 1 },
736     { "delSet", 2 },
737     { "resourceReport", 3 },
738     { "triggerResourceCtrl", 4},
739     { "resourceCtrl", 5},
740     { "accessCtrl", 6},
741     { "scan", 7},
742     { "sort", 8},
743     { "extendedServices", 10},
744     { "level-1Segmentation", 11},
745     { "level-2Segmentation", 12},
746     { "concurrentOperations", 13},
747     { "namedResultSets", 14},
748     { NULL, 0}
749     };
750     IrTcl_Obj *p = obj;
751
752     if (argc <= 0)
753     {
754         ODR_MASK_ZERO (&p->options);
755         ODR_MASK_SET (&p->options, 0);
756         ODR_MASK_SET (&p->options, 1);
757         ODR_MASK_SET (&p->options, 4);
758         ODR_MASK_SET (&p->options, 7);
759         ODR_MASK_SET (&p->options, 14);
760         return TCL_OK;
761     }
762     return ir_tcl_named_bits (options_tab, &p->options, interp, argc-2, argv+2);
763 }
764
765 /*
766  * do_apduInfo: Get APDU information
767  */
768 static int do_apduInfo (void *obj, Tcl_Interp *interp, int argc, char **argv)
769 {
770     char buf[16];
771     FILE *apduf;
772     IrTcl_Obj *p = obj;
773
774     if (argc <= 0)
775         return TCL_OK;
776     sprintf (buf, "%d", p->apduLen);
777     Tcl_AppendElement (interp, buf);
778     sprintf (buf, "%d", p->apduOffset);
779     Tcl_AppendElement (interp, buf);
780     if (!p->buf_in)
781     {
782         Tcl_AppendElement (interp, "");
783         return TCL_OK;
784     }
785     apduf = fopen ("apdu.tmp", "w");
786     if (!apduf)
787     {
788         Tcl_AppendElement (interp, "");
789         return TCL_OK;
790     }
791     odr_dumpBER (apduf, p->buf_in, p->apduLen);
792     fclose (apduf);
793     if (!(apduf = fopen ("apdu.tmp", "r")))
794         Tcl_AppendElement (interp, "");
795     else
796     {
797         int c;
798         
799         Tcl_AppendResult (interp, " {", NULL);
800         while ((c = getc (apduf)) != EOF)
801         {
802             buf[0] = c;
803             buf[1] = '\0';
804             Tcl_AppendResult (interp, buf, NULL);
805         }
806         fclose (apduf);
807         Tcl_AppendResult (interp, "}", NULL);
808     }
809     unlink ("apdu.tmp");
810     return TCL_OK;
811 }
812
813 /*
814  * do_failInfo: Get fail information
815  */
816 static int do_failInfo (void *obj, Tcl_Interp *interp, int argc, char **argv)
817 {
818     char buf[16], *cp;
819     IrTcl_Obj *p = obj;
820
821     if (argc <= 0)
822     {
823         p->failInfo = 0;
824         return TCL_OK;
825     }
826     sprintf (buf, "%d", p->failInfo);
827     switch (p->failInfo)
828     {
829     case 0:
830         cp = "ok";
831         break;
832     case IR_TCL_FAIL_CONNECT:
833         cp = "connect failed";
834         break;
835     case IR_TCL_FAIL_READ:
836         cp = "connection closed";
837         break;
838     case IR_TCL_FAIL_WRITE:
839         cp = "connection closed";
840         break;
841     case IR_TCL_FAIL_IN_APDU:
842         cp = "failed to decode incoming APDU";
843         break;
844     case IR_TCL_FAIL_UNKNOWN_APDU:
845         cp = "unknown APDU";
846         break;
847     default:
848         cp = "";
849     } 
850     Tcl_AppendElement (interp, buf);
851     Tcl_AppendElement (interp, cp);
852     return TCL_OK;
853 }
854
855 /*
856  * do_preferredMessageSize: Set/get preferred message size
857  */
858 static int do_preferredMessageSize (void *obj, Tcl_Interp *interp,
859                                     int argc, char **argv)
860 {
861     IrTcl_Obj *p = obj;
862
863     if (argc <= 0)
864     {
865         p->preferredMessageSize = 30000;
866         return TCL_OK;
867     }
868     return ir_tcl_get_set_int (&p->preferredMessageSize, interp, argc, argv);
869 }
870
871 /*
872  * do_maximumRecordSize: Set/get maximum record size
873  */
874 static int do_maximumRecordSize (void *obj, Tcl_Interp *interp,
875                                  int argc, char **argv)
876 {
877     IrTcl_Obj *p = obj;
878
879     if (argc <= 0)
880     {
881         p->maximumRecordSize = 30000;
882         return TCL_OK;
883     }
884     return ir_tcl_get_set_int (&p->maximumRecordSize, interp, argc, argv);
885 }
886
887 /*
888  * do_initResult: Get init result
889  */
890 static int do_initResult (void *obj, Tcl_Interp *interp,
891                           int argc, char **argv)
892 {
893     IrTcl_Obj *p = obj;
894    
895     if (argc <= 0)
896         return TCL_OK;
897     return ir_tcl_get_set_int (&p->initResult, interp, argc, argv);
898 }
899
900
901 /*
902  * do_implementationName: Set/get Implementation Name.
903  */
904 static int do_implementationName (void *obj, Tcl_Interp *interp,
905                                     int argc, char **argv)
906 {
907     IrTcl_Obj *p = obj;
908
909     if (argc == 0)
910         return ir_tcl_strdup (interp, &p->implementationName,
911                           "Index Data/IrTcl on YAZ");
912     else if (argc == -1)
913         return ir_tcl_strdel (interp, &p->implementationName);
914     if (argc == 3)
915     {
916         xfree (p->implementationName);
917         if (ir_tcl_strdup (interp, &p->implementationName, argv[2])
918             == TCL_ERROR)
919             return TCL_ERROR;
920     }
921     Tcl_AppendResult (interp, p->implementationName, (char*) NULL);
922     return TCL_OK;
923 }
924
925 /*
926  * do_implementationId: Get Implementation Id.
927  */
928 static int do_implementationId (void *obj, Tcl_Interp *interp,
929                                 int argc, char **argv)
930 {
931     IrTcl_Obj *p = obj;
932
933     if (argc == 0)
934         return ir_tcl_strdup (interp, &p->implementationId, "YAZ (id=81)");
935     else if (argc == -1)
936         return ir_tcl_strdel (interp, &p->implementationId);
937     Tcl_AppendResult (interp, p->implementationId, (char*) NULL);
938     return TCL_OK;
939 }
940
941 /*
942  * do_implementationVersion: get Implementation Version.
943  */
944 static int do_implementationVersion (void *obj, Tcl_Interp *interp,
945                                      int argc, char **argv)
946 {
947     IrTcl_Obj *p = obj;
948
949     if (argc == 0)
950         return ir_tcl_strdup (interp, &p->implementationVersion, 
951                           "YAZ: " YAZ_VERSION
952 #ifdef IR_TCL_VERSION
953                           " / Irtcl: " IR_TCL_VERSION
954 #endif
955                           );
956     else if (argc == -1)
957         return ir_tcl_strdel (interp, &p->implementationVersion);
958     Tcl_AppendResult (interp, p->implementationVersion, (char*) NULL);
959     return TCL_OK;
960 }
961
962 /*
963  * do_targetImplementationName: Get Implementation Name of target.
964  */
965 static int do_targetImplementationName (void *obj, Tcl_Interp *interp,
966                                         int argc, char **argv)
967 {
968     IrTcl_Obj *p = obj;
969     
970     if (argc == 0)
971     {
972         p->targetImplementationName = NULL;
973         return TCL_OK;
974     }
975     else if (argc == -1)
976         return ir_tcl_strdel (interp, &p->targetImplementationName);
977     Tcl_AppendResult (interp, p->targetImplementationName, (char*) NULL);
978     return TCL_OK;
979 }
980
981 /*
982  * do_targetImplementationId: Get Implementation Id of target
983  */
984 static int do_targetImplementationId (void *obj, Tcl_Interp *interp,
985                                       int argc, char **argv)
986 {
987     IrTcl_Obj *p = obj;
988
989     if (argc == 0)
990     {
991         p->targetImplementationId = NULL;
992         return TCL_OK;
993     }
994     else if (argc == -1)
995         return ir_tcl_strdel (interp, &p->targetImplementationId);
996     Tcl_AppendResult (interp, p->targetImplementationId, (char*) NULL);
997     return TCL_OK;
998 }
999
1000 /*
1001  * do_targetImplementationVersion: Get Implementation Version of target
1002  */
1003 static int do_targetImplementationVersion (void *obj, Tcl_Interp *interp,
1004                                            int argc, char **argv)
1005 {
1006     IrTcl_Obj *p = obj;
1007
1008     if (argc == 0)
1009     {
1010         p->targetImplementationVersion = NULL;
1011         return TCL_OK;
1012     }
1013     else if (argc == -1)
1014         return ir_tcl_strdel (interp, &p->targetImplementationVersion);
1015     Tcl_AppendResult (interp, p->targetImplementationVersion, (char*) NULL);
1016     return TCL_OK;
1017 }
1018
1019 /*
1020  * do_idAuthentication: Set/get id Authentication
1021  */
1022 static int do_idAuthentication (void *obj, Tcl_Interp *interp,
1023                                 int argc, char **argv)
1024 {
1025     IrTcl_Obj *p = obj;
1026
1027     if (argc >= 3 || argc == -1)
1028     {
1029         xfree (p->idAuthenticationOpen);
1030         xfree (p->idAuthenticationGroupId);
1031         xfree (p->idAuthenticationUserId);
1032         xfree (p->idAuthenticationPassword);
1033     }
1034     if (argc >= 3 || argc <= 0)
1035     {
1036         p->idAuthenticationOpen = NULL;
1037         p->idAuthenticationGroupId = NULL;
1038         p->idAuthenticationUserId = NULL;
1039         p->idAuthenticationPassword = NULL;
1040     }
1041     if (argc <= 0)
1042         return TCL_OK;
1043     if (argc >= 3)
1044     {
1045         if (argc == 3)
1046         {
1047             if (argv[2][0] && 
1048                 ir_tcl_strdup (interp, &p->idAuthenticationOpen, argv[2])
1049                 == TCL_ERROR)
1050                 return TCL_ERROR;
1051         }
1052         else if (argc == 5)
1053         {
1054             if (argv[2][0] && 
1055                 ir_tcl_strdup (interp, &p->idAuthenticationGroupId, argv[2])
1056                 == TCL_ERROR)
1057                 return TCL_ERROR;
1058             if (argv[3][0] && 
1059                 ir_tcl_strdup (interp, &p->idAuthenticationUserId, argv[3])
1060                 == TCL_ERROR)
1061                 return TCL_ERROR;
1062             if (argv[4][0] &&
1063                 ir_tcl_strdup (interp, &p->idAuthenticationPassword, argv[4])
1064                 == TCL_ERROR)
1065                 return TCL_ERROR;
1066         }
1067     }
1068     if (p->idAuthenticationOpen)
1069         Tcl_AppendElement (interp, p->idAuthenticationOpen);
1070     else if (p->idAuthenticationGroupId)
1071     {
1072         Tcl_AppendElement (interp, p->idAuthenticationGroupId);
1073         Tcl_AppendElement (interp, p->idAuthenticationUserId);
1074         Tcl_AppendElement (interp, p->idAuthenticationPassword);
1075     }
1076     return TCL_OK;
1077 }
1078
1079 /*
1080  * do_connect: connect method on IR object
1081  */
1082 static int do_connect (void *obj, Tcl_Interp *interp,
1083                        int argc, char **argv)
1084 {
1085     void *addr;
1086     IrTcl_Obj *p = obj;
1087     int r;
1088
1089     if (argc <= 0)
1090         return TCL_OK;
1091     if (argc == 3)
1092     {
1093         logf (LOG_DEBUG, "connect %s %s", *argv, argv[2]);
1094         if (p->hostname)
1095         {
1096             interp->result = "already connected";
1097             return TCL_ERROR;
1098         }
1099         if (!strcmp (p->comstackType, "tcpip"))
1100         {
1101             p->cs_link = cs_create (tcpip_type, CS_BLOCK, p->protocol_type);
1102             addr = tcpip_strtoaddr (argv[2]);
1103             if (!addr)
1104             {
1105                 interp->result = "tcpip_strtoaddr fail";
1106                 return TCL_ERROR;
1107             }
1108             logf (LOG_DEBUG, "tcp/ip connect %s", argv[2]);
1109         }
1110         else if (!strcmp (p->comstackType, "mosi"))
1111         {
1112 #if MOSI
1113             p->cs_link = cs_create (mosi_type, CS_BLOCK, p->protocol_type);
1114             addr = mosi_strtoaddr (argv[2]);
1115             if (!addr)
1116             {
1117                 interp->result = "mosi_strtoaddr fail";
1118                 return TCL_ERROR;
1119             }
1120             logf (LOG_DEBUG, "mosi connect %s", argv[2]);
1121 #else
1122             interp->result = "MOSI support not there";
1123             return TCL_ERROR;
1124 #endif
1125         }
1126         else 
1127         {
1128             Tcl_AppendResult (interp, "Bad comstack type: ", 
1129                               p->comstackType, NULL);
1130             return TCL_ERROR;
1131         }
1132         if (ir_tcl_strdup (interp, &p->hostname, argv[2]) == TCL_ERROR)
1133             return TCL_ERROR;
1134         p->eventType = "connect";
1135         if ((r=cs_connect (p->cs_link, addr)) < 0)
1136         {
1137             interp->result = "connect fail";
1138             ir_tcl_disconnect (p);
1139             return TCL_ERROR;
1140         }
1141         ir_select_add (cs_fileno (p->cs_link), p);
1142         if (r == 1)
1143         {
1144             logf (LOG_DEBUG, "connect pending fd=%d", cs_fileno(p->cs_link));
1145             ir_select_add_write (cs_fileno (p->cs_link), p);
1146             p->state = IR_TCL_R_Connecting;
1147         }
1148         else
1149         {
1150             logf (LOG_DEBUG, "connect ok fd=%d", cs_fileno(p->cs_link));
1151             p->state = IR_TCL_R_Idle;
1152             if (p->callback)
1153                 ir_tcl_eval (p->interp, p->callback);
1154         }
1155     }
1156     else
1157         Tcl_AppendResult (interp, p->hostname, NULL);
1158     return TCL_OK;
1159 }
1160
1161 /* 
1162  * ir_tcl_disconnect: close connection
1163  */
1164 void ir_tcl_disconnect (IrTcl_Obj *p)
1165 {
1166     if (p->hostname)
1167     {
1168         logf(LOG_DEBUG, "Closing connection to %s", p->hostname);
1169         xfree (p->hostname);
1170         p->hostname = NULL;
1171         assert (p->cs_link);
1172         ir_select_remove (cs_fileno (p->cs_link), p);
1173
1174         odr_reset (p->odr_in);
1175
1176         cs_close (p->cs_link);
1177         p->cs_link = NULL;
1178
1179         ODR_MASK_ZERO (&p->options);
1180         ODR_MASK_SET (&p->options, 0);
1181         ODR_MASK_SET (&p->options, 1);
1182         ODR_MASK_SET (&p->options, 4);
1183         ODR_MASK_SET (&p->options, 7);
1184         ODR_MASK_SET (&p->options, 14);
1185
1186         ODR_MASK_ZERO (&p->protocolVersion);
1187         ODR_MASK_SET (&p->protocolVersion, 0);
1188         ODR_MASK_SET (&p->protocolVersion, 1);
1189         ir_tcl_del_q (p);
1190     }
1191     assert (!p->cs_link);
1192 }
1193
1194 /*
1195  * do_disconnect: disconnect method on IR object
1196  */
1197 static int do_disconnect (void *obj, Tcl_Interp *interp,
1198                           int argc, char **argv)
1199 {
1200     IrTcl_Obj *p = obj;
1201
1202     if (argc == 0)
1203     {
1204         p->state = IR_TCL_R_Idle;
1205         p->eventType = NULL;
1206         p->hostname = NULL;
1207         p->cs_link = NULL;
1208         return TCL_OK;
1209     }
1210     ir_tcl_disconnect (p);
1211     return TCL_OK;
1212 }
1213
1214 /*
1215  * do_comstack: Set/get comstack method on IR object
1216  */
1217 static int do_comstack (void *o, Tcl_Interp *interp,
1218                         int argc, char **argv)
1219 {
1220     IrTcl_Obj *obj = o;
1221
1222     if (argc == 0)
1223         return ir_tcl_strdup (interp, &obj->comstackType, "tcpip");
1224     else if (argc == -1)
1225         return ir_tcl_strdel (interp, &obj->comstackType);
1226     else if (argc == 3)
1227     {
1228         xfree (obj->comstackType);
1229         if (ir_tcl_strdup (interp, &obj->comstackType, argv[2]) == TCL_ERROR)
1230             return TCL_ERROR;
1231     }
1232     Tcl_AppendElement (interp, obj->comstackType);
1233     return TCL_OK;
1234 }
1235
1236 /*
1237  * do_logLevel: Set log level
1238  */
1239 static int do_logLevel (void *o, Tcl_Interp *interp,
1240                         int argc, char **argv)
1241 {
1242     if (argc <= 2)
1243         return TCL_OK;
1244     if (argc == 3)
1245         log_init (log_mask_str (argv[2]), "", NULL);
1246     else if (argc == 4)
1247         log_init (log_mask_str (argv[2]), argv[3], NULL);
1248     else if (argc == 5)
1249         log_init (log_mask_str (argv[2]), argv[3], argv[4]);
1250     return TCL_OK;
1251 }
1252
1253
1254 /*
1255  * do_eventType: Return type of last event
1256  */
1257 static int do_eventType (void *obj, Tcl_Interp *interp,
1258                          int argc, char **argv)
1259 {
1260     IrTcl_Obj *p = obj;
1261
1262     if (argc <= 0)
1263     {
1264         p->eventType = NULL;
1265         return TCL_OK;
1266     }
1267     Tcl_AppendElement (interp, p->eventType ? p->eventType : "");
1268     return TCL_OK;
1269 }
1270
1271
1272 /*
1273  * do_callback: add callback
1274  */
1275 static int do_callback (void *obj, Tcl_Interp *interp,
1276                         int argc, char **argv)
1277 {
1278     IrTcl_Obj *p = obj;
1279
1280     if (argc == 0)
1281     {
1282         p->callback = NULL;
1283         return TCL_OK;
1284     }
1285     else if (argc == -1)
1286         return ir_tcl_strdel (interp, &p->callback);
1287     if (argc == 3)
1288     {
1289         xfree (p->callback);
1290         if (argv[2][0])
1291         {
1292             if (ir_tcl_strdup (interp, &p->callback, argv[2]) == TCL_ERROR)
1293                 return TCL_ERROR;
1294         }
1295         else
1296             p->callback = NULL;
1297     }
1298     return TCL_OK;
1299 }
1300
1301 /*
1302  * do_failback: add error handle callback
1303  */
1304 static int do_failback (void *obj, Tcl_Interp *interp,
1305                           int argc, char **argv)
1306 {
1307     IrTcl_Obj *p = obj;
1308
1309     if (argc == 0)
1310     {
1311         p->failback = NULL;
1312         return TCL_OK;
1313     }
1314     else if (argc == -1)
1315         return ir_tcl_strdel (interp, &p->failback);
1316     else if (argc == 3)
1317     {
1318         xfree (p->failback);
1319         if (argv[2][0])
1320         {
1321             if (ir_tcl_strdup (interp, &p->failback, argv[2]) == TCL_ERROR)
1322                 return TCL_ERROR;
1323         }
1324         else
1325             p->failback = NULL;
1326     }
1327     return TCL_OK;
1328 }
1329
1330 /*
1331  * do_initResponse: add init response handler
1332  */
1333 static int do_initResponse (void *obj, Tcl_Interp *interp,
1334                             int argc, char **argv)
1335 {
1336     IrTcl_Obj *p = obj;
1337
1338     if (argc == 0)
1339     {
1340         p->initResponse = NULL;
1341         return TCL_OK;
1342     }
1343     else if (argc == -1)
1344         return ir_tcl_strdel (interp, &p->initResponse);
1345     if (argc == 3)
1346     {
1347         xfree (p->initResponse);
1348         if (argv[2][0])
1349         {
1350             if (ir_tcl_strdup (interp, &p->initResponse, argv[2]) == TCL_ERROR)
1351                 return TCL_ERROR;
1352         }
1353         else
1354             p->initResponse = NULL;
1355     }
1356     return TCL_OK;
1357 }
1358 /*
1359  * do_protocol: Set/get protocol method on IR object
1360  */
1361 static int do_protocol (void *o, Tcl_Interp *interp, int argc, char **argv)
1362 {
1363     IrTcl_Obj *p = o;
1364
1365     if (argc <= 0)
1366     {
1367         p->protocol_type = PROTO_Z3950;
1368         return TCL_OK;
1369     }
1370     else if (argc == 3)
1371     {
1372         if (!strcmp (argv[2], "Z39"))
1373             p->protocol_type = PROTO_Z3950;
1374         else if (!strcmp (argv[2], "SR"))
1375             p->protocol_type = PROTO_SR;
1376         else
1377         {
1378             Tcl_AppendResult (interp, "Bad protocol: ", argv[2], NULL);
1379             return TCL_ERROR;
1380         }
1381         return TCL_OK;
1382     }
1383     switch (p->protocol_type)
1384     {
1385     case PROTO_Z3950:
1386         Tcl_AppendElement (interp, "Z39");
1387         break;
1388     case PROTO_SR:
1389         Tcl_AppendElement (interp, "SR");
1390         break;
1391     }
1392     return TCL_OK;
1393 }
1394
1395 /*
1396  * do_triggerResourceControl:
1397  */
1398 static int do_triggerResourceControl (void *obj, Tcl_Interp *interp,
1399                                       int argc, char **argv)
1400 {
1401     IrTcl_Obj *p = obj;
1402     Z_APDU *apdu;
1403     Z_TriggerResourceControlRequest *req;
1404     bool_t is_false = 0;
1405
1406     if (argc <= 0)
1407         return TCL_OK;
1408     if (!p->cs_link)
1409     {
1410         interp->result = "triggerResourceControl: not connected";
1411         return TCL_ERROR;
1412     }
1413     apdu = zget_APDU (p->odr_out, Z_APDU_triggerResourceControlRequest);
1414     req = apdu->u.triggerResourceControlRequest;
1415     *req->requestedAction = Z_TriggerResourceCtrl_cancel;
1416     req->resultSetWanted = &is_false; 
1417     
1418     return ir_tcl_send_APDU (interp, p, apdu, "triggerResourceControl",
1419                              argv[0]);
1420 }
1421
1422 /*
1423  * do_databaseNames: specify database names
1424  */
1425 static int do_databaseNames (void *obj, Tcl_Interp *interp,
1426                              int argc, char **argv)
1427 {
1428     int i;
1429     IrTcl_SetCObj *p = obj;
1430
1431     if (argc == -1)
1432     {
1433         for (i=0; i<p->num_databaseNames; i++)
1434             xfree (p->databaseNames[i]);
1435         xfree (p->databaseNames);
1436     }
1437     if (argc <= 0)
1438     {
1439         p->num_databaseNames = 0;
1440         p->databaseNames = NULL;
1441         return TCL_OK;
1442     }
1443     if (argc < 3)
1444     {
1445         for (i=0; i<p->num_databaseNames; i++)
1446             Tcl_AppendElement (interp, p->databaseNames[i]);
1447         return TCL_OK;
1448     }
1449     if (p->databaseNames)
1450     {
1451         for (i=0; i<p->num_databaseNames; i++)
1452             xfree (p->databaseNames[i]);
1453         xfree (p->databaseNames);
1454     }
1455     p->num_databaseNames = argc - 2;
1456     p->databaseNames =
1457         ir_tcl_malloc (sizeof(*p->databaseNames) * (1+p->num_databaseNames));
1458     for (i=0; i<p->num_databaseNames; i++)
1459     {
1460         if (ir_tcl_strdup (interp, &p->databaseNames[i], argv[2+i]) 
1461             == TCL_ERROR)
1462             return TCL_ERROR;
1463     }
1464     p->databaseNames[i] = NULL;
1465     return TCL_OK;
1466 }
1467
1468 /*
1469  * do_replaceIndicator: Set/get replace Set indicator
1470  */
1471 static int do_replaceIndicator (void *obj, Tcl_Interp *interp,
1472                                 int argc, char **argv)
1473 {
1474     IrTcl_SetCObj *p = obj;
1475
1476     if (argc <= 0)
1477     {
1478         p->replaceIndicator = 1;
1479         return TCL_OK;
1480     }
1481     return ir_tcl_get_set_int (&p->replaceIndicator, interp, argc, argv);
1482 }
1483
1484 /*
1485  * do_queryType: Set/Get query method
1486  */
1487 static int do_queryType (void *obj, Tcl_Interp *interp,
1488                        int argc, char **argv)
1489 {
1490     IrTcl_SetCObj *p = obj;
1491
1492     if (argc == 0)
1493         return ir_tcl_strdup (interp, &p->queryType, "rpn");
1494     else if (argc == -1)
1495         return ir_tcl_strdel (interp, &p->queryType);
1496     if (argc == 3)
1497     {
1498         xfree (p->queryType);
1499         if (ir_tcl_strdup (interp, &p->queryType, argv[2]) == TCL_ERROR)
1500             return TCL_ERROR;
1501     }
1502     Tcl_AppendResult (interp, p->queryType, NULL);
1503     return TCL_OK;
1504 }
1505
1506 /*
1507  * do_userInformationField: Get User information field
1508  */
1509 static int do_userInformationField (void *obj, Tcl_Interp *interp,
1510                                     int argc, char **argv)
1511 {
1512     IrTcl_Obj *p = obj;
1513     
1514     if (argc == 0)
1515     {
1516         p->userInformationField = NULL;
1517         return TCL_OK;
1518     }
1519     else if (argc == -1)
1520         return ir_tcl_strdel (interp, &p->userInformationField);
1521     Tcl_AppendResult (interp, p->userInformationField, NULL);
1522     return TCL_OK;
1523 }
1524
1525 /*
1526  * do_smallSetUpperBound: Set/get small set upper bound
1527  */
1528 static int do_smallSetUpperBound (void *o, Tcl_Interp *interp,
1529                        int argc, char **argv)
1530 {
1531     IrTcl_SetCObj *p = o;
1532
1533     if (argc <= 0)
1534     {
1535         p->smallSetUpperBound = 0;
1536         return TCL_OK;
1537     }
1538     return ir_tcl_get_set_int (&p->smallSetUpperBound, interp, argc, argv);
1539 }
1540
1541 /*
1542  * do_largeSetLowerBound: Set/get large set lower bound
1543  */
1544 static int do_largeSetLowerBound (void *o, Tcl_Interp *interp,
1545                                   int argc, char **argv)
1546 {
1547     IrTcl_SetCObj *p = o;
1548
1549     if (argc <= 0)
1550     {
1551         p->largeSetLowerBound = 2;
1552         return TCL_OK;
1553     }
1554     return ir_tcl_get_set_int (&p->largeSetLowerBound, interp, argc, argv);
1555 }
1556
1557 /*
1558  * do_mediumSetPresentNumber: Set/get large set lower bound
1559  */
1560 static int do_mediumSetPresentNumber (void *o, Tcl_Interp *interp,
1561                                       int argc, char **argv)
1562 {
1563     IrTcl_SetCObj *p = o;
1564    
1565     if (argc <= 0)
1566     {
1567         p->mediumSetPresentNumber = 0;
1568         return TCL_OK;
1569     }
1570     return ir_tcl_get_set_int (&p->mediumSetPresentNumber, interp, argc, argv);
1571 }
1572
1573 /*
1574  * do_referenceId: Set/Get referenceId
1575  */
1576 static int do_referenceId (void *obj, Tcl_Interp *interp,
1577                            int argc, char **argv)
1578 {
1579     IrTcl_SetCObj *p = obj;
1580
1581     if (argc == 0)
1582     {
1583         p->referenceId = NULL;
1584         return TCL_OK;
1585     }
1586     else if (argc == -1)
1587         return ir_tcl_strdel (interp, &p->referenceId);
1588     if (argc == 3)
1589     {
1590         xfree (p->referenceId);
1591         if (ir_tcl_strdup (interp, &p->referenceId, argv[2]) == TCL_ERROR)
1592             return TCL_ERROR;
1593     }
1594     Tcl_AppendResult (interp, p->referenceId, NULL);
1595     return TCL_OK;
1596 }
1597
1598 /*
1599  * do_preferredRecordSyntax: Set/get preferred record syntax
1600  */
1601 static int do_preferredRecordSyntax (void *obj, Tcl_Interp *interp,
1602                                      int argc, char **argv)
1603 {
1604     IrTcl_SetCObj *p = obj;
1605
1606     if (argc == 0)
1607     {
1608         p->preferredRecordSyntax = NULL;
1609         return TCL_OK;
1610     }
1611     else if (argc == -1)
1612     {
1613         xfree (p->preferredRecordSyntax);
1614         p->preferredRecordSyntax = NULL;
1615         return TCL_OK;
1616     }
1617     if (argc == 3)
1618     {
1619         xfree (p->preferredRecordSyntax);
1620         p->preferredRecordSyntax = NULL;
1621         if (argv[2][0] && (p->preferredRecordSyntax = 
1622                            ir_tcl_malloc (sizeof(*p->preferredRecordSyntax))))
1623             *p->preferredRecordSyntax = IrTcl_getRecordSyntaxVal (argv[2]);
1624     }
1625     else if (argc == 2)
1626     {
1627         Tcl_AppendElement
1628             (interp,!p->preferredRecordSyntax ? "" :
1629              IrTcl_getRecordSyntaxStr(*p->preferredRecordSyntax));
1630     }
1631     return TCL_OK;
1632             
1633 }
1634
1635 /*
1636  * do_elementSetNames: Set/Get element Set Names
1637  */
1638 static int do_elementSetNames (void *obj, Tcl_Interp *interp,
1639                                int argc, char **argv)
1640 {
1641     IrTcl_SetCObj *p = obj;
1642
1643     if (argc == 0)
1644     {
1645         p->elementSetNames = NULL;
1646         return TCL_OK;
1647     }
1648     else if (argc == -1)
1649         return ir_tcl_strdel (interp, &p->elementSetNames);
1650     if (argc == 3)
1651     {
1652         xfree (p->elementSetNames);
1653         if (ir_tcl_strdup (interp, &p->elementSetNames, argv[2]) == TCL_ERROR)
1654             return TCL_ERROR;
1655     }
1656     Tcl_AppendResult (interp, p->elementSetNames, NULL);
1657     return TCL_OK;
1658 }
1659
1660 /*
1661  * do_smallSetElementSetNames: Set/Get small Set Element Set Names
1662  */
1663 static int do_smallSetElementSetNames (void *obj, Tcl_Interp *interp,
1664                                int argc, char **argv)
1665 {
1666     IrTcl_SetCObj *p = obj;
1667
1668     if (argc == 0)
1669     {
1670         p->smallSetElementSetNames = NULL;
1671         return TCL_OK;
1672     }
1673     else if (argc == -1)
1674         return ir_tcl_strdel (interp, &p->smallSetElementSetNames);
1675     if (argc == 3)
1676     {
1677         xfree (p->smallSetElementSetNames);
1678         if (ir_tcl_strdup (interp, &p->smallSetElementSetNames,
1679                            argv[2]) == TCL_ERROR)
1680             return TCL_ERROR;
1681     }
1682     Tcl_AppendResult (interp, p->smallSetElementSetNames, NULL);
1683     return TCL_OK;
1684 }
1685
1686 /*
1687  * do_mediumSetElementSetNames: Set/Get medium Set Element Set Names
1688  */
1689 static int do_mediumSetElementSetNames (void *obj, Tcl_Interp *interp,
1690                                int argc, char **argv)
1691 {
1692     IrTcl_SetCObj *p = obj;
1693
1694     if (argc == 0)
1695     {
1696         p->mediumSetElementSetNames = NULL;
1697         return TCL_OK;
1698     }
1699     else if (argc == -1)
1700         return ir_tcl_strdel (interp, &p->mediumSetElementSetNames);
1701     if (argc == 3)
1702     {
1703         xfree (p->mediumSetElementSetNames);
1704         if (ir_tcl_strdup (interp, &p->mediumSetElementSetNames,
1705                            argv[2]) == TCL_ERROR)
1706             return TCL_ERROR;
1707     }
1708     Tcl_AppendResult (interp, p->mediumSetElementSetNames, NULL);
1709     return TCL_OK;
1710 }
1711
1712 static IrTcl_Method ir_method_tab[] = {
1713 { "comstack",                    do_comstack, NULL },
1714 { "protocol",                    do_protocol, NULL },
1715 { "failback",                    do_failback, NULL },
1716 { "failInfo",                    do_failInfo, NULL },
1717 { "apduInfo",                    do_apduInfo, NULL },
1718 { "logLevel",                    do_logLevel, NULL },
1719
1720 { "eventType",                   do_eventType, NULL },
1721 { "connect",                     do_connect, NULL },
1722 { "protocolVersion",             do_protocolVersion, NULL },
1723 { "preferredMessageSize",        do_preferredMessageSize, NULL },
1724 { "maximumRecordSize",           do_maximumRecordSize, NULL },
1725 { "implementationName",          do_implementationName, NULL },
1726 { "implementationId",            do_implementationId, NULL },
1727 { "implementationVersion",       do_implementationVersion, NULL },
1728 { "targetImplementationName",    do_targetImplementationName, NULL },
1729 { "targetImplementationId",      do_targetImplementationId, NULL },
1730 { "targetImplementationVersion", do_targetImplementationVersion, NULL},
1731 { "userInformationField",        do_userInformationField, NULL},
1732 { "idAuthentication",            do_idAuthentication, NULL},
1733 { "options",                     do_options, NULL},
1734 { "init",                        do_init_request, NULL},
1735 { "initResult",                  do_initResult, NULL},
1736 { "disconnect",                  do_disconnect, NULL},
1737 { "callback",                    do_callback, NULL},
1738 { "initResponse",                do_initResponse, NULL},
1739 { "triggerResourceControl",      do_triggerResourceControl, NULL},
1740 { "initResponse",                do_initResponse, NULL},
1741 { NULL, NULL}
1742 };
1743
1744 static IrTcl_Method ir_set_c_method_tab[] = {
1745 { "databaseNames",               do_databaseNames, NULL},
1746 { "replaceIndicator",            do_replaceIndicator, NULL},
1747 { "queryType",                   do_queryType, NULL},
1748 { "preferredRecordSyntax",       do_preferredRecordSyntax, NULL},
1749 { "smallSetUpperBound",          do_smallSetUpperBound, NULL},
1750 { "largeSetLowerBound",          do_largeSetLowerBound, NULL},
1751 { "mediumSetPresentNumber",      do_mediumSetPresentNumber, NULL},
1752 { "referenceId",                 do_referenceId, NULL},
1753 { "elementSetNames",             do_elementSetNames, NULL},
1754 { "smallSetElementSetNames",     do_smallSetElementSetNames, NULL},
1755 { "mediumSetElementSetNames",    do_mediumSetElementSetNames, NULL},
1756 { NULL, NULL}
1757 };
1758
1759 /* 
1760  * ir_obj_method: IR Object methods
1761  */
1762 static int ir_obj_method (ClientData clientData, Tcl_Interp *interp,
1763                           int argc, char **argv)
1764 {
1765     IrTcl_Methods tab[3];
1766     IrTcl_Obj *p = clientData;
1767     int r;
1768
1769     if (argc < 2)
1770         return TCL_ERROR;
1771     
1772     tab[0].tab = ir_method_tab;
1773     tab[0].obj = p;
1774     tab[1].tab = ir_set_c_method_tab;
1775     tab[1].obj = &p->set_inher;
1776     tab[2].tab = NULL;
1777     
1778     ir_tcl_method (interp, argc, argv, tab, &r);
1779     return r;
1780 }
1781
1782 /* 
1783  * ir_obj_delete: IR Object disposal
1784  */
1785 static void ir_obj_delete (ClientData clientData)
1786 {
1787     IrTcl_Obj *obj = clientData;
1788     IrTcl_Methods tab[3];
1789
1790     --(obj->ref_count);
1791     if (obj->ref_count > 0)
1792         return;
1793     assert (obj->ref_count == 0);
1794
1795     logf (LOG_DEBUG, "ir object delete");
1796     tab[0].tab = ir_method_tab;
1797     tab[0].obj = obj;
1798     tab[1].tab = ir_set_c_method_tab;
1799     tab[1].obj = &obj->set_inher;
1800     tab[2].tab = NULL;
1801
1802     ir_tcl_method (NULL, -1, NULL, tab, NULL);
1803
1804     ir_tcl_del_q (obj);
1805     odr_destroy (obj->odr_in);
1806     odr_destroy (obj->odr_out);
1807     odr_destroy (obj->odr_pr);
1808     xfree (obj);
1809 }
1810
1811 /* 
1812  * ir_obj_init: IR Object initialization
1813  */
1814 int ir_obj_init (ClientData clientData, Tcl_Interp *interp,
1815                  int argc, char **argv, ClientData *subData,
1816                  ClientData parentData)
1817 {
1818     IrTcl_Methods tab[3];
1819     IrTcl_Obj *obj;
1820 #if CCL2RPN
1821     FILE *inf;
1822 #endif
1823
1824     if (argc != 2)
1825     {
1826         interp->result = "wrong # args";
1827         return TCL_ERROR;
1828     }
1829     obj = ir_tcl_malloc (sizeof(*obj));
1830     obj->ref_count = 1;
1831 #if CCL2RPN
1832     obj->bibset = ccl_qual_mk (); 
1833     if ((inf = fopen ("default.bib", "r")))
1834     {
1835         ccl_qual_file (obj->bibset, inf);
1836         fclose (inf);
1837     }
1838 #endif
1839
1840     logf (LOG_DEBUG, "ir object create %s", argv[1]);
1841     obj->odr_in = odr_createmem (ODR_DECODE);
1842     odr_choice_enable_bias (obj->odr_in, 0);
1843     obj->odr_out = odr_createmem (ODR_ENCODE);
1844     obj->odr_pr = odr_createmem (ODR_PRINT);
1845     obj->state = IR_TCL_R_Idle;
1846     obj->interp = interp;
1847
1848     obj->len_in = 0;
1849     obj->buf_in = NULL;
1850     obj->request_queue = NULL;
1851
1852     tab[0].tab = ir_method_tab;
1853     tab[0].obj = obj;
1854     tab[1].tab = ir_set_c_method_tab;
1855     tab[1].obj = &obj->set_inher;
1856     tab[2].tab = NULL;
1857
1858     if (ir_tcl_method (interp, 0, NULL, tab, NULL) == TCL_ERROR)
1859     {
1860         Tcl_AppendResult (interp, "Failed to initialize ", argv[1], NULL);
1861         return TCL_ERROR;
1862     }
1863     *subData = obj;
1864     return TCL_OK;
1865 }
1866
1867
1868 /* 
1869  * ir_obj_mk: IR Object creation
1870  */
1871 static int ir_obj_mk (ClientData clientData, Tcl_Interp *interp,
1872                       int argc, char **argv)
1873 {
1874     ClientData subData;
1875     int r = ir_obj_init (clientData, interp, argc, argv, &subData, 0);
1876     
1877     if (r == TCL_ERROR)
1878         return TCL_ERROR;
1879     Tcl_CreateCommand (interp, argv[1], ir_obj_method,
1880                        subData, ir_obj_delete);
1881     return TCL_OK;
1882 }
1883
1884 IrTcl_Class ir_obj_class = {
1885     "ir",
1886     ir_obj_init,
1887     ir_obj_method,
1888     ir_obj_delete
1889 };
1890
1891
1892 /* ------------------------------------------------------- */
1893 /*
1894  * do_search: Do search request
1895  */
1896 static int do_search (void *o, Tcl_Interp *interp, int argc, char **argv)
1897 {
1898     Z_SearchRequest *req;
1899     Z_Query query;
1900     Z_APDU *apdu;
1901     Odr_oct ccl_query;
1902     IrTcl_SetObj *obj = o;
1903     IrTcl_Obj *p;
1904     int r;
1905
1906     if (argc <= 0)
1907         return TCL_OK;
1908
1909     p = obj->parent;
1910     if (argc != 3)
1911     {
1912         logf (LOG_DEBUG, "search %s", *argv);
1913         interp->result = "wrong # args";
1914         return TCL_ERROR;
1915     }
1916     logf (LOG_DEBUG, "search %s %s", *argv, argv[2]);
1917     if (!obj->set_inher.num_databaseNames)
1918     {
1919         interp->result = "no databaseNames";
1920         return TCL_ERROR;
1921     }
1922     if (!p->cs_link)
1923     {
1924         interp->result = "search: not connected";
1925         return TCL_ERROR;
1926     }
1927     apdu = zget_APDU (p->odr_out, Z_APDU_searchRequest);
1928     req = apdu->u.searchRequest;
1929
1930     obj->start = 1;
1931
1932     set_referenceId (p->odr_out, &req->referenceId,
1933                      obj->set_inher.referenceId);
1934
1935     req->smallSetUpperBound = &obj->set_inher.smallSetUpperBound;
1936     req->largeSetLowerBound = &obj->set_inher.largeSetLowerBound;
1937     req->mediumSetPresentNumber = &obj->set_inher.mediumSetPresentNumber;
1938     req->replaceIndicator = &obj->set_inher.replaceIndicator;
1939     req->resultSetName = obj->setName ? obj->setName : "Default";
1940     logf (LOG_DEBUG, "Search, resultSetName %s", req->resultSetName);
1941     req->num_databaseNames = obj->set_inher.num_databaseNames;
1942     req->databaseNames = obj->set_inher.databaseNames;
1943     for (r=0; r < obj->set_inher.num_databaseNames; r++)
1944         logf (LOG_DEBUG, " Database %s", obj->set_inher.databaseNames[r]);
1945     if (obj->set_inher.preferredRecordSyntax)
1946     {
1947         struct oident ident;
1948
1949         ident.proto = p->protocol_type;
1950         ident.oclass = CLASS_RECSYN;
1951         ident.value = *obj->set_inher.preferredRecordSyntax;
1952         logf (LOG_DEBUG, "Preferred record syntax is %d", ident.value);
1953         req->preferredRecordSyntax = odr_oiddup (p->odr_out, 
1954                                                  oid_getoidbyent (&ident));
1955     }
1956     else
1957         req->preferredRecordSyntax = 0;
1958
1959     if (obj->set_inher.smallSetElementSetNames &&
1960         *obj->set_inher.smallSetElementSetNames)
1961     {
1962         Z_ElementSetNames *esn = odr_malloc (p->odr_out, sizeof(*esn));
1963         
1964         esn->which = Z_ElementSetNames_generic;
1965         esn->u.generic = obj->set_inher.smallSetElementSetNames;
1966         req->smallSetElementSetNames = esn;
1967     }
1968     else
1969         req->smallSetElementSetNames = NULL; 
1970     
1971     if (obj->set_inher.mediumSetElementSetNames &&
1972         *obj->set_inher.mediumSetElementSetNames)
1973     {
1974         Z_ElementSetNames *esn = odr_malloc (p->odr_out, sizeof(*esn));
1975         
1976         esn->which = Z_ElementSetNames_generic;
1977         esn->u.generic = obj->set_inher.mediumSetElementSetNames;
1978         req->mediumSetElementSetNames = esn;
1979     }
1980     else
1981         req->mediumSetElementSetNames = NULL; 
1982     
1983     req->query = &query;
1984    
1985     logf (LOG_DEBUG, "queryType %s", obj->set_inher.queryType);
1986     if (!strcmp (obj->set_inher.queryType, "rpn"))
1987     {
1988         Z_RPNQuery *RPNquery;
1989
1990         RPNquery = p_query_rpn (p->odr_out, p->protocol_type, argv[2]);
1991         if (!RPNquery)
1992         {
1993             Tcl_AppendResult (interp, "Syntax error in query", NULL);
1994             return TCL_ERROR;
1995         }
1996         query.which = Z_Query_type_1;
1997         query.u.type_1 = RPNquery;
1998     }
1999 #if CCL2RPN
2000     else if (!strcmp (obj->set_inher.queryType, "cclrpn"))
2001     {
2002         int error;
2003         int pos;
2004         struct ccl_rpn_node *rpn;
2005         Z_RPNQuery *RPNquery;
2006         oident bib1;
2007
2008         bib1.proto = p->protocol_type;
2009         bib1.oclass = CLASS_ATTSET;
2010         bib1.value = VAL_BIB1;
2011
2012         rpn = ccl_find_str(p->bibset, argv[2], &error, &pos);
2013         if (error)
2014         {
2015             Tcl_AppendResult (interp, "CCL error: ", 
2016                               ccl_err_msg(error), NULL);
2017             return TCL_ERROR;
2018         }
2019 #if 0
2020         ccl_pr_tree (rpn, stderr);
2021         fprintf (stderr, "\n");
2022 #endif
2023         assert((RPNquery = ccl_rpn_query(rpn)));
2024         RPNquery->attributeSetId = oid_getoidbyent (&bib1);
2025         query.which = Z_Query_type_1;
2026         query.u.type_1 = RPNquery;
2027     }
2028 #endif
2029     else if (!strcmp (obj->set_inher.queryType, "ccl"))
2030     {
2031         query.which = Z_Query_type_2;
2032         query.u.type_2 = &ccl_query;
2033         ccl_query.buf = (unsigned char *) argv[2];
2034         ccl_query.len = strlen (argv[2]);
2035     }
2036     else
2037     {
2038         interp->result = "unknown query method";
2039         return TCL_ERROR;
2040     }
2041     return ir_tcl_send_APDU (interp, p, apdu, "search", *argv);
2042 }
2043
2044 /*
2045  * do_searchResponse: add search response handler
2046  */
2047 static int do_searchResponse (void *o, Tcl_Interp *interp,
2048                               int argc, char **argv)
2049 {
2050     IrTcl_SetObj *obj = o;
2051
2052     if (argc == 0)
2053     {
2054         obj->searchResponse = NULL;
2055         return TCL_OK;
2056     }
2057     else if (argc == -1)
2058         return ir_tcl_strdel (interp, &obj->searchResponse);
2059     if (argc == 3)
2060     {
2061         xfree (obj->searchResponse);
2062         if (argv[2][0])
2063         {
2064             if (ir_tcl_strdup (interp, &obj->searchResponse, argv[2])
2065                 == TCL_ERROR)
2066                 return TCL_ERROR;
2067         }
2068         else
2069             obj->searchResponse = NULL;
2070     }
2071     return TCL_OK;
2072 }
2073
2074 /*
2075  * do_presentResponse: add present response handler
2076  */
2077 static int do_presentResponse (void *o, Tcl_Interp *interp,
2078                                int argc, char **argv)
2079 {
2080     IrTcl_SetObj *obj = o;
2081
2082     if (argc == 0)
2083     {
2084         obj->presentResponse = NULL;
2085         return TCL_OK;
2086     }
2087     else if (argc == -1)
2088         return ir_tcl_strdel (interp, &obj->presentResponse);
2089     if (argc == 3)
2090     {
2091         xfree (obj->presentResponse);
2092         if (argv[2][0])
2093         {
2094             if (ir_tcl_strdup (interp, &obj->presentResponse, argv[2])
2095                 == TCL_ERROR)
2096                 return TCL_ERROR;
2097         }
2098         else
2099             obj->presentResponse = NULL;
2100     }
2101     return TCL_OK;
2102 }
2103
2104 /*
2105  * do_resultCount: Get number of hits
2106  */
2107 static int do_resultCount (void *o, Tcl_Interp *interp,
2108                        int argc, char **argv)
2109 {
2110     IrTcl_SetObj *obj = o;
2111
2112     if (argc <= 0)
2113     {
2114         obj->resultCount = 0;
2115         return TCL_OK;
2116     }
2117     return ir_tcl_get_set_int (&obj->resultCount, interp, argc, argv);
2118 }
2119
2120 /*
2121  * do_searchStatus: Get search status (after search response)
2122  */
2123 static int do_searchStatus (void *o, Tcl_Interp *interp,
2124                             int argc, char **argv)
2125 {
2126     IrTcl_SetObj *obj = o;
2127
2128     if (argc <= 0)
2129         return TCL_OK;
2130     return ir_tcl_get_set_int (&obj->searchStatus, interp, argc, argv);
2131 }
2132
2133 /*
2134  * do_presentStatus: Get search status (after search/present response)
2135  */
2136 static int do_presentStatus (void *o, Tcl_Interp *interp,
2137                             int argc, char **argv)
2138 {
2139     IrTcl_SetObj *obj = o;
2140
2141     if (argc <= 0)
2142         return TCL_OK;
2143     return ir_tcl_get_set_int (&obj->presentStatus, interp, argc, argv);
2144 }
2145
2146 /*
2147  * do_nextResultSetPosition: Get next result set position
2148  *       (after search/present response)
2149  */
2150 static int do_nextResultSetPosition (void *o, Tcl_Interp *interp,
2151                                      int argc, char **argv)
2152 {
2153     IrTcl_SetObj *obj = o;
2154
2155     if (argc <= 0)
2156     {
2157         obj->nextResultSetPosition = 0;
2158         return TCL_OK;
2159     }
2160     return ir_tcl_get_set_int (&obj->nextResultSetPosition, interp,
2161                                argc, argv);
2162 }
2163
2164 /*
2165  * do_setName: Set result Set name
2166  */
2167 static int do_setName (void *o, Tcl_Interp *interp,
2168                        int argc, char **argv)
2169 {
2170     IrTcl_SetObj *obj = o;
2171
2172     if (argc == 0)
2173         return ir_tcl_strdup (interp, &obj->setName, "Default");
2174     else if (argc == -1)
2175         return ir_tcl_strdel (interp, &obj->setName);
2176     if (argc == 3)
2177     {
2178         xfree (obj->setName);
2179         if (ir_tcl_strdup (interp, &obj->setName, argv[2])
2180             == TCL_ERROR)
2181             return TCL_ERROR;
2182     }
2183     Tcl_AppendElement (interp, obj->setName);
2184     return TCL_OK;
2185 }
2186
2187 /*
2188  * do_numberOfRecordsReturned: Get number of records returned
2189  */
2190 static int do_numberOfRecordsReturned (void *o, Tcl_Interp *interp,
2191                                        int argc, char **argv)
2192 {
2193     IrTcl_SetObj *obj = o;
2194
2195     if (argc <= 0)
2196     {
2197         obj->numberOfRecordsReturned = 0;
2198         return TCL_OK;
2199     }
2200     return ir_tcl_get_set_int (&obj->numberOfRecordsReturned, interp,
2201                                argc, argv);
2202 }
2203
2204 /*
2205  * do_type: Return type (if any) at position.
2206  */
2207 static int do_type (void *o, Tcl_Interp *interp, int argc, char **argv)
2208 {
2209     IrTcl_SetObj *obj = o;
2210     int offset;
2211     IrTcl_RecordList *rl;
2212
2213     if (argc == 0)
2214     {
2215         obj->record_list = NULL;
2216         return TCL_OK;
2217     }
2218     else if (argc == -1)
2219     {
2220         delete_IR_records (obj);
2221         return TCL_OK;
2222     }
2223     if (argc != 3)
2224     {
2225         sprintf (interp->result, "wrong # args");
2226         return TCL_ERROR;
2227     }
2228     if (Tcl_GetInt (interp, argv[2], &offset)==TCL_ERROR)
2229         return TCL_ERROR;
2230     rl = find_IR_record (obj, offset);
2231     if (!rl)
2232     {
2233         logf (LOG_DEBUG, "No record at position %d", offset);
2234         return TCL_OK;
2235     }
2236     switch (rl->which)
2237     {
2238     case Z_NamePlusRecord_databaseRecord:
2239         interp->result = "DB";
2240         break;
2241     case Z_NamePlusRecord_surrogateDiagnostic:
2242         interp->result = "SD";
2243         break;
2244     }
2245     return TCL_OK;
2246 }
2247
2248
2249 /*
2250  * do_recordType: Return record type (if any) at position.
2251  */
2252 static int do_recordType (void *o, Tcl_Interp *interp, int argc, char **argv)
2253 {
2254     IrTcl_SetObj *obj = o;
2255     int offset;
2256     IrTcl_RecordList *rl;
2257
2258     if (argc == 0)
2259     {
2260         return TCL_OK;
2261     }
2262     else if (argc == -1)
2263     {
2264         return TCL_OK;
2265     }
2266     if (argc != 3)
2267     {
2268         sprintf (interp->result, "wrong # args");
2269         return TCL_ERROR;
2270     }
2271     if (Tcl_GetInt (interp, argv[2], &offset)==TCL_ERROR)
2272         return TCL_ERROR;
2273     rl = find_IR_record (obj, offset);
2274     if (!rl)
2275         return TCL_OK;
2276     if (rl->which != Z_NamePlusRecord_databaseRecord)
2277     {
2278         Tcl_AppendResult (interp, "No DB record at #", argv[2], NULL);
2279         return TCL_ERROR;
2280     }
2281     Tcl_AppendElement (interp, (char*)
2282                        IrTcl_getRecordSyntaxStr (rl->u.dbrec.type));
2283     return TCL_OK;
2284 }
2285
2286 /*
2287  * set record elements (for record extraction)
2288  */
2289 static int do_recordElements (void *o, Tcl_Interp *interp,
2290                               int argc, char **argv)
2291 {
2292     IrTcl_SetObj *obj = o;
2293
2294     if (argc == 0)
2295     {
2296         obj->recordElements = NULL;
2297         return TCL_OK;
2298     }
2299     else if (argc == -1)
2300         return ir_tcl_strdel (NULL, &obj->recordElements);
2301     if (argc > 3)
2302     {
2303         sprintf (interp->result, "wrong # args");
2304         return TCL_ERROR;
2305     }
2306     if (argc == 3)
2307     {
2308         xfree (obj->recordElements);
2309         return ir_tcl_strdup (NULL, &obj->recordElements, 
2310                               (*argv[2] ? argv[2] : NULL));
2311     }
2312     Tcl_AppendResult (interp, obj->recordElements, NULL);
2313     return TCL_OK;
2314 }
2315
2316 /*
2317  * ir_diagResult 
2318  */
2319 static int ir_diagResult (Tcl_Interp *interp, IrTcl_Diagnostic *list, int num)
2320 {
2321     char buf[20];
2322     int i;
2323     const char *cp;
2324
2325     for (i = 0; i<num; i++)
2326     {
2327         sprintf (buf, "%d", list[i].condition);
2328         Tcl_AppendElement (interp, buf);
2329         cp = diagbib1_str (list[i].condition);
2330         if (cp)
2331             Tcl_AppendElement (interp, (char*) cp);
2332         else
2333             Tcl_AppendElement (interp, "");
2334         if (list[i].addinfo)
2335             Tcl_AppendElement (interp, (char*) list[i].addinfo);
2336         else
2337             Tcl_AppendElement (interp, "");
2338     }
2339     return TCL_OK;
2340 }
2341
2342 /*
2343  * do_diag: Return diagnostic record info
2344  */
2345 static int do_diag (void *o, Tcl_Interp *interp, int argc, char **argv)
2346 {
2347     IrTcl_SetObj *obj = o;
2348     int offset;
2349     IrTcl_RecordList *rl;
2350
2351     if (argc <= 0)
2352         return TCL_OK;
2353     if (argc != 3)
2354     {
2355         sprintf (interp->result, "wrong # args");
2356         return TCL_ERROR;
2357     }
2358     if (Tcl_GetInt (interp, argv[2], &offset)==TCL_ERROR)
2359         return TCL_ERROR;
2360     rl = find_IR_record (obj, offset);
2361     if (!rl)
2362     {
2363         Tcl_AppendResult (interp, "No record at #", argv[2], NULL);
2364         return TCL_ERROR;
2365     }
2366     if (rl->which != Z_NamePlusRecord_surrogateDiagnostic)
2367     {
2368         Tcl_AppendResult (interp, "No Diagnostic record at #", argv[2], NULL);
2369         return TCL_ERROR;
2370     }
2371     return ir_diagResult (interp, rl->u.surrogateDiagnostics.list,
2372                           rl->u.surrogateDiagnostics.num);
2373 }
2374
2375 /*
2376  * do_getMarc: Get ISO2709 Record lines/fields
2377  */
2378 static int do_getMarc (void *o, Tcl_Interp *interp, int argc, char **argv)
2379 {
2380     IrTcl_SetObj *obj = o;
2381     int offset;
2382     IrTcl_RecordList *rl;
2383
2384     if (argc <= 0)
2385         return TCL_OK;
2386     if (argc < 7)
2387     {
2388         sprintf (interp->result, "wrong # args");
2389         return TCL_ERROR;
2390     }
2391     if (Tcl_GetInt (interp, argv[2], &offset)==TCL_ERROR)
2392         return TCL_ERROR;
2393     rl = find_IR_record (obj, offset);
2394     if (!rl)
2395     {
2396         Tcl_AppendResult (interp, "No record at #", argv[2], NULL);
2397         return TCL_ERROR;
2398     }
2399     if (rl->which != Z_NamePlusRecord_databaseRecord)
2400     {
2401         Tcl_AppendResult (interp, "No DB record at #", argv[2], NULL);
2402         return TCL_ERROR;
2403     }
2404     return ir_tcl_get_marc (interp, rl->u.dbrec.buf, argc, argv);
2405 }
2406
2407 /*
2408  * do_getSutrs: Get SUTRS Record
2409  */
2410 static int do_getSutrs (void *o, Tcl_Interp *interp, int argc, char **argv)
2411 {
2412     IrTcl_SetObj *obj = o;
2413     int offset;
2414     IrTcl_RecordList *rl;
2415
2416     if (argc <= 0)
2417         return TCL_OK;
2418     if (argc != 3)
2419     {
2420         sprintf (interp->result, "wrong # args");
2421         return TCL_ERROR;
2422     }
2423     if (Tcl_GetInt (interp, argv[2], &offset)==TCL_ERROR)
2424         return TCL_ERROR;
2425     rl = find_IR_record (obj, offset);
2426     if (!rl)
2427     {
2428         Tcl_AppendResult (interp, "No record at #", argv[2], NULL);
2429         return TCL_ERROR;
2430     }
2431     if (rl->which != Z_NamePlusRecord_databaseRecord)
2432     {
2433         Tcl_AppendResult (interp, "No DB record at #", argv[2], NULL);
2434         return TCL_ERROR;
2435     }
2436     if (rl->u.dbrec.type != VAL_SUTRS)
2437         return TCL_OK;
2438     Tcl_AppendElement (interp, rl->u.dbrec.buf);
2439     return TCL_OK;
2440 }
2441
2442
2443 /*
2444  * do_getGrs: Get a GRS-1 Record
2445  */
2446 static int do_getGrs (void *o, Tcl_Interp *interp, int argc, char **argv)
2447 {
2448     IrTcl_SetObj *obj = o;
2449     int offset;
2450     IrTcl_RecordList *rl;
2451
2452     if (argc <= 0)
2453         return TCL_OK;
2454     if (argc < 3)
2455     {
2456         sprintf (interp->result, "wrong # args");
2457         return TCL_ERROR;
2458     }
2459     if (Tcl_GetInt (interp, argv[2], &offset)==TCL_ERROR)
2460         return TCL_ERROR;
2461     rl = find_IR_record (obj, offset);
2462     if (!rl)
2463     {
2464         Tcl_AppendResult (interp, "No record at #", argv[2], NULL);
2465         return TCL_ERROR;
2466     }
2467     if (rl->which != Z_NamePlusRecord_databaseRecord)
2468     {
2469         Tcl_AppendResult (interp, "No DB record at #", argv[2], NULL);
2470         return TCL_ERROR;
2471     }
2472     if (rl->u.dbrec.type != VAL_GRS1)
2473         return TCL_OK;
2474     return ir_tcl_get_grs (interp, rl->u.dbrec.u.grs1, argc, argv);
2475 }
2476
2477
2478 /*
2479  * do_getExplain: Get an Explain Record
2480  */
2481 static int do_getExplain (void *o, Tcl_Interp *interp, int argc, char **argv)
2482 {
2483     IrTcl_SetObj *obj = o;
2484     IrTcl_Obj *p = obj->parent;
2485     void *rr;
2486     Z_ext_typeent *etype;
2487     int offset;
2488     IrTcl_RecordList *rl;
2489
2490     if (argc <= 0)
2491         return TCL_OK;
2492     if (argc < 3)
2493     {
2494         sprintf (interp->result, "wrong # args");
2495         return TCL_ERROR;
2496     }
2497     if (Tcl_GetInt (interp, argv[2], &offset)==TCL_ERROR)
2498         return TCL_ERROR;
2499     rl = find_IR_record (obj, offset);
2500     if (!rl)
2501     {
2502         Tcl_AppendResult (interp, "No record at #", argv[2], NULL);
2503         return TCL_ERROR;
2504     }
2505     if (rl->which != Z_NamePlusRecord_databaseRecord)
2506     {
2507         Tcl_AppendResult (interp, "No DB record at #", argv[2], NULL);
2508         return TCL_ERROR;
2509     }
2510     if (rl->u.dbrec.type != VAL_EXPLAIN)
2511         return TCL_OK;
2512
2513     if (!(etype = z_ext_getentbyref (VAL_EXPLAIN)))
2514         return TCL_OK;
2515
2516     odr_setbuf (p->odr_in, rl->u.dbrec.buf, rl->u.dbrec.size, 0);
2517     if (!(*etype->fun)(p->odr_in, &rr, 0))
2518         return TCL_OK;
2519     
2520     if (etype->what != Z_External_explainRecord)
2521         return TCL_OK;
2522
2523     return ir_tcl_get_explain (interp, rr, argc, argv);
2524 }
2525
2526 /*
2527  * do_responseStatus: Return response status (present or search)
2528  */
2529 static int do_responseStatus (void *o, Tcl_Interp *interp, 
2530                              int argc, char **argv)
2531 {
2532     IrTcl_SetObj *obj = o;
2533
2534     if (argc == 0)
2535     {
2536         obj->recordFlag = 0;
2537         obj->nonSurrogateDiagnosticNum = 0;
2538         obj->nonSurrogateDiagnosticList = NULL;
2539         return TCL_OK;
2540     }
2541     else if (argc == -1)
2542     {
2543         ir_deleteDiags (&obj->nonSurrogateDiagnosticList,
2544                         &obj->nonSurrogateDiagnosticNum);
2545         return TCL_OK;
2546     }
2547     if (!obj->recordFlag)
2548     {
2549         Tcl_AppendElement (interp, "OK");
2550         return TCL_OK;
2551     }
2552     switch (obj->which)
2553     {
2554     case Z_Records_DBOSD:
2555         Tcl_AppendElement (interp, "DBOSD");
2556         break;
2557     case Z_Records_NSD:
2558         Tcl_AppendElement (interp, "NSD");
2559         return ir_diagResult (interp, obj->nonSurrogateDiagnosticList,
2560                               obj->nonSurrogateDiagnosticNum);
2561     }
2562     return TCL_OK;
2563 }
2564
2565 /*
2566  * do_present: Perform Present Request
2567  */
2568
2569 static int do_present (void *o, Tcl_Interp *interp, int argc, char **argv)
2570 {
2571     IrTcl_SetObj *obj = o;
2572     IrTcl_Obj *p;
2573     Z_APDU *apdu;
2574     Z_PresentRequest *req;
2575     int start;
2576     int number;
2577
2578     if (argc <= 0)
2579         return TCL_OK;
2580     if (argc >= 3)
2581     {
2582         if (Tcl_GetInt (interp, argv[2], &start) == TCL_ERROR)
2583             return TCL_ERROR;
2584     }
2585     else
2586         start = 1;
2587     if (argc >= 4)
2588     {
2589         if (Tcl_GetInt (interp, argv[3], &number) == TCL_ERROR)
2590             return TCL_ERROR;
2591     }
2592     else 
2593         number = 10;
2594     logf (LOG_DEBUG, "present %s %d %d", *argv, start, number);
2595     p = obj->parent;
2596     if (!p->cs_link)
2597     {
2598         interp->result = "present: not connected";
2599         return TCL_ERROR;
2600     }
2601
2602     obj->start = start;
2603     obj->number = number;
2604
2605     apdu = zget_APDU (p->odr_out, Z_APDU_presentRequest);
2606     req = apdu->u.presentRequest;
2607
2608     set_referenceId (p->odr_out, &req->referenceId,
2609                      obj->set_inher.referenceId);
2610
2611     req->resultSetId = obj->setName ? obj->setName : "Default";
2612     
2613     req->resultSetStartPoint = &start;
2614     req->numberOfRecordsRequested = &number;
2615     if (obj->set_inher.preferredRecordSyntax)
2616     {
2617         struct oident ident;
2618
2619         ident.proto = p->protocol_type;
2620         ident.oclass = CLASS_RECSYN;
2621         ident.value = *obj->set_inher.preferredRecordSyntax;
2622         logf (LOG_DEBUG, "Preferred record syntax is %d", ident.value);
2623         req->preferredRecordSyntax = odr_oiddup (p->odr_out, 
2624                                                  oid_getoidbyent (&ident));
2625     }
2626     else
2627         req->preferredRecordSyntax = 0;
2628
2629     if (obj->set_inher.elementSetNames && *obj->set_inher.elementSetNames)
2630     {
2631         Z_ElementSetNames *esn = odr_malloc (p->odr_out, sizeof(*esn));
2632         Z_RecordComposition *compo = odr_malloc (p->odr_out, sizeof(*compo));
2633
2634         esn->which = Z_ElementSetNames_generic;
2635         esn->u.generic = obj->set_inher.elementSetNames;
2636
2637         req->recordComposition = compo;
2638         compo->which = Z_RecordComp_simple;
2639         compo->u.simple = esn;
2640     }
2641     else
2642         req->recordComposition = NULL;
2643     return ir_tcl_send_APDU (interp, p, apdu, "present", *argv);
2644 }
2645
2646 #define IR_TCL_RECORD_ENCODING_ISO2709  1
2647 #define IR_TCL_RECORD_ENCODING_RAW      2
2648
2649 typedef struct {
2650     int encoding;
2651     int syntax;
2652     int size;
2653 } IrTcl_FileRecordHead;
2654
2655 /*
2656  * do_loadFile: Load result set from file
2657  */
2658 static int do_loadFile (void *o, Tcl_Interp *interp,
2659                         int argc, char **argv)
2660 {
2661     IrTcl_SetObj *setobj = o;
2662     FILE *inf;
2663     size_t size;
2664     int offset;
2665     int start = 1;
2666     int number = 30000;
2667     char *buf;
2668     
2669     if (argc <= 0)
2670         return TCL_OK;
2671     if (argc < 3)
2672     {
2673         interp->result = "wrong # args";
2674         return TCL_ERROR;
2675     }
2676     if (argc > 3)
2677         start = atoi (argv[3]);
2678     if (argc > 4)
2679         number = atoi (argv[4]);
2680     offset = start;
2681
2682     inf = fopen (argv[2], "r");
2683     if (!inf)
2684     {
2685         Tcl_AppendResult (interp, "Cannot open ", argv[2], NULL);
2686         return TCL_ERROR;
2687     }
2688     while (offset < (start+number))
2689     {
2690         IrTcl_FileRecordHead head;
2691         IrTcl_RecordList *rl;
2692
2693         if (fread (&head, sizeof(head), 1, inf) < 1)
2694             break;
2695         rl = new_IR_record (setobj, offset,
2696                             Z_NamePlusRecord_databaseRecord,
2697                             (argc > 5) ? argv[5] : NULL);
2698         rl->u.dbrec.type = head.syntax;
2699         if (head.encoding == IR_TCL_RECORD_ENCODING_ISO2709)
2700         {
2701             if (!(buf = ir_tcl_fread_marc (inf, &size)))
2702                 break;
2703             rl->u.dbrec.buf = buf;
2704             rl->u.dbrec.size = size;
2705             if (size != head.size)
2706             {
2707                 Tcl_AppendResult (interp, "Bad ISO2709 encoding in file",
2708                                   argv[2], NULL);
2709                 fclose (inf);
2710                 return TCL_ERROR;
2711             }
2712         } 
2713         else if (head.encoding == IR_TCL_RECORD_ENCODING_RAW)
2714         {
2715             rl->u.dbrec.size = head.size;
2716             rl->u.dbrec.buf = ir_tcl_malloc (head.size + 1);
2717             if (fread (rl->u.dbrec.buf, rl->u.dbrec.size, 1, inf) < 1)
2718             {
2719                 Tcl_AppendResult (interp, "Bad RAW encoding in file",
2720                                   argv[2], NULL);
2721                 fclose (inf);
2722                 return TCL_ERROR;
2723             }
2724             rl->u.dbrec.buf[rl->u.dbrec.size] = '\0';
2725         }
2726         else
2727         {
2728             rl->u.dbrec.buf = NULL;
2729             rl->u.dbrec.size = 0;
2730             Tcl_AppendResult (interp, "Bad encoding in file", argv[2], NULL);
2731             fclose (inf);
2732             return TCL_ERROR;
2733         }
2734         offset++;
2735     }
2736     setobj->numberOfRecordsReturned = offset - start;
2737     fclose (inf);
2738     return TCL_OK;
2739 }
2740
2741 /*
2742  * do_saveFile: Save result set on file
2743  */
2744 static int do_saveFile (void *o, Tcl_Interp *interp,
2745                         int argc, char **argv)
2746 {
2747     IrTcl_SetObj *setobj = o;
2748     FILE *outf;
2749     int offset;
2750     int start = 1;
2751     int number = 30000;
2752     IrTcl_RecordList *rl;
2753     
2754     if (argc <= 0)
2755         return TCL_OK;
2756     if (argc < 3)
2757     {
2758         interp->result = "wrong # args";
2759         return TCL_ERROR;
2760     }
2761     if (argc > 3)
2762         start = atoi (argv[3]);
2763     if (argc > 4)
2764         number = atoi (argv[4]);
2765     offset = start;
2766
2767     outf = fopen (argv[2], "w");
2768     if (!outf)
2769     {
2770         Tcl_AppendResult (interp, "Cannot open ", argv[2], NULL);
2771         return TCL_ERROR;
2772     }
2773     while (offset < (start+number) && (rl = find_IR_record (setobj, offset)))
2774     {
2775         if (rl->which == Z_NamePlusRecord_databaseRecord &&
2776             rl->u.dbrec.buf && rl->u.dbrec.size)
2777         {
2778             IrTcl_FileRecordHead head;
2779
2780             head.encoding = IR_TCL_RECORD_ENCODING_RAW;
2781             head.syntax = rl->u.dbrec.type;
2782             head.size = rl->u.dbrec.size;
2783             if (fwrite (&head, sizeof(head), 1, outf) < 1)
2784             {
2785                 Tcl_AppendResult (interp, "Cannot write ", argv[2], NULL);
2786                 return TCL_ERROR;
2787             }
2788             if (fwrite (rl->u.dbrec.buf, rl->u.dbrec.size, 1, outf) < 1)
2789             {
2790                 Tcl_AppendResult (interp, "Cannot write ", argv[2], NULL);
2791                 return TCL_ERROR;
2792             }
2793         }
2794         offset++;
2795     }
2796     if (fclose (outf))
2797     {
2798         Tcl_AppendResult (interp, "Cannot write ", argv[2], NULL);
2799         return TCL_ERROR;
2800     }
2801     return TCL_OK;
2802 }
2803
2804
2805 static IrTcl_Method ir_set_method_tab[] = {
2806     { "search",                  do_search, NULL},
2807     { "searchResponse",          do_searchResponse, NULL},
2808     { "presentResponse",         do_presentResponse, NULL},
2809     { "searchStatus",            do_searchStatus, NULL},
2810     { "presentStatus",           do_presentStatus, NULL},
2811     { "nextResultSetPosition",   do_nextResultSetPosition, NULL},
2812     { "setName",                 do_setName, NULL},
2813     { "resultCount",             do_resultCount, NULL},
2814     { "numberOfRecordsReturned", do_numberOfRecordsReturned, NULL},
2815     { "present",                 do_present, NULL},
2816     { "type",                    do_type, NULL},
2817     { "getMarc",                 do_getMarc, NULL},
2818     { "getSutrs",                do_getSutrs, NULL},
2819     { "getGrs",                  do_getGrs, NULL},
2820     { "getExplain",              do_getExplain, NULL},
2821     { "recordType",              do_recordType, NULL},
2822     { "recordElements",          do_recordElements, NULL},
2823     { "diag",                    do_diag, NULL},
2824     { "responseStatus",          do_responseStatus, NULL},
2825     { "loadFile",                do_loadFile, NULL},
2826     { "saveFile",                do_saveFile, NULL},
2827     { NULL, NULL}
2828 };
2829
2830 /* 
2831  * ir_set_obj_method: IR Set Object methods
2832  */
2833 static int ir_set_obj_method (ClientData clientData, Tcl_Interp *interp,
2834                           int argc, char **argv)
2835 {
2836     IrTcl_Methods tabs[3];
2837     IrTcl_SetObj *p = clientData;
2838     int r;
2839
2840     if (argc < 2)
2841     {
2842         interp->result = "wrong # args";
2843         return TCL_ERROR;
2844     }
2845     tabs[0].tab = ir_set_method_tab;
2846     tabs[0].obj = p;
2847     tabs[1].tab = ir_set_c_method_tab;
2848     tabs[1].obj = &p->set_inher;
2849     tabs[2].tab = NULL;
2850
2851     ir_tcl_method (interp, argc, argv, tabs, &r);
2852     return r;
2853 }
2854
2855 /* 
2856  * ir_set_obj_delete: IR Set Object disposal
2857  */
2858 static void ir_set_obj_delete (ClientData clientData)
2859 {
2860     IrTcl_Methods tabs[3];
2861     IrTcl_SetObj *p = clientData;
2862
2863     logf (LOG_DEBUG, "ir set delete");
2864
2865     tabs[0].tab = ir_set_method_tab;
2866     tabs[0].obj = p;
2867     tabs[1].tab = ir_set_c_method_tab;
2868     tabs[1].obj = &p->set_inher;
2869     tabs[2].tab = NULL;
2870
2871     ir_tcl_method (NULL, -1, NULL, tabs, NULL);
2872
2873     xfree (p);
2874 }
2875
2876 /*
2877  * ir_set_obj_init: IR Set Object initialization
2878  */
2879 static int ir_set_obj_init (ClientData clientData, Tcl_Interp *interp,
2880                             int argc, char **argv, ClientData *subData,
2881                             ClientData parentData)
2882 {
2883     IrTcl_Methods tabs[3];
2884     IrTcl_SetObj *obj;
2885
2886     if (argc < 2 || argc > 3)
2887     {
2888         interp->result = "wrong # args";
2889         return TCL_ERROR;
2890     }
2891     obj = ir_tcl_malloc (sizeof(*obj));
2892     logf (LOG_DEBUG, "ir set create %s", argv[1]);
2893     if (parentData)
2894     {
2895         int i;
2896         IrTcl_SetCObj *dst;
2897         IrTcl_SetCObj *src;
2898
2899         obj->parent = (IrTcl_Obj *) parentData;
2900
2901         dst = &obj->set_inher;
2902         src = &obj->parent->set_inher;
2903
2904         if ((dst->num_databaseNames = src->num_databaseNames))
2905         {
2906             dst->databaseNames =
2907                 ir_tcl_malloc (sizeof (*dst->databaseNames)
2908                                * (1+dst->num_databaseNames));
2909             for (i = 0; i < dst->num_databaseNames; i++)
2910                 if (ir_tcl_strdup (interp, &dst->databaseNames[i],
2911                                    src->databaseNames[i]) == TCL_ERROR)
2912                     return TCL_ERROR;
2913             dst->databaseNames[i] = NULL;
2914         }
2915         else
2916             dst->databaseNames = NULL;
2917         if (ir_tcl_strdup (interp, &dst->queryType, src->queryType)
2918             == TCL_ERROR)
2919             return TCL_ERROR;
2920
2921         if (ir_tcl_strdup (interp, &dst->referenceId, src->referenceId)
2922             == TCL_ERROR)
2923             return TCL_ERROR;
2924
2925         if (ir_tcl_strdup (interp, &dst->elementSetNames, src->elementSetNames)
2926             == TCL_ERROR)
2927             return TCL_ERROR;
2928
2929         if (ir_tcl_strdup (interp, &dst->smallSetElementSetNames,
2930                            src->smallSetElementSetNames)
2931             == TCL_ERROR)
2932             return TCL_ERROR;
2933
2934         if (ir_tcl_strdup (interp, &dst->mediumSetElementSetNames,
2935                            src->mediumSetElementSetNames)
2936             == TCL_ERROR)
2937             return TCL_ERROR;
2938
2939         if (src->preferredRecordSyntax && 
2940             (dst->preferredRecordSyntax 
2941              = ir_tcl_malloc (sizeof(*dst->preferredRecordSyntax))))
2942             *dst->preferredRecordSyntax = *src->preferredRecordSyntax;
2943         else
2944             dst->preferredRecordSyntax = NULL;
2945         dst->replaceIndicator = src->replaceIndicator;
2946         dst->smallSetUpperBound = src->smallSetUpperBound;
2947         dst->largeSetLowerBound = src->largeSetLowerBound;
2948         dst->mediumSetPresentNumber = src->mediumSetPresentNumber;
2949     }   
2950     else
2951         obj->parent = NULL;
2952
2953     tabs[0].tab = ir_set_method_tab;
2954     tabs[0].obj = obj;
2955     tabs[1].tab = NULL;
2956
2957     if (ir_tcl_method (interp, 0, NULL, tabs, NULL) == TCL_ERROR)
2958         return TCL_ERROR;
2959
2960     *subData = obj;
2961     return TCL_OK;
2962 }
2963
2964 /*
2965  * ir_set_obj_mk: IR Set Object creation
2966  */
2967 static int ir_set_obj_mk (ClientData clientData, Tcl_Interp *interp,
2968                           int argc, char **argv)
2969 {
2970     ClientData subData;
2971     ClientData parentData = 0;
2972     int r;
2973
2974     if (argc == 3)
2975     {
2976         Tcl_CmdInfo parent_info;
2977         if (!Tcl_GetCommandInfo (interp, argv[2], &parent_info))
2978         {
2979             interp->result = "No parent";
2980             return TCL_ERROR;
2981         }
2982         parentData = parent_info.clientData;
2983     }
2984     r = ir_set_obj_init (clientData, interp, argc, argv, &subData, parentData);
2985     if (r == TCL_ERROR)
2986         return TCL_ERROR;
2987     Tcl_CreateCommand (interp, argv[1], ir_set_obj_method,
2988                        subData, ir_set_obj_delete);
2989     return TCL_OK;
2990 }
2991
2992 IrTcl_Class ir_set_obj_class = {
2993     "ir-set",
2994     ir_set_obj_init,
2995     ir_set_obj_method,
2996     ir_set_obj_delete
2997 };
2998
2999 /* ------------------------------------------------------- */
3000
3001 /*
3002  * do_scan: Perform scan 
3003  */
3004 static int do_scan (void *o, Tcl_Interp *interp, int argc, char **argv)
3005 {
3006     Z_ScanRequest *req;
3007     Z_APDU *apdu;
3008     IrTcl_ScanObj *obj = o;
3009     IrTcl_Obj *p = obj->parent;
3010 #if CCL2RPN
3011     oident bib1;
3012     struct ccl_rpn_node *rpn;
3013     int pos;
3014 #endif
3015
3016     if (argc <= 0)
3017         return TCL_OK;
3018     if (argc != 3)
3019     {
3020         interp->result = "wrong # args";
3021         return TCL_ERROR;
3022     }
3023     logf (LOG_DEBUG, "scan %s %s", *argv, argv[2]);
3024     if (!p->set_inher.num_databaseNames)
3025     {
3026         interp->result = "no databaseNames";
3027         return TCL_ERROR;
3028     }
3029     if (!p->cs_link)
3030     {
3031         interp->result = "scan: not connected";
3032         return TCL_ERROR;
3033     }
3034
3035     apdu = zget_APDU (p->odr_out, Z_APDU_scanRequest);
3036     req = apdu->u.scanRequest;
3037
3038     set_referenceId (p->odr_out, &req->referenceId, p->set_inher.referenceId);
3039     req->num_databaseNames = p->set_inher.num_databaseNames;
3040     req->databaseNames = p->set_inher.databaseNames;
3041
3042 #if !CCL2RPN
3043     if (!(req->termListAndStartPoint =
3044           p_query_scan (p->odr_out, p->protocol_type,
3045                         &req->attributeSet, argv[2])))
3046     {
3047         Tcl_AppendResult (interp, "Syntax error in query", NULL);
3048         return TCL_ERROR;
3049     }
3050 #else
3051     rpn = ccl_find_str(p->bibset, argv[2], &r, &pos);
3052     if (r)
3053     {
3054         Tcl_AppendResult (interp, "CCL error: ", ccl_err_msg (r), NULL);
3055         return TCL_ERROR;
3056     }
3057     bib1.proto = p->protocol_type;
3058     bib1.oclass = CLASS_ATTSET;
3059     bib1.value = VAL_BIB1;
3060
3061     req->attributeSet = oid_getoidbyent (&bib1);
3062     if (!(req->termListAndStartPoint = ccl_scan_query (rpn)))
3063         return TCL_ERROR;
3064 #endif
3065     req->stepSize = &obj->stepSize;
3066     req->numberOfTermsRequested = &obj->numberOfTermsRequested;
3067     req->preferredPositionInResponse = &obj->preferredPositionInResponse;
3068     logf (LOG_DEBUG, "stepSize=%d", *req->stepSize);
3069     logf (LOG_DEBUG, "numberOfTermsRequested=%d",
3070           *req->numberOfTermsRequested);
3071     logf (LOG_DEBUG, "preferredPositionInResponse=%d",
3072           *req->preferredPositionInResponse);
3073     
3074     return ir_tcl_send_APDU (interp, p, apdu, "scan", *argv);
3075 }
3076
3077 /*
3078  * do_scanResponse: add scan response handler
3079  */
3080 static int do_scanResponse (void *o, Tcl_Interp *interp,
3081                             int argc, char **argv)
3082 {
3083     IrTcl_ScanObj *obj = o;
3084
3085     if (argc == 0)
3086     {
3087         obj->scanResponse = NULL;
3088         return TCL_OK;
3089     }
3090     else if (argc == -1)
3091         return ir_tcl_strdel (interp, &obj->scanResponse);
3092     if (argc == 3)
3093     {
3094         xfree (obj->scanResponse);
3095         if (argv[2][0])
3096         {
3097             if (ir_tcl_strdup (interp, &obj->scanResponse, argv[2])
3098                 == TCL_ERROR)
3099                 return TCL_ERROR;
3100         }
3101         else
3102             obj->scanResponse = NULL;
3103     }
3104     return TCL_OK;
3105 }
3106
3107 /*
3108  * do_stepSize: Set/get replace Step Size
3109  */
3110 static int do_stepSize (void *obj, Tcl_Interp *interp,
3111                         int argc, char **argv)
3112 {
3113     IrTcl_ScanObj *p = obj;
3114     if (argc <= 0)
3115     {
3116         p->stepSize = 0;
3117         return TCL_OK;
3118     }
3119     return ir_tcl_get_set_int (&p->stepSize, interp, argc, argv);
3120 }
3121
3122 /*
3123  * do_numberOfTermsRequested: Set/get Number of Terms requested
3124  */
3125 static int do_numberOfTermsRequested (void *obj, Tcl_Interp *interp,
3126                                       int argc, char **argv)
3127 {
3128     IrTcl_ScanObj *p = obj;
3129
3130     if (argc <= 0)
3131     {
3132         p->numberOfTermsRequested = 20;
3133         return TCL_OK;
3134     }
3135     return ir_tcl_get_set_int (&p->numberOfTermsRequested, interp, argc, argv);
3136 }
3137
3138
3139 /*
3140  * do_preferredPositionInResponse: Set/get preferred Position
3141  */
3142 static int do_preferredPositionInResponse (void *obj, Tcl_Interp *interp,
3143                                            int argc, char **argv)
3144 {
3145     IrTcl_ScanObj *p = obj;
3146
3147     if (argc <= 0)
3148     {
3149         p->preferredPositionInResponse = 1;
3150         return TCL_OK;
3151     }
3152     return ir_tcl_get_set_int (&p->preferredPositionInResponse, interp,
3153                                argc, argv);
3154 }
3155
3156 /*
3157  * do_scanStatus: Get scan status
3158  */
3159 static int do_scanStatus (void *obj, Tcl_Interp *interp,
3160                           int argc, char **argv)
3161 {
3162     IrTcl_ScanObj *p = obj;
3163
3164     if (argc <= 0)
3165         return TCL_OK;
3166     return ir_tcl_get_set_int (&p->scanStatus, interp, argc, argv);
3167 }
3168
3169 /*
3170  * do_numberOfEntriesReturned: Get number of Entries returned
3171  */
3172 static int do_numberOfEntriesReturned (void *obj, Tcl_Interp *interp,
3173                                        int argc, char **argv)
3174 {
3175     IrTcl_ScanObj *p = obj;
3176
3177     if (argc <= 0)
3178         return TCL_OK;
3179     return ir_tcl_get_set_int (&p->numberOfEntriesReturned, interp,
3180                                argc, argv);
3181 }
3182
3183 /*
3184  * do_positionOfTerm: Get position of Term
3185  */
3186 static int do_positionOfTerm (void *obj, Tcl_Interp *interp,
3187                               int argc, char **argv)
3188 {
3189     IrTcl_ScanObj *p = obj;
3190
3191     if (argc <= 0)
3192         return TCL_OK;
3193     return ir_tcl_get_set_int (&p->positionOfTerm, interp, argc, argv);
3194 }
3195
3196 /*
3197  * do_scanLine: get Scan Line (surrogate or normal) after response
3198  */
3199 static int do_scanLine (void *obj, Tcl_Interp *interp, int argc, char **argv)
3200 {
3201     IrTcl_ScanObj *p = obj;
3202     int i;
3203     char numstr[20];
3204
3205     if (argc == 0)
3206     {
3207         p->entries_flag = 0;
3208         p->entries = NULL;
3209         p->nonSurrogateDiagnosticNum = 0;
3210         p->nonSurrogateDiagnosticList = 0;
3211         return TCL_OK;
3212     }
3213     else if (argc == -1)
3214     {
3215         p->entries_flag = 0;
3216         /* release entries */
3217         p->entries = NULL;
3218
3219         ir_deleteDiags (&p->nonSurrogateDiagnosticList, 
3220                         &p->nonSurrogateDiagnosticNum);
3221         return TCL_OK;
3222     }
3223     if (argc != 3)
3224     {
3225         interp->result = "wrong # args";
3226         return TCL_ERROR;
3227     }
3228     if (Tcl_GetInt (interp, argv[2], &i) == TCL_ERROR)
3229         return TCL_ERROR;
3230     if (!p->entries_flag || p->which != Z_ListEntries_entries || !p->entries
3231         || i >= p->num_entries || i < 0)
3232         return TCL_OK;
3233     switch (p->entries[i].which)
3234     {
3235     case Z_Entry_termInfo:
3236         Tcl_AppendElement (interp, "T");
3237         if (p->entries[i].u.term.buf)
3238             Tcl_AppendElement (interp, p->entries[i].u.term.buf);
3239         else
3240             Tcl_AppendElement (interp, "");
3241         sprintf (numstr, "%d", p->entries[i].u.term.globalOccurrences);
3242         Tcl_AppendElement (interp, numstr);
3243         break;
3244     case Z_Entry_surrogateDiagnostic:
3245         Tcl_AppendElement (interp, "SD");
3246         return ir_diagResult (interp, p->entries[i].u.diag.list,
3247                               p->entries[i].u.diag.num);
3248         break;
3249     }
3250     return TCL_OK;
3251 }
3252
3253 static IrTcl_Method ir_scan_method_tab[] = {
3254     { "scan",                    do_scan, NULL},
3255     { "scanResponse",            do_scanResponse, NULL},
3256     { "stepSize",                do_stepSize, NULL},
3257     { "numberOfTermsRequested",  do_numberOfTermsRequested, NULL},
3258     { "preferredPositionInResponse", do_preferredPositionInResponse, NULL},
3259     { "scanStatus",              do_scanStatus, NULL},
3260     { "numberOfEntriesReturned", do_numberOfEntriesReturned, NULL},
3261     { "positionOfTerm",          do_positionOfTerm, NULL},
3262     { "scanLine",                do_scanLine, NULL},
3263     { NULL, NULL}
3264 };
3265
3266 /* 
3267  * ir_scan_obj_method: IR Scan Object methods
3268  */
3269 static int ir_scan_obj_method (ClientData clientData, Tcl_Interp *interp,
3270                                int argc, char **argv)
3271 {
3272     IrTcl_Methods tabs[2];
3273     int r;
3274
3275     if (argc < 2)
3276     {
3277         interp->result = "wrong # args";
3278         return TCL_ERROR;
3279     }
3280     tabs[0].tab = ir_scan_method_tab;
3281     tabs[0].obj = clientData;
3282     tabs[1].tab = NULL;
3283
3284     ir_tcl_method (interp, argc, argv, tabs, &r);
3285     return r;
3286 }
3287
3288 /* 
3289  * ir_scan_obj_delete: IR Scan Object disposal
3290  */
3291 static void ir_scan_obj_delete (ClientData clientData)
3292 {
3293     IrTcl_Methods tabs[2];
3294     IrTcl_ScanObj *obj = clientData;
3295
3296     tabs[0].tab = ir_scan_method_tab;
3297     tabs[0].obj = obj;
3298     tabs[1].tab = NULL;
3299
3300     ir_tcl_method (NULL, -1, NULL, tabs, NULL);
3301     xfree (obj);
3302 }
3303
3304 /* 
3305  * ir_scan_obj_mk: IR Scan Object creation
3306  */
3307 static int ir_scan_obj_mk (ClientData clientData, Tcl_Interp *interp,
3308                            int argc, char **argv)
3309 {
3310     Tcl_CmdInfo parent_info;
3311     IrTcl_ScanObj *obj;
3312     IrTcl_Methods tabs[2];
3313
3314     if (argc != 3)
3315     {
3316         interp->result = "wrong # args";
3317         return TCL_ERROR;
3318     }
3319     logf (LOG_DEBUG, "ir scan create %s", argv[1]);
3320     if (!Tcl_GetCommandInfo (interp, argv[2], &parent_info))
3321     {
3322         interp->result = "No parent";
3323         return TCL_ERROR;
3324     }
3325     obj = ir_tcl_malloc (sizeof(*obj));
3326     obj->parent = (IrTcl_Obj *) parent_info.clientData;
3327
3328     tabs[0].tab = ir_scan_method_tab;
3329     tabs[0].obj = obj;
3330     tabs[1].tab = NULL;
3331
3332     if (ir_tcl_method (interp, 0, NULL, tabs, NULL) == TCL_ERROR)
3333         return TCL_ERROR;
3334     Tcl_CreateCommand (interp, argv[1], ir_scan_obj_method,
3335                        (ClientData) obj, ir_scan_obj_delete);
3336     return TCL_OK;
3337 }
3338
3339 /* ------------------------------------------------------- */
3340
3341 static void ir_initResponse (void *obj, Z_InitResponse *initrs)
3342 {
3343     IrTcl_Obj *p = obj;
3344
3345     p->initResult = *initrs->result ? 1 : 0;
3346     if (!*initrs->result)
3347         logf (LOG_DEBUG, "Connection rejected by target");
3348     else
3349         logf (LOG_DEBUG, "Connection accepted by target");
3350
3351     get_referenceId (&p->set_inher.referenceId, initrs->referenceId);
3352
3353     xfree (p->targetImplementationId);
3354     ir_tcl_strdup (p->interp, &p->targetImplementationId,
3355                initrs->implementationId);
3356     xfree (p->targetImplementationName);
3357     ir_tcl_strdup (p->interp, &p->targetImplementationName,
3358                initrs->implementationName);
3359     xfree (p->targetImplementationVersion);
3360     ir_tcl_strdup (p->interp, &p->targetImplementationVersion,
3361                initrs->implementationVersion);
3362
3363     p->maximumRecordSize = *initrs->maximumRecordSize;
3364     p->preferredMessageSize = *initrs->preferredMessageSize;
3365     
3366     memcpy (&p->options, initrs->options, sizeof(initrs->options));
3367     memcpy (&p->protocolVersion, initrs->protocolVersion,
3368             sizeof(initrs->protocolVersion));
3369     xfree (p->userInformationField);
3370     p->userInformationField = NULL;
3371     if (initrs->userInformationField)
3372     {
3373         int len;
3374
3375         if (initrs->userInformationField->which == ODR_EXTERNAL_octet && 
3376             (p->userInformationField =
3377              ir_tcl_malloc ((len = 
3378                              initrs->userInformationField->
3379                              u.octet_aligned->len) +1)))
3380         {
3381             memcpy (p->userInformationField,
3382                     initrs->userInformationField->u.octet_aligned->buf,
3383                         len);
3384             (p->userInformationField)[len] = '\0';
3385         }
3386     }
3387 }
3388
3389 static void ir_deleteDiags (IrTcl_Diagnostic **dst_list, int *dst_num)
3390 {
3391     int i;
3392     for (i = 0; i<*dst_num; i++)
3393         xfree (dst_list[i]->addinfo);
3394     xfree (*dst_list);
3395     *dst_list = NULL;
3396     *dst_num = 0;
3397 }
3398
3399 static void ir_handleDiags (IrTcl_Diagnostic **dst_list, int *dst_num,
3400                             Z_DiagRec **list, int num)
3401 {
3402     int i;
3403     char *addinfo;
3404
3405     *dst_num = num;
3406     *dst_list = ir_tcl_malloc (sizeof(**dst_list) * num);
3407     for (i = 0; i<num; i++)
3408     {
3409         const char *cp;
3410         switch (list[i]->which)
3411         {
3412         case Z_DiagRec_defaultFormat:
3413             (*dst_list)[i].condition = *list[i]->u.defaultFormat->condition;
3414             addinfo = list[i]->u.defaultFormat->addinfo;
3415             if (addinfo && 
3416                 ((*dst_list)[i].addinfo = ir_tcl_malloc (strlen(addinfo)+1)))
3417                 strcpy ((*dst_list)[i].addinfo, addinfo);
3418             cp = diagbib1_str ((*dst_list)[i].condition);
3419             logf (LOG_DEBUG, "Diag %d %s %s", (*dst_list)[i].condition,
3420                   cp ? cp : "", addinfo ? addinfo : "");
3421             break;
3422         default:
3423             (*dst_list)[i].addinfo = NULL;
3424             (*dst_list)[i].condition = 0;
3425         }
3426     }
3427 }
3428
3429 static void ir_handleDBRecord (IrTcl_Obj *p, IrTcl_RecordList *rl,
3430                                Z_External *oe)
3431 {
3432     struct oident *ident;
3433     Z_ext_typeent *etype;
3434                 
3435     rl->u.dbrec.size = oe->u.octet_aligned->len;
3436     rl->u.dbrec.buf = NULL;
3437     
3438     if ((ident = oid_getentbyoid (oe->direct_reference)))
3439         rl->u.dbrec.type = ident->value;
3440     else
3441         rl->u.dbrec.type = VAL_USMARC;
3442
3443     if (ident && (oe->which == Z_External_single ||
3444                   oe->which == Z_External_octet)
3445         && (etype = z_ext_getentbyref (ident->value)))
3446     {
3447         void *rr;
3448         
3449         odr_setbuf (p->odr_in, (char*) oe->u.octet_aligned->buf,
3450                     oe->u.octet_aligned->len, 0);
3451         if (!(*etype->fun)(p->odr_in, &rr, 0))
3452             return;
3453         switch (etype->what)
3454         {
3455         case Z_External_sutrs:
3456             logf (LOG_LOG, "Z_External_sutrs");
3457             oe->u.sutrs = rr;
3458             if ((rl->u.dbrec.buf = ir_tcl_malloc (oe->u.sutrs->len+1)))
3459             {
3460                 memcpy (rl->u.dbrec.buf, oe->u.sutrs->buf,
3461                         oe->u.sutrs->len);
3462                 rl->u.dbrec.buf[oe->u.sutrs->len] = '\0';
3463             }
3464             rl->u.dbrec.size = oe->u.sutrs->len;
3465             break;
3466         case Z_External_grs1:
3467             logf (LOG_LOG, "Z_External_grs1");
3468             oe->u.grs1 = rr;
3469             ir_tcl_grs_mk (oe->u.grs1, &rl->u.dbrec.u.grs1);
3470             break;
3471         case Z_External_explainRecord:
3472             logf (LOG_LOG, "Z_External_explainRecord");
3473             if ((rl->u.dbrec.buf = ir_tcl_malloc (rl->u.dbrec.size)))
3474             {
3475                 memcpy (rl->u.dbrec.buf, oe->u.octet_aligned->buf,
3476                         rl->u.dbrec.size);
3477             }
3478             break;
3479         }
3480     }
3481     else
3482     {
3483         if (oe->which == Z_External_octet && rl->u.dbrec.size > 0)
3484         {
3485             char *buf = (char*) oe->u.octet_aligned->buf;
3486             if ((rl->u.dbrec.buf = ir_tcl_malloc (rl->u.dbrec.size)))
3487                 memcpy (rl->u.dbrec.buf, buf, rl->u.dbrec.size);
3488         }
3489         else if (rl->u.dbrec.type == VAL_SUTRS && 
3490                  oe->which == Z_External_sutrs)
3491         {
3492             if ((rl->u.dbrec.buf = ir_tcl_malloc (oe->u.sutrs->len+1)))
3493             {
3494                 memcpy (rl->u.dbrec.buf, oe->u.sutrs->buf,
3495                         oe->u.sutrs->len);
3496                 rl->u.dbrec.buf[oe->u.sutrs->len] = '\0';
3497             }
3498             rl->u.dbrec.size = oe->u.sutrs->len;
3499         }
3500         else if (rl->u.dbrec.type == VAL_GRS1 && 
3501                  oe->which == Z_External_grs1)
3502         {
3503             ir_tcl_grs_mk (oe->u.grs1, &rl->u.dbrec.u.grs1);
3504         }
3505     }
3506 }
3507
3508 static void ir_handleZRecords (void *o, Z_Records *zrs, IrTcl_SetObj *setobj,
3509                               const char *elements)
3510 {
3511     IrTcl_Obj *p = o;
3512
3513     int offset;
3514     IrTcl_RecordList *rl;
3515
3516     setobj->which = zrs->which;
3517     setobj->recordFlag = 1;
3518     
3519     ir_deleteDiags (&setobj->nonSurrogateDiagnosticList,
3520                     &setobj->nonSurrogateDiagnosticNum);
3521     if (zrs->which == Z_Records_DBOSD)
3522     {
3523         setobj->numberOfRecordsReturned = 
3524             zrs->u.databaseOrSurDiagnostics->num_records;
3525         logf (LOG_DEBUG, "Got %d records", setobj->numberOfRecordsReturned);
3526         for (offset = 0; offset < setobj->numberOfRecordsReturned; offset++)
3527         {
3528             Z_NamePlusRecord *znpr = zrs->u.databaseOrSurDiagnostics->
3529                 records[offset];
3530             
3531             rl = new_IR_record (setobj, setobj->start + offset, znpr->which,
3532                                 elements);
3533             if (rl->which == Z_NamePlusRecord_surrogateDiagnostic)
3534                 ir_handleDiags (&rl->u.surrogateDiagnostics.list,
3535                                 &rl->u.surrogateDiagnostics.num,
3536                                 &znpr->u.surrogateDiagnostic,
3537                                 1);
3538             else
3539                 ir_handleDBRecord (p, rl,
3540                                    (Z_External*) (znpr->u.databaseRecord));
3541         }
3542     }
3543     else if (zrs->which == Z_Records_multipleNSD)
3544     {
3545         logf (LOG_DEBUG, "multipleNonSurrogateDiagnostic %d",
3546               zrs->u.multipleNonSurDiagnostics->num_diagRecs);
3547         setobj->numberOfRecordsReturned = 0;
3548         ir_handleDiags (&setobj->nonSurrogateDiagnosticList,
3549                         &setobj->nonSurrogateDiagnosticNum,
3550                         zrs->u.multipleNonSurDiagnostics->diagRecs,
3551                         zrs->u.multipleNonSurDiagnostics->num_diagRecs);
3552     }
3553     else
3554     {
3555         logf (LOG_DEBUG, "NonSurrogateDiagnostic");
3556         setobj->numberOfRecordsReturned = 0;
3557         ir_handleDiags (&setobj->nonSurrogateDiagnosticList,
3558                         &setobj->nonSurrogateDiagnosticNum,
3559                         &zrs->u.nonSurrogateDiagnostic,
3560                         1);
3561     }
3562 }
3563
3564 static void ir_searchResponse (void *o, Z_SearchResponse *searchrs,
3565                                IrTcl_SetObj *setobj)
3566 {    
3567     Z_Records *zrs = searchrs->records;
3568
3569     logf (LOG_DEBUG, "Received search response");
3570     if (!setobj)
3571     {
3572         logf (LOG_DEBUG, "Search response, no object!");
3573         return;
3574     }
3575     setobj->searchStatus = searchrs->searchStatus ? 1 : 0;
3576     get_referenceId (&setobj->set_inher.referenceId, searchrs->referenceId);
3577     setobj->resultCount = *searchrs->resultCount;
3578     if (searchrs->presentStatus)
3579         setobj->presentStatus = *searchrs->presentStatus;
3580     if (searchrs->nextResultSetPosition)
3581         setobj->nextResultSetPosition = *searchrs->nextResultSetPosition;
3582
3583     logf (LOG_DEBUG, "status %d hits %d", 
3584           setobj->searchStatus, setobj->resultCount);
3585     if (zrs)
3586     {
3587         const char *es;
3588         if (setobj->resultCount <= setobj->set_inher.smallSetUpperBound)
3589             es = setobj->set_inher.smallSetElementSetNames;
3590         else 
3591             es = setobj->set_inher.mediumSetElementSetNames;
3592         ir_handleZRecords (o, zrs, setobj, es);
3593     }
3594     else
3595         setobj->recordFlag = 0;
3596 }
3597
3598
3599 static void ir_presentResponse (void *o, Z_PresentResponse *presrs,
3600                                 IrTcl_SetObj *setobj)
3601 {
3602     Z_Records *zrs = presrs->records;
3603     
3604     logf (LOG_DEBUG, "Received present response");
3605     if (!setobj)
3606     {
3607         logf (LOG_DEBUG, "Present response, no object!");
3608         return;
3609     }
3610     setobj->presentStatus = *presrs->presentStatus;
3611     get_referenceId (&setobj->set_inher.referenceId, presrs->referenceId);
3612     setobj->nextResultSetPosition = *presrs->nextResultSetPosition;
3613     if (zrs)
3614         ir_handleZRecords (o, zrs, setobj, setobj->set_inher.elementSetNames);
3615     else
3616     {
3617         setobj->recordFlag = 0;
3618         logf (LOG_DEBUG, "No records!");
3619     }
3620 }
3621
3622 static void ir_scanResponse (void *o, Z_ScanResponse *scanrs,
3623                              IrTcl_ScanObj *scanobj)
3624 {
3625     IrTcl_Obj *p = o;
3626     
3627     logf (LOG_DEBUG, "Received scanResponse");
3628
3629     get_referenceId (&p->set_inher.referenceId, scanrs->referenceId);
3630     scanobj->scanStatus = *scanrs->scanStatus;
3631     logf (LOG_DEBUG, "scanStatus=%d", scanobj->scanStatus);
3632
3633     if (scanrs->stepSize)
3634         scanobj->stepSize = *scanrs->stepSize;
3635     logf (LOG_DEBUG, "stepSize=%d", scanobj->stepSize);
3636
3637     scanobj->numberOfEntriesReturned = *scanrs->numberOfEntriesReturned;
3638     logf (LOG_DEBUG, "numberOfEntriesReturned=%d",
3639           scanobj->numberOfEntriesReturned);
3640
3641     if (scanrs->positionOfTerm)
3642         scanobj->positionOfTerm = *scanrs->positionOfTerm;
3643     else
3644         scanobj->positionOfTerm = -1;
3645     logf (LOG_DEBUG, "positionOfTerm=%d", scanobj->positionOfTerm);
3646
3647     xfree (scanobj->entries);
3648     scanobj->entries = NULL;
3649
3650     ir_deleteDiags (&scanobj->nonSurrogateDiagnosticList,
3651                     &scanobj->nonSurrogateDiagnosticNum);
3652     if (scanrs->entries)
3653     {
3654         int i;
3655         Z_Entry *ze;
3656
3657         scanobj->entries_flag = 1;
3658         scanobj->which = scanrs->entries->which;
3659         switch (scanobj->which)
3660         {
3661         case Z_ListEntries_entries:
3662             scanobj->num_entries = scanrs->entries->u.entries->num_entries;
3663             scanobj->entries = ir_tcl_malloc (scanobj->num_entries * 
3664                                        sizeof(*scanobj->entries));
3665             for (i=0; i<scanobj->num_entries; i++)
3666             {
3667                 ze = scanrs->entries->u.entries->entries[i];
3668                 scanobj->entries[i].which = ze->which;
3669                 switch (ze->which)
3670                 {
3671                 case Z_Entry_termInfo:
3672                     if (ze->u.termInfo->term->which == Z_Term_general)
3673                     {
3674                         int l = ze->u.termInfo->term->u.general->len;
3675                         scanobj->entries[i].u.term.buf = ir_tcl_malloc (1+l);
3676                         memcpy (scanobj->entries[i].u.term.buf, 
3677                                 ze->u.termInfo->term->u.general->buf,
3678                                 l);
3679                         scanobj->entries[i].u.term.buf[l] = '\0';
3680                     }
3681                     else
3682                         scanobj->entries[i].u.term.buf = NULL;
3683                     if (ze->u.termInfo->globalOccurrences)
3684                         scanobj->entries[i].u.term.globalOccurrences = 
3685                             *ze->u.termInfo->globalOccurrences;
3686                     else
3687                         scanobj->entries[i].u.term.globalOccurrences = 0;
3688                     break;
3689                 case Z_Entry_surrogateDiagnostic:
3690                     ir_handleDiags (&scanobj->entries[i].u.diag.list,
3691                                     &scanobj->entries[i].u.diag.num,
3692                                     &ze->u.surrogateDiagnostic,
3693                                     1);
3694                     break;
3695                 }
3696             }
3697             break;
3698         case Z_ListEntries_nonSurrogateDiagnostics:
3699             ir_handleDiags (&scanobj->nonSurrogateDiagnosticList,
3700                             &scanobj->nonSurrogateDiagnosticNum,
3701                             scanrs->entries->u.nonSurrogateDiagnostics->
3702                             diagRecs,
3703                             scanrs->entries->u.nonSurrogateDiagnostics->
3704                             num_diagRecs);
3705             break;
3706         }
3707     }
3708     else
3709         scanobj->entries_flag = 0;
3710 }
3711
3712 /*
3713  * ir_select_read: handle incoming packages
3714  */
3715 static void ir_select_read (ClientData clientData)
3716 {
3717     IrTcl_Obj *p = clientData;
3718     Z_APDU *apdu;
3719     int r;
3720     IrTcl_Request *rq;
3721     char *object_name;
3722     Tcl_CmdInfo cmd_info;
3723     const char *apdu_call;
3724
3725     logf(LOG_DEBUG, "Read handler fd=%d", cs_fileno(p->cs_link));
3726     if (p->state == IR_TCL_R_Connecting)
3727     {
3728         logf(LOG_DEBUG, "read: connect");
3729         r = cs_rcvconnect (p->cs_link);
3730         if (r == 1)
3731         {
3732             logf (LOG_WARN, "cs_rcvconnect returned 1");
3733             return;
3734         }
3735         p->state = IR_TCL_R_Idle;
3736         p->ref_count = 2;
3737         ir_select_remove_write (cs_fileno (p->cs_link), p);
3738         if (r < 0)
3739         {
3740             logf (LOG_DEBUG, "cs_rcvconnect error");
3741             ir_tcl_disconnect (p);
3742             if (p->failback)
3743             {
3744                 p->failInfo = IR_TCL_FAIL_CONNECT;
3745                 ir_tcl_eval (p->interp, p->failback);
3746             }
3747             ir_obj_delete (p);
3748             return;
3749         }
3750         if (p->callback)
3751             ir_tcl_eval (p->interp, p->callback);
3752         if (p->ref_count == 2 && p->cs_link && p->request_queue
3753             && p->state == IR_TCL_R_Idle)
3754             ir_tcl_send_q (p, p->request_queue, "x");
3755         ir_obj_delete (p);
3756         return;
3757     }
3758     do
3759     {
3760         p->state = IR_TCL_R_Reading;
3761
3762         /* read incoming APDU */
3763         if ((r=cs_get (p->cs_link, &p->buf_in, &p->len_in)) == 1)
3764         {
3765             logf(LOG_DEBUG, "PDU Fraction read");
3766             return ;
3767         }
3768         /* signal one more use of ir object - callbacks must not
3769            release the ir memory (p pointer) */
3770         p->ref_count = 2;
3771         if (r <= 0)
3772         {
3773             logf (LOG_DEBUG, "cs_get failed, code %d", r);
3774             ir_select_remove (cs_fileno (p->cs_link), p);
3775             ir_tcl_disconnect (p);
3776             if (p->failback)
3777             {
3778                 p->failInfo = IR_TCL_FAIL_READ;
3779                 ir_tcl_eval (p->interp, p->failback);
3780             }
3781             /* release ir object now if callback deleted it */
3782             ir_obj_delete (p);
3783             return;
3784         }        
3785         /* got complete APDU. Now decode */
3786         p->apduLen = r;
3787         p->apduOffset = -1;
3788         odr_setbuf (p->odr_in, p->buf_in, r, 0);
3789         logf (LOG_DEBUG, "cs_get ok, total size %d", r);
3790         if (!z_APDU (p->odr_in, &apdu, 0))
3791         {
3792             logf (LOG_DEBUG, "cs_get failed: %s",
3793                 odr_errmsg (odr_geterror (p->odr_in)));
3794             ir_tcl_disconnect (p);
3795             if (p->failback)
3796             {
3797                 p->failInfo = IR_TCL_FAIL_IN_APDU;
3798                 p->apduOffset = odr_offset (p->odr_in);
3799                 ir_tcl_eval (p->interp, p->failback);
3800             }
3801             /* release ir object now if failback deleted it */
3802             ir_obj_delete (p);
3803             return;
3804         }
3805         /* handle APDU and invoke callback */
3806         rq = p->request_queue;
3807         if (!rq)
3808         {
3809             logf (LOG_FATAL, "Internal error. No queue entry");
3810             exit (1);
3811         }
3812         object_name = rq->object_name;
3813         logf (LOG_DEBUG, "Object %s", object_name);
3814         apdu_call = NULL;
3815         if (Tcl_GetCommandInfo (p->interp, object_name, &cmd_info))
3816         {
3817             switch(apdu->which)
3818             {
3819             case Z_APDU_initResponse:
3820                 p->eventType = "init";
3821                 ir_initResponse (p, apdu->u.initResponse);
3822                 apdu_call = p->initResponse;
3823                 break;
3824             case Z_APDU_searchResponse:
3825                 p->eventType = "search";
3826                 ir_searchResponse (p, apdu->u.searchResponse,
3827                                    (IrTcl_SetObj *) cmd_info.clientData);
3828                 apdu_call = ((IrTcl_SetObj *) 
3829                              cmd_info.clientData)->searchResponse;
3830                 break;
3831             case Z_APDU_presentResponse:
3832                 p->eventType = "present";
3833                 ir_presentResponse (p, apdu->u.presentResponse,
3834                                     (IrTcl_SetObj *) cmd_info.clientData);
3835                 apdu_call = ((IrTcl_SetObj *) 
3836                              cmd_info.clientData)->presentResponse;
3837                 break;
3838             case Z_APDU_scanResponse:
3839                 p->eventType = "scan";
3840                 ir_scanResponse (p, apdu->u.scanResponse, 
3841                                  (IrTcl_ScanObj *) cmd_info.clientData);
3842                 apdu_call = ((IrTcl_ScanObj *) 
3843                              cmd_info.clientData)->scanResponse;
3844                 break;
3845             default:
3846                 logf (LOG_WARN, "Received unknown APDU type (%d)",
3847                       apdu->which);
3848                 ir_tcl_disconnect (p);
3849                 if (p->failback)
3850                 {
3851                     p->failInfo = IR_TCL_FAIL_UNKNOWN_APDU;
3852                     ir_tcl_eval (p->interp, p->failback);
3853                 }
3854                 return;
3855             }
3856         }
3857         p->request_queue = rq->next;
3858         p->state = IR_TCL_R_Idle;
3859        
3860         if (apdu_call)
3861             ir_tcl_eval (p->interp, apdu_call);
3862         else if (rq->callback)
3863             ir_tcl_eval (p->interp, rq->callback);
3864         xfree (rq->buf_out);
3865         xfree (rq->callback);
3866         xfree (rq->object_name);
3867         xfree (rq);
3868         odr_reset (p->odr_in);
3869         if (p->ref_count == 1)
3870         {
3871             ir_obj_delete (p);
3872             return;
3873         }
3874         ir_obj_delete (p);
3875     } while (p->cs_link && cs_more (p->cs_link));
3876     if (p->cs_link && p->request_queue && p->state == IR_TCL_R_Idle)
3877         ir_tcl_send_q (p, p->request_queue, "x");
3878 }
3879
3880 /*
3881  * ir_select_write: handle outgoing packages - not yet written.
3882  */
3883 static int ir_select_write (ClientData clientData)
3884 {
3885     IrTcl_Obj *p = clientData;
3886     int r;
3887     IrTcl_Request *rq;
3888
3889     logf (LOG_DEBUG, "Write handler fd=%d", cs_fileno(p->cs_link));
3890     if (p->state == IR_TCL_R_Connecting)
3891     {
3892         logf(LOG_DEBUG, "write: connect");
3893         r = cs_rcvconnect (p->cs_link);
3894         if (r == 1)
3895         {
3896             logf (LOG_DEBUG, "cs_rcvconnect returned 1");
3897             return 2;
3898         }
3899         p->state = IR_TCL_R_Idle;
3900         p->ref_count = 2;
3901         ir_select_remove_write (cs_fileno (p->cs_link), p);
3902         if (r < 0)
3903         {
3904             logf (LOG_DEBUG, "cs_rcvconnect error");
3905             ir_tcl_disconnect (p);
3906             if (p->failback)
3907             {
3908                 p->failInfo = IR_TCL_FAIL_CONNECT;
3909                 ir_tcl_eval (p->interp, p->failback);
3910             }
3911             ir_obj_delete (p);
3912             return 2;
3913         }
3914         if (p->callback)
3915             ir_tcl_eval (p->interp, p->callback);
3916         ir_obj_delete (p);
3917         return 2;
3918     }
3919     rq = p->request_queue;
3920     if (!rq || !rq->buf_out)
3921         return 0;
3922     assert (rq);
3923     if ((r=cs_put (p->cs_link, rq->buf_out, rq->len_out)) < 0)
3924     {
3925         logf (LOG_DEBUG, "cs_put write fail");
3926         p->ref_count = 2;
3927         xfree (rq->buf_out);
3928         rq->buf_out = NULL;
3929         ir_tcl_disconnect (p);
3930         if (p->failback)
3931         {
3932             p->failInfo = IR_TCL_FAIL_WRITE;
3933             ir_tcl_eval (p->interp, p->failback);
3934         }
3935         ir_obj_delete (p);
3936     }
3937     else if (r == 0)            /* remove select bit */
3938     {
3939         logf (LOG_DEBUG, "Write completed");
3940         p->state = IR_TCL_R_Waiting;
3941         ir_select_remove_write (cs_fileno (p->cs_link), p);
3942         xfree (rq->buf_out);
3943         rq->buf_out = NULL;
3944     }
3945     return 1;
3946 }
3947
3948 static void ir_select_notify (ClientData clientData, int r, int w, int e)
3949 {
3950     if (w)
3951     {
3952         if (!ir_select_write (clientData) && r)
3953             ir_select_read (clientData);
3954     } 
3955     else if (r)
3956     {
3957         ir_select_read (clientData);
3958     }
3959 }
3960
3961 /* ------------------------------------------------------- */
3962
3963 /*
3964  * Irtcl_init: Registration of TCL commands.
3965  */
3966 int Irtcl_Init (Tcl_Interp *interp)
3967 {
3968     Tcl_CreateCommand (interp, "ir", ir_obj_mk, (ClientData) NULL,
3969                        (Tcl_CmdDeleteProc *) NULL);
3970     Tcl_CreateCommand (interp, "ir-set", ir_set_obj_mk,
3971                        (ClientData) NULL, (Tcl_CmdDeleteProc *) NULL);
3972     Tcl_CreateCommand (interp, "ir-scan", ir_scan_obj_mk,
3973                        (ClientData) NULL, (Tcl_CmdDeleteProc *) NULL);
3974     return TCL_OK;
3975 }
3976