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