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