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