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