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