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