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