Minor changes.
[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.44  1995-06-19 17:01:20  adam
9  * Minor changes.
10  *
11  * Revision 1.43  1995/06/19  13:06:08  adam
12  * New define: IR_TCL_VERSION.
13  *
14  * Revision 1.42  1995/06/19  08:08:52  adam
15  * client.tcl: hotTargets now contain both database and target name.
16  * ir-tcl.c: setting protocol edited. Errors in callbacks are logged
17  * by logf(LOG_WARN, ...) calls.
18  *
19  * Revision 1.41  1995/06/16  12:28:16  adam
20  * Implemented preferredRecordSyntax.
21  * Minor changes in diagnostic handling.
22  * Record list deleted when connection closes.
23  *
24  * Revision 1.40  1995/06/14  13:37:18  adam
25  * Setting recordType implemented.
26  * Setting implementationVersion implemented.
27  * Settings implementationId / implementationName edited.
28  *
29  * Revision 1.39  1995/06/08  10:26:32  adam
30  * Bug fix in ir_strdup.
31  *
32  * Revision 1.38  1995/06/01  16:36:47  adam
33  * About buttons. Minor bug fixes.
34  *
35  * Revision 1.37  1995/06/01  07:31:20  adam
36  * Rename of many typedefs -> IrTcl_...
37  *
38  * Revision 1.36  1995/05/31  13:09:59  adam
39  * Client searches/presents may be interrupted.
40  * New moving book-logo.
41  *
42  * Revision 1.35  1995/05/31  08:36:33  adam
43  * Bug fix in client.tcl: didn't save options on clientrc.tcl.
44  * New method: referenceId. More work on scan.
45  *
46  * Revision 1.34  1995/05/29  10:33:42  adam
47  * README and rename of startup script.
48  *
49  * Revision 1.33  1995/05/29  09:15:11  quinn
50  * Changed CS_SR to PROTO_SR, etc.
51  *
52  * Revision 1.32  1995/05/29  08:44:16  adam
53  * Work on delete of objects.
54  *
55  * Revision 1.31  1995/05/26  11:44:10  adam
56  * Bugs fixed. More work on MARC utilities and queries. Test
57  * client is up-to-date again.
58  *
59  * Revision 1.30  1995/05/26  08:54:11  adam
60  * New MARC utilities. Uses prefix query.
61  *
62  * Revision 1.29  1995/05/24  14:10:22  adam
63  * Work on idAuthentication, protocolVersion and options.
64  *
65  * Revision 1.28  1995/05/23  15:34:48  adam
66  * Many new settings, userInformationField, smallSetUpperBound, etc.
67  * A number of settings are inherited when ir-set is executed.
68  * This version is incompatible with the graphical test client (client.tcl).
69  *
70  * Revision 1.27  1995/05/11  15:34:47  adam
71  * Scan request changed a bit. This version works with RLG.
72  *
73  * Revision 1.26  1995/04/18  16:11:51  adam
74  * First version of graphical Scan. Some work on query-by-form.
75  *
76  * Revision 1.25  1995/04/17  09:37:17  adam
77  * Further development of scan.
78  *
79  * Revision 1.24  1995/04/11  14:16:42  adam
80  * Further work on scan. Response works. Entries aren't saved yet.
81  *
82  * Revision 1.23  1995/04/10  10:50:27  adam
83  * Result-set name defaults to suffix of ir-set name.
84  * Started working on scan. Not finished at this point.
85  *
86  * Revision 1.22  1995/03/31  10:43:03  adam
87  * More robust when getting bad MARC records.
88  *
89  * Revision 1.21  1995/03/31  08:56:37  adam
90  * New button "Search".
91  *
92  * Revision 1.20  1995/03/29  16:07:09  adam
93  * Bug fix: Didn't use setName in present request.
94  *
95  * Revision 1.19  1995/03/28  12:45:23  adam
96  * New ir method failback: called on disconnect/protocol error.
97  * New ir set/get method: protocol: SR / Z3950.
98  * Simple popup and disconnect when failback is invoked.
99  *
100  * Revision 1.18  1995/03/21  15:50:12  adam
101  * Minor changes.
102  *
103  * Revision 1.17  1995/03/21  13:41:03  adam
104  * Comstack cs_create not used too often. Non-blocking connect.
105  *
106  * Revision 1.16  1995/03/21  08:26:06  adam
107  * New method, setName, to specify the result set name (other than Default).
108  * New method, responseStatus, which returns diagnostic info, if any, after
109  * present response / search response.
110  *
111  * Revision 1.15  1995/03/20  15:24:07  adam
112  * Diagnostic records saved on searchResponse.
113  *
114  * Revision 1.14  1995/03/20  08:53:22  adam
115  * Event loop in tclmain.c rewritten. New method searchStatus.
116  *
117  * Revision 1.13  1995/03/17  18:26:17  adam
118  * Non-blocking i/o used now. Database names popup as cascade items.
119  *
120  * Revision 1.12  1995/03/17  15:45:00  adam
121  * Improved target/database setup.
122  *
123  * Revision 1.11  1995/03/16  17:54:03  adam
124  * Minor changes really.
125  *
126  * Revision 1.10  1995/03/15  16:14:50  adam
127  * Blocking arg in cs_create changed.
128  *
129  * Revision 1.9  1995/03/15  13:59:24  adam
130  * Minor changes.
131  *
132  * Revision 1.8  1995/03/15  08:25:16  adam
133  * New method presentStatus to check for error on present. Misc. cleanup
134  * of IrTcl_RecordList manipulations. Full MARC record presentation in
135  * search.tcl.
136  *
137  * Revision 1.7  1995/03/14  17:32:29  adam
138  * Presentation of full Marc record in popup window.
139  *
140  * Revision 1.6  1995/03/12  19:31:55  adam
141  * Pattern matching implemented when retrieving MARC records. More
142  * diagnostic functions.
143  *
144  * Revision 1.5  1995/03/10  18:00:15  adam
145  * Actual presentation in line-by-line format. RPN query support.
146  *
147  * Revision 1.4  1995/03/09  16:15:08  adam
148  * First presentRequest attempts. Hot-target list.
149  *
150  */
151
152 #include <stdlib.h>
153 #include <stdio.h>
154 #include <sys/time.h>
155 #include <assert.h>
156
157 #define CS_BLOCK 0
158
159 #include "ir-tclp.h"
160
161 typedef struct {
162     int type;
163     char *name;
164     int (*method) (void *obj, Tcl_Interp *interp, int argc, char **argv);
165 } IrTcl_Method;
166
167 typedef struct {
168     void *obj;
169     IrTcl_Method *tab;
170 } IrTcl_Methods;
171
172 static Tcl_Interp *irTcl_interp;
173
174 static void ir_deleteDiags (IrTcl_Diagnostic **dst_list, int *dst_num);
175 static int do_disconnect (void *obj, Tcl_Interp *interp, 
176                           int argc, char **argv);
177
178 static IrTcl_RecordList *new_IR_record (IrTcl_SetObj *setobj, 
179                                         int no, int which)
180 {
181     IrTcl_RecordList *rl;
182
183     for (rl = setobj->record_list; rl; rl = rl->next)
184     {
185         if (no == rl->no)
186         {
187             switch (rl->which)
188             {
189             case Z_NamePlusRecord_databaseRecord:
190                 free (rl->u.dbrec.buf);
191                 rl->u.dbrec.buf = NULL;
192                 break;
193             case Z_NamePlusRecord_surrogateDiagnostic:
194                 ir_deleteDiags (&rl->u.surrogateDiagnostics.list,
195                                 &rl->u.surrogateDiagnostics.num);
196                 break;
197             }
198             break;
199         }
200     }
201     if (!rl)
202     {
203         rl = malloc (sizeof(*rl));
204         assert (rl);
205         rl->next = setobj->record_list;
206         rl->no = no;
207         setobj->record_list = rl;
208     }
209     rl->which = which;
210     return rl;
211 }
212
213 static struct {
214     enum oid_value value;
215     const char *name;
216 } IrTcl_recordSyntaxTab[] = { 
217 { VAL_UNIMARC,    "UNIMARC" },
218 { VAL_INTERMARC,  "INTERMARC" },
219 { VAL_CCF,        "CCF" },
220 { VAL_USMARC,     "USMARC" },
221 { VAL_UKMARC,     "UKMARC" },
222 { VAL_NORMARC,    "NORMARC" },
223 { VAL_LIBRISMARC, "LIBRISMARC" },
224 { VAL_DANMARC,    "DANMARC" },
225 { VAL_FINMARC,    "FINMARC" },
226 { VAL_MAB,        "MAB" },
227 { VAL_CANMARC,    "CANMARC" },
228 { VAL_SBN,        "SBN" },
229 { VAL_PICAMARC,   "PICAMARC" },
230 { VAL_AUSMARC,    "AUSMARC" },
231 { VAL_IBERMARC,   "IBERMARC" },
232 { VAL_SUTRS,      "SUTRS" },
233 { 0, NULL }
234 };
235
236 /* 
237  * IrTcl_eval
238  */
239 int IrTcl_eval (Tcl_Interp *interp, const char *command)
240 {
241     char *tmp = malloc (strlen(command)+1);
242     int r;
243
244     if (!tmp)
245     {
246         logf (LOG_FATAL, "Out of memory in IrTcl_eval");
247         exit (1);
248     }
249     strcpy (tmp, command);
250     r = Tcl_Eval (interp, tmp);
251     if (r == TCL_ERROR)
252         logf (LOG_WARN, "Tcl error in line %d: %s", interp->errorLine, 
253               interp->result);
254     Tcl_FreeResult (interp);
255     free (tmp);
256     return r;
257 }
258
259 /*
260  * IrTcl_getRecordSyntaxStr: Return record syntax name of object id
261  */
262 static const char *IrTcl_getRecordSyntaxStr (enum oid_value value)
263 {
264     int i;
265     for (i = 0; IrTcl_recordSyntaxTab[i].name; i++) 
266         if (IrTcl_recordSyntaxTab[i].value == value)
267             return IrTcl_recordSyntaxTab[i].name;
268     return "USMARC";
269 }
270
271 /*
272  * IrTcl_getRecordSyntaxVal: Return record syntax value of string
273  */
274 static enum oid_value IrTcl_getRecordSyntaxVal (const char *name)
275 {
276     int i;
277     for (i = 0; IrTcl_recordSyntaxTab[i].name; i++) 
278         if (!strcmp (IrTcl_recordSyntaxTab[i].name, name))
279             return IrTcl_recordSyntaxTab[i].value;
280     return 0;
281 }
282
283 static IrTcl_RecordList *find_IR_record (IrTcl_SetObj *setobj, int no)
284 {
285     IrTcl_RecordList *rl;
286
287     for (rl = setobj->record_list; rl; rl = rl->next)
288         if (no == rl->no)
289             return rl;
290     return NULL;
291 }
292
293 static void delete_IR_records (IrTcl_SetObj *setobj)
294 {
295     IrTcl_RecordList *rl, *rl1;
296
297     for (rl = setobj->record_list; rl; rl = rl1)
298     {
299         switch (rl->which)
300         {
301         case Z_NamePlusRecord_databaseRecord:
302             free (rl->u.dbrec.buf);
303             break;
304         case Z_NamePlusRecord_surrogateDiagnostic:
305             ir_deleteDiags (&rl->u.surrogateDiagnostics.list,
306                             &rl->u.surrogateDiagnostics.num);
307             break;
308         }
309         rl1 = rl->next;
310         free (rl);
311     }
312     setobj->record_list = NULL;
313 }
314
315 /*
316  * get_set_int: Set/get integer value
317  */
318 static int get_set_int (int *val, Tcl_Interp *interp, int argc, char **argv)
319 {
320     char buf[20];
321     
322     if (argc == 3)
323     {
324         if (Tcl_GetInt (interp, argv[2], val)==TCL_ERROR)
325             return TCL_ERROR;
326     }
327     sprintf (buf, "%d", *val);
328     Tcl_AppendResult (interp, buf, NULL);
329     return TCL_OK;
330 }
331
332 /*
333  * ir_method: Search for method in table and invoke method handler
334  */
335 int ir_method (Tcl_Interp *interp, int argc, char **argv, IrTcl_Methods *tab)
336 {
337     IrTcl_Methods *tab_i = tab;
338     IrTcl_Method *t;
339
340     for (tab_i = tab; tab_i->tab; tab_i++)
341         for (t = tab_i->tab; t->name; t++)
342             if (argc <= 0)
343             {
344                 if ((*t->method)(tab_i->obj, interp, argc, argv) == TCL_ERROR)
345                     return TCL_ERROR;
346             }
347             else
348                 if (!strcmp (t->name, argv[1]))
349                     return (*t->method)(tab_i->obj, interp, argc, argv);
350
351     if (argc <= 0)
352         return TCL_OK;
353     Tcl_AppendResult (interp, "Bad method. Possible methods:", NULL);
354     for (tab_i = tab; tab_i->tab; tab_i++)
355         for (t = tab_i->tab; t->name; t++)
356             Tcl_AppendResult (interp, " ", t->name, NULL);
357     return TCL_ERROR;
358 }
359
360 /*
361  * ir_method_r: Get status for all readable elements
362  */
363 int ir_method_r (void *obj, Tcl_Interp *interp, int argc, char **argv,
364                  IrTcl_Method *tab)
365 {
366     char *argv_n[3];
367     int argc_n;
368
369     argv_n[0] = argv[0];
370     argc_n = 2;
371     for (; tab->name; tab++)
372         if (tab->type)
373         {
374             argv_n[1] = tab->name;
375             Tcl_AppendResult (interp, "{", NULL);
376             (*tab->method)(obj, interp, argc_n, argv_n);
377             Tcl_AppendResult (interp, "} ", NULL);
378         }
379     return TCL_OK;
380 }
381
382 /*
383  *  ir_named_bits: get/set named bits
384  */
385 int ir_named_bits (struct ir_named_entry *tab, Odr_bitmask *ob,
386                    Tcl_Interp *interp, int argc, char **argv)
387 {
388     struct ir_named_entry *ti;
389     if (argc > 0)
390     {
391         int no;
392         ODR_MASK_ZERO (ob);
393         for (no = 0; no < argc; no++)
394         {
395             for (ti = tab; ti->name; ti++)
396                 if (!strcmp (argv[no], ti->name))
397                 {
398                     ODR_MASK_SET (ob, ti->pos);
399                     break;
400                 }
401             if (!ti->name)
402             {
403                 Tcl_AppendResult (interp, "Bad bit mask: ", argv[no], NULL);
404                 return TCL_ERROR;
405             }
406         }
407         return TCL_OK;
408     }
409     for (ti = tab; ti->name; ti++)
410         if (ODR_MASK_GET (ob, ti->pos))
411             Tcl_AppendElement (interp, ti->name);
412     return TCL_OK;
413 }
414
415 /*
416  * ir_strdup: Duplicate string
417  */
418 int ir_strdup (Tcl_Interp *interp, char** p, const char *s)
419 {
420     if (!s)
421     {
422         *p = NULL;
423         return TCL_OK;
424     }
425     *p = malloc (strlen(s)+1);
426     if (!*p)
427     {
428         interp->result = "strdup fail";
429         return TCL_ERROR;
430     }
431     strcpy (*p, s);
432     return TCL_OK;
433 }
434
435 /*
436  * ir_strdel: Delete string
437  */
438 int ir_strdel (Tcl_Interp *interp, char **p)
439 {
440     free (*p);
441     *p = NULL;
442     return TCL_OK;
443 }
444
445 /*
446  * ir_malloc: Malloc function
447  */
448 void *ir_malloc (Tcl_Interp *interp, size_t size)
449 {
450     static char buf[128];
451     void *p = malloc (size);
452
453     if (!p)
454     {
455         sprintf (buf, "Malloc fail. %ld bytes requested", (long) size);
456         interp->result = buf;
457         return NULL;
458     }
459     return p;
460 }
461
462 static void set_referenceId (ODR o, Z_ReferenceId **dst, const char *src)
463 {
464     if (!src || !*src)
465         *dst = NULL;
466     else
467     {
468         *dst = odr_malloc (o, sizeof(**dst));
469         (*dst)->size = (*dst)->len = strlen(src);
470         (*dst)->buf = odr_malloc (o, (*dst)->len);
471         memcpy ((*dst)->buf, src, (*dst)->len);
472     }
473 }
474
475 static void get_referenceId (char **dst, Z_ReferenceId *src)
476 {
477     free (*dst);
478     if (!src)
479     {
480         *dst = NULL;
481         return;
482     }
483     *dst = malloc (src->len+1);
484     memcpy (*dst, src->buf, src->len);
485     (*dst)[src->len] = '\0';
486 }
487
488 /* ------------------------------------------------------- */
489
490 /*
491  * do_init_request: init method on IR object
492  */
493 static int do_init_request (void *obj, Tcl_Interp *interp,
494                             int argc, char **argv)
495 {
496     Z_APDU *apdu;
497     IrTcl_Obj *p = obj;
498     Z_InitRequest *req;
499     int r;
500
501     if (argc <= 0)
502         return TCL_OK;
503     if (!p->cs_link)
504     {
505         interp->result = "not connected";
506         return TCL_ERROR;
507     }
508     odr_reset (p->odr_out);
509     apdu = zget_APDU (p->odr_out, Z_APDU_initRequest);
510     req = apdu->u.initRequest;
511
512     set_referenceId (p->odr_out, &req->referenceId, p->set_inher.referenceId);
513     req->options = &p->options;
514     req->protocolVersion = &p->protocolVersion;
515     req->preferredMessageSize = &p->preferredMessageSize;
516     req->maximumRecordSize = &p->maximumRecordSize;
517
518     if (p->idAuthenticationGroupId)
519     {
520         Z_IdPass *pass = odr_malloc (p->odr_out, sizeof(*pass));
521         Z_IdAuthentication *auth = odr_malloc (p->odr_out, sizeof(*auth));
522
523         auth->which = Z_IdAuthentication_idPass;
524         auth->u.idPass = pass;
525         if (p->idAuthenticationGroupId && *p->idAuthenticationGroupId)
526             pass->groupId = p->idAuthenticationGroupId;
527         else
528             pass->groupId = NULL;
529         if (p->idAuthenticationUserId && *p->idAuthenticationUserId)
530             pass->userId = p->idAuthenticationUserId;
531         else
532             pass->userId = NULL;
533         if (p->idAuthenticationPassword && *p->idAuthenticationPassword)
534             pass->password = p->idAuthenticationPassword;
535         else
536             pass->password = NULL;
537         req->idAuthentication = auth;
538     }
539     else if (!p->idAuthenticationOpen || !*p->idAuthenticationOpen)
540         req->idAuthentication = NULL;
541     else
542     {
543         Z_IdAuthentication *auth = odr_malloc (p->odr_out, sizeof(*auth));
544
545         auth->which = Z_IdAuthentication_open;
546         auth->u.open = p->idAuthenticationOpen;
547         req->idAuthentication = auth;
548     }
549     req->implementationId = p->implementationId;
550     req->implementationName = p->implementationName;
551     req->implementationVersion = p->implementationVersion;
552     req->userInformationField = 0;
553
554     if (!z_APDU (p->odr_out, &apdu, 0))
555     {
556         Tcl_AppendResult (interp, odr_errlist [odr_geterror (p->odr_out)],
557                           NULL);
558         odr_reset (p->odr_out);
559         return TCL_ERROR;
560     }
561     p->sbuf = odr_getbuf (p->odr_out, &p->slen, NULL);
562     if ((r=cs_put (p->cs_link, p->sbuf, p->slen)) < 0)
563     {     
564         interp->result = "cs_put failed in init";
565         do_disconnect (p, NULL, 2, NULL);
566         return TCL_ERROR;
567     }
568     else if (r == 1)
569     {
570         ir_select_add_write (cs_fileno(p->cs_link), p);
571         logf (LOG_DEBUG, "Sent part of initializeRequest (%d bytes)", p->slen);
572     }
573     else
574         logf (LOG_DEBUG, "Sent whole initializeRequest (%d bytes)", p->slen);
575     return TCL_OK;
576 }
577
578 /*
579  * do_protocolVersion: Set protocol Version
580  */
581 static int do_protocolVersion (void *obj, Tcl_Interp *interp,
582                                int argc, char **argv)
583 {
584     int version, i;
585     char buf[10];
586     IrTcl_Obj *p = obj;
587
588     if (argc <= 0)
589     {
590         ODR_MASK_ZERO (&p->protocolVersion);
591         ODR_MASK_SET (&p->protocolVersion, 0);
592         ODR_MASK_SET (&p->protocolVersion, 1);
593         return TCL_OK;
594     }
595     if (argc == 3)
596     {
597         if (Tcl_GetInt (interp, argv[2], &version)==TCL_ERROR)
598             return TCL_ERROR;
599         ODR_MASK_ZERO (&p->protocolVersion);
600         for (i = 0; i<version; i++)
601             ODR_MASK_SET (&p->protocolVersion, i);
602     }
603     for (i = 4; --i >= 0; )
604         if (ODR_MASK_GET (&p->protocolVersion, i))
605             break;
606     sprintf (buf, "%d", i+1);
607     interp->result = buf;
608     return TCL_OK;
609 }
610
611 /*
612  * do_options: Set options
613  */
614 static int do_options (void *obj, Tcl_Interp *interp,
615                        int argc, char **argv)
616 {
617     static struct ir_named_entry options_tab[] = {
618     { "search", 0 },
619     { "present", 1 },
620     { "delSet", 2 },
621     { "resourceReport", 3 },
622     { "triggerResourceCtrl", 4},
623     { "resourceCtrl", 5},
624     { "accessCtrl", 6},
625     { "scan", 7},
626     { "sort", 8},
627     { "extendedServices", 10},
628     { "level-1Segmentation", 11},
629     { "level-2Segmentation", 12},
630     { "concurrentOperations", 13},
631     { "namedResultSets", 14},
632     { NULL, 0}
633     };
634     IrTcl_Obj *p = obj;
635
636     if (argc <= 0)
637     {
638         ODR_MASK_ZERO (&p->options);
639         ODR_MASK_SET (&p->options, 0);
640         ODR_MASK_SET (&p->options, 1);
641         ODR_MASK_SET (&p->options, 7);
642         ODR_MASK_SET (&p->options, 14);
643         return TCL_OK;
644     }
645     return ir_named_bits (options_tab, &p->options, interp, argc-2, argv+2);
646 }
647
648 /*
649  * do_preferredMessageSize: Set/get preferred message size
650  */
651 static int do_preferredMessageSize (void *obj, Tcl_Interp *interp,
652                                     int argc, char **argv)
653 {
654     IrTcl_Obj *p = obj;
655
656     if (argc <= 0)
657     {
658         p->preferredMessageSize = 30000;
659         return TCL_OK;
660     }
661     return get_set_int (&p->preferredMessageSize, interp, argc, argv);
662 }
663
664 /*
665  * do_maximumRecordSize: Set/get maximum record size
666  */
667 static int do_maximumRecordSize (void *obj, Tcl_Interp *interp,
668                                  int argc, char **argv)
669 {
670     IrTcl_Obj *p = obj;
671
672     if (argc <= 0)
673     {
674         p->maximumRecordSize = 30000;
675         return TCL_OK;
676     }
677     return get_set_int (&p->maximumRecordSize, interp, argc, argv);
678 }
679
680 /*
681  * do_initResult: Get init result
682  */
683 static int do_initResult (void *obj, Tcl_Interp *interp,
684                           int argc, char **argv)
685 {
686     IrTcl_Obj *p = obj;
687    
688     if (argc <= 0)
689         return TCL_OK;
690     return get_set_int (&p->initResult, interp, argc, argv);
691 }
692
693
694 /*
695  * do_implementationName: Set/get Implementation Name.
696  */
697 static int do_implementationName (void *obj, Tcl_Interp *interp,
698                                     int argc, char **argv)
699 {
700     IrTcl_Obj *p = obj;
701
702     if (argc == 0)
703         return ir_strdup (interp, &p->implementationName,
704                           "Index Data/IrTcl on YAZ");
705     else if (argc == -1)
706         return ir_strdel (interp, &p->implementationName);
707     if (argc == 3)
708     {
709         free (p->implementationName);
710         if (ir_strdup (interp, &p->implementationName, argv[2])
711             == TCL_ERROR)
712             return TCL_ERROR;
713     }
714     Tcl_AppendResult (interp, p->implementationName, (char*) NULL);
715     return TCL_OK;
716 }
717
718 /*
719  * do_implementationId: Get Implementation Id.
720  */
721 static int do_implementationId (void *obj, Tcl_Interp *interp,
722                                 int argc, char **argv)
723 {
724     IrTcl_Obj *p = obj;
725
726     if (argc == 0)
727         return ir_strdup (interp, &p->implementationId, "YAZ (id=81)");
728     else if (argc == -1)
729         return ir_strdel (interp, &p->implementationId);
730     Tcl_AppendResult (interp, p->implementationId, (char*) NULL);
731     return TCL_OK;
732 }
733
734 /*
735  * do_implementationVersion: get Implementation Version.
736  */
737 static int do_implementationVersion (void *obj, Tcl_Interp *interp,
738                                      int argc, char **argv)
739 {
740     IrTcl_Obj *p = obj;
741
742     if (argc == 0)
743         return ir_strdup (interp, &p->implementationVersion, 
744                           "YAZ: " YAZ_VERSION " / IrTcl: " IR_TCL_VERSION);
745     else if (argc == -1)
746         return ir_strdel (interp, &p->implementationVersion);
747     Tcl_AppendResult (interp, p->implementationVersion, (char*) NULL);
748     return TCL_OK;
749 }
750
751 /*
752  * do_targetImplementationName: Get Implementation Name of target.
753  */
754 static int do_targetImplementationName (void *obj, Tcl_Interp *interp,
755                                         int argc, char **argv)
756 {
757     IrTcl_Obj *p = obj;
758
759     if (argc == 0)
760     {
761         p->targetImplementationName = NULL;
762         return TCL_OK;
763     }
764     else if (argc == -1)
765         return ir_strdel (interp, &p->targetImplementationName);
766     Tcl_AppendResult (interp, p->targetImplementationName, (char*) NULL);
767     return TCL_OK;
768 }
769
770 /*
771  * do_targetImplementationId: Get Implementation Id of target
772  */
773 static int do_targetImplementationId (void *obj, Tcl_Interp *interp,
774                                       int argc, char **argv)
775 {
776     IrTcl_Obj *p = obj;
777
778     if (argc == 0)
779     {
780         p->targetImplementationId = NULL;
781         return TCL_OK;
782     }
783     else if (argc == -1)
784         return ir_strdel (interp, &p->targetImplementationId);
785     Tcl_AppendResult (interp, p->targetImplementationId, (char*) NULL);
786     return TCL_OK;
787 }
788
789 /*
790  * do_targetImplementationVersion: Get Implementation Version of target
791  */
792 static int do_targetImplementationVersion (void *obj, Tcl_Interp *interp,
793                                            int argc, char **argv)
794 {
795     IrTcl_Obj *p = obj;
796
797     if (argc == 0)
798     {
799         p->targetImplementationVersion = NULL;
800         return TCL_OK;
801     }
802     else if (argc == -1)
803         return ir_strdel (interp, &p->targetImplementationVersion);
804     Tcl_AppendResult (interp, p->targetImplementationVersion, (char*) NULL);
805     return TCL_OK;
806 }
807
808 /*
809  * do_idAuthentication: Set/get id Authentication
810  */
811 static int do_idAuthentication (void *obj, Tcl_Interp *interp,
812                                 int argc, char **argv)
813 {
814     IrTcl_Obj *p = obj;
815
816     if (argc >= 3 || argc == -1)
817     {
818         free (p->idAuthenticationOpen);
819         free (p->idAuthenticationGroupId);
820         free (p->idAuthenticationUserId);
821         free (p->idAuthenticationPassword);
822     }
823     if (argc >= 3 || argc <= 0)
824     {
825         p->idAuthenticationOpen = NULL;
826         p->idAuthenticationGroupId = NULL;
827         p->idAuthenticationUserId = NULL;
828         p->idAuthenticationPassword = NULL;
829     }
830     if (argc <= 0)
831         return TCL_OK;
832     if (argc >= 3)
833     {
834         if (argc == 3)
835         {
836             if (ir_strdup (interp, &p->idAuthenticationOpen, argv[2])
837                 == TCL_ERROR)
838                 return TCL_ERROR;
839         }
840         else if (argc == 5)
841         {
842             if (ir_strdup (interp, &p->idAuthenticationGroupId, argv[2])
843                 == TCL_ERROR)
844                 return TCL_ERROR;
845             if (ir_strdup (interp, &p->idAuthenticationUserId, argv[3])
846                 == TCL_ERROR)
847                 return TCL_ERROR;
848             if (ir_strdup (interp, &p->idAuthenticationPassword, argv[4])
849                 == TCL_ERROR)
850                 return TCL_ERROR;
851         }
852     }
853     if (p->idAuthenticationOpen)
854         Tcl_AppendElement (interp, p->idAuthenticationOpen);
855     else if (p->idAuthenticationGroupId)
856     {
857         Tcl_AppendElement (interp, p->idAuthenticationGroupId);
858         Tcl_AppendElement (interp, p->idAuthenticationUserId);
859         Tcl_AppendElement (interp, p->idAuthenticationPassword);
860     }
861     return TCL_OK;
862 }
863
864 /*
865  * do_connect: connect method on IR object
866  */
867 static int do_connect (void *obj, Tcl_Interp *interp,
868                        int argc, char **argv)
869 {
870     void *addr;
871     IrTcl_Obj *p = obj;
872     int r;
873
874     if (argc <= 0)
875         return TCL_OK;
876     if (argc == 3)
877     {
878         if (p->hostname)
879         {
880             interp->result = "already connected";
881             return TCL_ERROR;
882         }
883         if (!strcmp (p->cs_type, "tcpip"))
884         {
885             p->cs_link = cs_create (tcpip_type, CS_BLOCK, p->protocol_type);
886             addr = tcpip_strtoaddr (argv[2]);
887             if (!addr)
888             {
889                 interp->result = "tcpip_strtoaddr fail";
890                 return TCL_ERROR;
891             }
892             logf (LOG_DEBUG, "tcp/ip connect %s", argv[2]);
893         }
894         else if (!strcmp (p->cs_type, "mosi"))
895         {
896 #if MOSI
897             p->cs_link = cs_create (mosi_type, CS_BLOCK, p->protocol_type);
898             addr = mosi_strtoaddr (argv[2]);
899             if (!addr)
900             {
901                 interp->result = "mosi_strtoaddr fail";
902                 return TCL_ERROR;
903             }
904             logf (LOG_DEBUG, "mosi connect %s", argv[2]);
905 #else
906             interp->result = "MOSI support not there";
907             return TCL_ERROR;
908 #endif
909         }
910         else 
911         {
912             Tcl_AppendResult (interp, "Bad comstack type: ", 
913                               p->cs_type, NULL);
914             return TCL_ERROR;
915         }
916         if (ir_strdup (interp, &p->hostname, argv[2]) == TCL_ERROR)
917             return TCL_ERROR;
918         if ((r=cs_connect (p->cs_link, addr)) < 0)
919         {
920             interp->result = "connect fail";
921             do_disconnect (p, NULL, 2, NULL);
922             return TCL_ERROR;
923         }
924         ir_select_add (cs_fileno (p->cs_link), p);
925         if (r == 1)
926         {
927             ir_select_add_write (cs_fileno (p->cs_link), p);
928             p->connectFlag = 1;
929         }
930         else
931         {
932             p->connectFlag = 0;
933             if (p->callback)
934                 IrTcl_eval (p->interp, p->callback);
935         }
936     }
937     if (p->hostname)
938         Tcl_AppendElement (interp, p->hostname);
939     return TCL_OK;
940 }
941
942 /*
943  * do_disconnect: disconnect method on IR object
944  */
945 static int do_disconnect (void *obj, Tcl_Interp *interp,
946                           int argc, char **argv)
947 {
948     IrTcl_Obj *p = obj;
949
950     if (argc == 0)
951     {
952         p->connectFlag = 0;
953         p->hostname = NULL;
954         p->cs_link = NULL;
955         return TCL_OK;
956     }
957     if (p->hostname)
958     {
959         free (p->hostname);
960         p->hostname = NULL;
961         ir_select_remove_write (cs_fileno (p->cs_link), p);
962         ir_select_remove (cs_fileno (p->cs_link), p);
963
964         assert (p->cs_link);
965         cs_close (p->cs_link);
966         p->cs_link = NULL;
967
968         ODR_MASK_ZERO (&p->options);
969         ODR_MASK_SET (&p->options, 0);
970         ODR_MASK_SET (&p->options, 1);
971         ODR_MASK_SET (&p->options, 7);
972         ODR_MASK_SET (&p->options, 14);
973
974         ODR_MASK_ZERO (&p->protocolVersion);
975         ODR_MASK_SET (&p->protocolVersion, 0);
976         ODR_MASK_SET (&p->protocolVersion, 1);
977     }
978     assert (!p->cs_link);
979     return TCL_OK;
980 }
981
982 /*
983  * do_comstack: Set/get comstack method on IR object
984  */
985 static int do_comstack (void *o, Tcl_Interp *interp,
986                         int argc, char **argv)
987 {
988     IrTcl_Obj *obj = o;
989
990     if (argc == 0)
991         return ir_strdup (interp, &obj->cs_type, "tcpip");
992     else if (argc == -1)
993         return ir_strdel (interp, &obj->cs_type);
994     else if (argc == 3)
995     {
996         free (obj->cs_type);
997         if (ir_strdup (interp, &obj->cs_type, argv[2]) == TCL_ERROR)
998             return TCL_ERROR;
999     }
1000     Tcl_AppendElement (interp, obj->cs_type);
1001     return TCL_OK;
1002 }
1003
1004
1005 /*
1006  * do_callback: add callback
1007  */
1008 static int do_callback (void *obj, Tcl_Interp *interp,
1009                           int argc, char **argv)
1010 {
1011     IrTcl_Obj *p = obj;
1012
1013     if (argc == 0)
1014     {
1015         p->callback = NULL;
1016         return TCL_OK;
1017     }
1018     else if (argc == -1)
1019         return ir_strdel (interp, &p->callback);
1020     if (argc == 3)
1021     {
1022         free (p->callback);
1023         if (argv[2][0])
1024         {
1025             if (ir_strdup (interp, &p->callback, argv[2]) == TCL_ERROR)
1026                 return TCL_ERROR;
1027         }
1028         else
1029             p->callback = NULL;
1030         p->interp = interp;
1031     }
1032     return TCL_OK;
1033 }
1034
1035 /*
1036  * do_failback: add error handle callback
1037  */
1038 static int do_failback (void *obj, Tcl_Interp *interp,
1039                           int argc, char **argv)
1040 {
1041     IrTcl_Obj *p = obj;
1042
1043     if (argc == 0)
1044     {
1045         p->failback = NULL;
1046         return TCL_OK;
1047     }
1048     else if (argc == -1)
1049         return ir_strdel (interp, &p->failback);
1050     else if (argc == 3)
1051     {
1052         free (p->failback);
1053         if (argv[2][0])
1054         {
1055             if (ir_strdup (interp, &p->failback, argv[2]) == TCL_ERROR)
1056                 return TCL_ERROR;
1057         }
1058         else
1059             p->failback = NULL;
1060         p->interp = interp;
1061     }
1062     return TCL_OK;
1063 }
1064
1065 /*
1066  * do_protocol: Set/get protocol method on IR object
1067  */
1068 static int do_protocol (void *o, Tcl_Interp *interp, int argc, char **argv)
1069 {
1070     IrTcl_Obj *p = o;
1071
1072     if (argc <= 0)
1073     {
1074         p->protocol_type = PROTO_Z3950;
1075         return TCL_OK;
1076     }
1077     else if (argc == 3)
1078     {
1079         if (!strcmp (argv[2], "Z39"))
1080             p->protocol_type = PROTO_Z3950;
1081         else if (!strcmp (argv[2], "SR"))
1082             p->protocol_type = PROTO_SR;
1083         else
1084         {
1085             Tcl_AppendResult (interp, "Bad protocol: ", argv[2], NULL);
1086             return TCL_ERROR;
1087         }
1088         return TCL_OK;
1089     }
1090     switch (p->protocol_type)
1091     {
1092     case PROTO_Z3950:
1093         Tcl_AppendElement (interp, "Z39");
1094         break;
1095     case PROTO_SR:
1096         Tcl_AppendElement (interp, "SR");
1097         break;
1098     }
1099     return TCL_OK;
1100 }
1101
1102 /*
1103  * do_databaseNames: specify database names
1104  */
1105 static int do_databaseNames (void *obj, Tcl_Interp *interp,
1106                              int argc, char **argv)
1107 {
1108     int i;
1109     IrTcl_SetCObj *p = obj;
1110
1111     if (argc == -1)
1112     {
1113         for (i=0; i<p->num_databaseNames; i++)
1114             free (p->databaseNames[i]);
1115         free (p->databaseNames);
1116     }
1117     if (argc <= 0)
1118     {
1119         p->num_databaseNames = 0;
1120         p->databaseNames = NULL;
1121         return TCL_OK;
1122     }
1123     if (argc < 3)
1124     {
1125         for (i=0; i<p->num_databaseNames; i++)
1126             Tcl_AppendElement (interp, p->databaseNames[i]);
1127         return TCL_OK;
1128     }
1129     if (p->databaseNames)
1130     {
1131         for (i=0; i<p->num_databaseNames; i++)
1132             free (p->databaseNames[i]);
1133         free (p->databaseNames);
1134     }
1135     p->num_databaseNames = argc - 2;
1136     if (!(p->databaseNames = ir_malloc (interp, 
1137           sizeof(*p->databaseNames) * p->num_databaseNames)))
1138         return TCL_ERROR;
1139     for (i=0; i<p->num_databaseNames; i++)
1140     {
1141         if (ir_strdup (interp, &p->databaseNames[i], argv[2+i]) 
1142             == TCL_ERROR)
1143             return TCL_ERROR;
1144     }
1145     return TCL_OK;
1146 }
1147
1148 /*
1149  * do_replaceIndicator: Set/get replace Set indicator
1150  */
1151 static int do_replaceIndicator (void *obj, Tcl_Interp *interp,
1152                                 int argc, char **argv)
1153 {
1154     IrTcl_SetCObj *p = obj;
1155
1156     if (argc <= 0)
1157     {
1158         p->replaceIndicator = 1;
1159         return TCL_OK;
1160     }
1161     return get_set_int (&p->replaceIndicator, interp, argc, argv);
1162 }
1163
1164 /*
1165  * do_queryType: Set/Get query method
1166  */
1167 static int do_queryType (void *obj, Tcl_Interp *interp,
1168                        int argc, char **argv)
1169 {
1170     IrTcl_SetCObj *p = obj;
1171
1172     if (argc == 0)
1173         return ir_strdup (interp, &p->queryType, "rpn");
1174     else if (argc == -1)
1175         return ir_strdel (interp, &p->queryType);
1176     if (argc == 3)
1177     {
1178         free (p->queryType);
1179         if (ir_strdup (interp, &p->queryType, argv[2]) == TCL_ERROR)
1180             return TCL_ERROR;
1181     }
1182     Tcl_AppendResult (interp, p->queryType, NULL);
1183     return TCL_OK;
1184 }
1185
1186 /*
1187  * do_userInformationField: Get User information field
1188  */
1189 static int do_userInformationField (void *obj, Tcl_Interp *interp,
1190                                     int argc, char **argv)
1191 {
1192     IrTcl_Obj *p = obj;
1193     
1194     if (argc == 0)
1195     {
1196         p->userInformationField = NULL;
1197         return TCL_OK;
1198     }
1199     else if (argc == -1)
1200         return ir_strdel (interp, &p->userInformationField);
1201     Tcl_AppendResult (interp, p->userInformationField, NULL);
1202     return TCL_OK;
1203 }
1204
1205 /*
1206  * do_smallSetUpperBound: Set/get small set upper bound
1207  */
1208 static int do_smallSetUpperBound (void *o, Tcl_Interp *interp,
1209                        int argc, char **argv)
1210 {
1211     IrTcl_SetCObj *p = o;
1212
1213     if (argc <= 0)
1214     {
1215         p->smallSetUpperBound = 0;
1216         return TCL_OK;
1217     }
1218     return get_set_int (&p->smallSetUpperBound, interp, argc, argv);
1219 }
1220
1221 /*
1222  * do_largeSetLowerBound: Set/get large set lower bound
1223  */
1224 static int do_largeSetLowerBound (void *o, Tcl_Interp *interp,
1225                                   int argc, char **argv)
1226 {
1227     IrTcl_SetCObj *p = o;
1228
1229     if (argc <= 0)
1230     {
1231         p->largeSetLowerBound = 2;
1232         return TCL_OK;
1233     }
1234     return get_set_int (&p->largeSetLowerBound, interp, argc, argv);
1235 }
1236
1237 /*
1238  * do_mediumSetPresentNumber: Set/get large set lower bound
1239  */
1240 static int do_mediumSetPresentNumber (void *o, Tcl_Interp *interp,
1241                                       int argc, char **argv)
1242 {
1243     IrTcl_SetCObj *p = o;
1244    
1245     if (argc <= 0)
1246     {
1247         p->mediumSetPresentNumber = 0;
1248         return TCL_OK;
1249     }
1250     return get_set_int (&p->mediumSetPresentNumber, interp, argc, argv);
1251 }
1252
1253 /*
1254  * do_referenceId: Set/Get referenceId
1255  */
1256 static int do_referenceId (void *obj, Tcl_Interp *interp,
1257                            int argc, char **argv)
1258 {
1259     IrTcl_SetCObj *p = obj;
1260
1261     if (argc == 0)
1262     {
1263         p->referenceId = NULL;
1264         return TCL_OK;
1265     }
1266     else if (argc == -1)
1267         return ir_strdel (interp, &p->referenceId);
1268     if (argc == 3)
1269     {
1270         free (p->referenceId);
1271         if (ir_strdup (interp, &p->referenceId, argv[2]) == TCL_ERROR)
1272             return TCL_ERROR;
1273     }
1274     Tcl_AppendResult (interp, p->referenceId, NULL);
1275     return TCL_OK;
1276 }
1277
1278 /*
1279  * do_preferredRecordSyntax: Set/get preferred record syntax
1280  */
1281 static int do_preferredRecordSyntax (void *obj, Tcl_Interp *interp,
1282                                      int argc, char **argv)
1283 {
1284     IrTcl_SetCObj *p = obj;
1285
1286     if (argc == 0)
1287     {
1288         p->preferredRecordSyntax = NULL;
1289         return TCL_OK;
1290     }
1291     else if (argc == -1)
1292     {
1293         free (p->preferredRecordSyntax);
1294         p->preferredRecordSyntax = NULL;
1295         return TCL_OK;
1296     }
1297     if (argc == 3)
1298     {
1299         free (p->preferredRecordSyntax);
1300         p->preferredRecordSyntax = NULL;
1301         if (argv[2][0] && (p->preferredRecordSyntax = 
1302                            malloc (sizeof(*p->preferredRecordSyntax))))
1303             *p->preferredRecordSyntax = IrTcl_getRecordSyntaxVal (argv[2]);
1304     }
1305     return TCL_OK;
1306             
1307 }
1308 static IrTcl_Method ir_method_tab[] = {
1309 { 1, "comstack",                    do_comstack },
1310 { 1, "protocol",                    do_protocol },
1311 { 0, "failback",                    do_failback },
1312
1313 { 1, "connect",                     do_connect },
1314 { 0, "protocolVersion",             do_protocolVersion },
1315 { 1, "preferredMessageSize",        do_preferredMessageSize },
1316 { 1, "maximumRecordSize",           do_maximumRecordSize },
1317 { 1, "implementationName",          do_implementationName },
1318 { 1, "implementationId",            do_implementationId },
1319 { 1, "implementationVersion",       do_implementationVersion },
1320 { 0, "targetImplementationName",    do_targetImplementationName },
1321 { 0, "targetImplementationId",      do_targetImplementationId },
1322 { 0, "targetImplementationVersion", do_targetImplementationVersion },
1323 { 0, "userInformationField",        do_userInformationField },
1324 { 1, "idAuthentication",            do_idAuthentication },
1325 { 0, "options",                     do_options },
1326 { 0, "init",                        do_init_request },
1327 { 0, "initResult",                  do_initResult },
1328 { 0, "disconnect",                  do_disconnect },
1329 { 0, "callback",                    do_callback },
1330 { 0, NULL, NULL}
1331 };
1332
1333 static IrTcl_Method ir_set_c_method_tab[] = {
1334 { 0, "databaseNames",               do_databaseNames},
1335 { 0, "replaceIndicator",            do_replaceIndicator},
1336 { 0, "queryType",                   do_queryType },
1337 { 0, "preferredRecordSyntax",       do_preferredRecordSyntax },
1338 { 0, "smallSetUpperBound",          do_smallSetUpperBound},
1339 { 0, "largeSetLowerBound",          do_largeSetLowerBound},
1340 { 0, "mediumSetPresentNumber",      do_mediumSetPresentNumber},
1341 { 0, "referenceId",                 do_referenceId },
1342 { 0, NULL, NULL}
1343 };
1344
1345 /* 
1346  * ir_obj_method: IR Object methods
1347  */
1348 static int ir_obj_method (ClientData clientData, Tcl_Interp *interp,
1349                           int argc, char **argv)
1350 {
1351     IrTcl_Methods tab[3];
1352     IrTcl_Obj *p = clientData;
1353
1354     if (argc < 2)
1355         return ir_method_r (clientData, interp, argc, argv, ir_method_tab);
1356
1357     tab[0].tab = ir_method_tab;
1358     tab[0].obj = p;
1359     tab[1].tab = ir_set_c_method_tab;
1360     tab[1].obj = &p->set_inher;
1361     tab[2].tab = NULL;
1362
1363     return ir_method (interp, argc, argv, tab);
1364 }
1365
1366 /* 
1367  * ir_obj_delete: IR Object disposal
1368  */
1369 static void ir_obj_delete (ClientData clientData)
1370 {
1371     IrTcl_Obj *obj = clientData;
1372     IrTcl_Methods tab[3];
1373
1374     --(obj->ref_count);
1375     if (obj->ref_count > 0)
1376         return;
1377     assert (obj->ref_count == 0);
1378
1379     tab[0].tab = ir_method_tab;
1380     tab[0].obj = obj;
1381     tab[1].tab = ir_set_c_method_tab;
1382     tab[1].obj = &obj->set_inher;
1383     tab[2].tab = NULL;
1384
1385     ir_method (NULL, -1, NULL, tab);
1386     odr_destroy (obj->odr_in);
1387     odr_destroy (obj->odr_out);
1388     odr_destroy (obj->odr_pr);
1389     free (obj->buf_out);
1390     free (obj->buf_in);
1391     free (obj);
1392 }
1393
1394 /* 
1395  * ir_obj_mk: IR Object creation
1396  */
1397 static int ir_obj_mk (ClientData clientData, Tcl_Interp *interp,
1398                       int argc, char **argv)
1399 {
1400     IrTcl_Methods tab[3];
1401     IrTcl_Obj *obj;
1402 #if CCL2RPN
1403     FILE *inf;
1404 #endif
1405
1406     if (argc != 2)
1407     {
1408         interp->result = "wrong # args";
1409         return TCL_ERROR;
1410     }
1411     if (!(obj = ir_malloc (interp, sizeof(*obj))))
1412         return TCL_ERROR;
1413
1414     obj->ref_count = 1;
1415 #if CCL2RPN
1416     obj->bibset = ccl_qual_mk (); 
1417     if ((inf = fopen ("default.bib", "r")))
1418     {
1419         ccl_qual_file (obj->bibset, inf);
1420         fclose (inf);
1421     }
1422 #endif
1423
1424     obj->odr_in = odr_createmem (ODR_DECODE);
1425     obj->odr_out = odr_createmem (ODR_ENCODE);
1426     obj->odr_pr = odr_createmem (ODR_PRINT);
1427
1428     obj->len_out = 10000;
1429     if (!(obj->buf_out = ir_malloc (interp, obj->len_out)))
1430         return TCL_ERROR;
1431     odr_setbuf (obj->odr_out, obj->buf_out, obj->len_out, 0);
1432
1433     obj->len_in = 0;
1434     obj->buf_in = NULL;
1435
1436     tab[0].tab = ir_method_tab;
1437     tab[0].obj = obj;
1438     tab[1].tab = ir_set_c_method_tab;
1439     tab[1].obj = &obj->set_inher;
1440     tab[2].tab = NULL;
1441
1442     if (ir_method (interp, 0, NULL, tab) == TCL_ERROR)
1443         return TCL_ERROR;
1444     Tcl_CreateCommand (interp, argv[1], ir_obj_method,
1445                        (ClientData) obj, ir_obj_delete);
1446     return TCL_OK;
1447 }
1448
1449 /* ------------------------------------------------------- */
1450 /*
1451  * do_search: Do search request
1452  */
1453 static int do_search (void *o, Tcl_Interp *interp, int argc, char **argv)
1454 {
1455     Z_SearchRequest *req;
1456     Z_Query query;
1457     Z_APDU *apdu;
1458     Odr_oct ccl_query;
1459     IrTcl_SetObj *obj = o;
1460     IrTcl_Obj *p = obj->parent;
1461     int r;
1462     oident bib1;
1463
1464     if (argc <= 0)
1465         return TCL_OK;
1466
1467     p->set_child = o;
1468     if (argc != 3)
1469     {
1470         interp->result = "wrong # args";
1471         return TCL_ERROR;
1472     }
1473     if (!obj->set_inher.num_databaseNames)
1474     {
1475         interp->result = "no databaseNames";
1476         return TCL_ERROR;
1477     }
1478     if (!p->cs_link)
1479     {
1480         interp->result = "not connected";
1481         return TCL_ERROR;
1482     }
1483     odr_reset (p->odr_out);
1484     apdu = zget_APDU (p->odr_out, Z_APDU_searchRequest);
1485     req = apdu->u.searchRequest;
1486
1487     bib1.proto = p->protocol_type;
1488     bib1.class = CLASS_ATTSET;
1489     bib1.value = VAL_BIB1;
1490
1491     set_referenceId (p->odr_out, &req->referenceId,
1492                      obj->set_inher.referenceId);
1493
1494     req->smallSetUpperBound = &obj->set_inher.smallSetUpperBound;
1495     req->largeSetLowerBound = &obj->set_inher.largeSetLowerBound;
1496     req->mediumSetPresentNumber = &obj->set_inher.mediumSetPresentNumber;
1497     req->replaceIndicator = &obj->set_inher.replaceIndicator;
1498     req->resultSetName = obj->setName ? obj->setName : "Default";
1499     logf (LOG_DEBUG, "Search, resultSetName %s", req->resultSetName);
1500     req->num_databaseNames = obj->set_inher.num_databaseNames;
1501     req->databaseNames = obj->set_inher.databaseNames;
1502     for (r=0; r < obj->set_inher.num_databaseNames; r++)
1503         logf (LOG_DEBUG, " Database %s", obj->set_inher.databaseNames[r]);
1504     req->smallSetElementSetNames = 0;
1505     req->mediumSetElementSetNames = 0;
1506     if (obj->set_inher.preferredRecordSyntax)
1507     {
1508         struct oident ident;
1509
1510         ident.proto = p->protocol_type;
1511         ident.class = CLASS_RECSYN;
1512         ident.value = *obj->set_inher.preferredRecordSyntax;
1513         req->preferredRecordSyntax = odr_oiddup (p->odr_out, 
1514                                                  oid_getoidbyent (&ident));
1515     }
1516     else
1517         req->preferredRecordSyntax = 0;
1518     req->query = &query;
1519
1520     if (!strcmp (obj->set_inher.queryType, "rpn"))
1521     {
1522         Z_RPNQuery *RPNquery;
1523
1524         RPNquery = p_query_rpn (p->odr_out, argv[2]);
1525         if (!RPNquery)
1526         {
1527             Tcl_AppendResult (interp, "Syntax error in query", NULL);
1528             return TCL_ERROR;
1529         }
1530         RPNquery->attributeSetId = oid_getoidbyent (&bib1);
1531         query.which = Z_Query_type_1;
1532         query.u.type_1 = RPNquery;
1533         logf (LOG_DEBUG, "RPN");
1534     }
1535 #if CCL2RPN
1536     else if (!strcmp (obj->set_inher.queryType, "cclrpn"))
1537     {
1538         int error;
1539         int pos;
1540         struct ccl_rpn_node *rpn;
1541         Z_RPNQuery *RPNquery;
1542
1543         rpn = ccl_find_str(p->bibset, argv[2], &error, &pos);
1544         if (error)
1545         {
1546             Tcl_AppendResult (interp, "CCL error: ", 
1547                               ccl_err_msg(error), NULL);
1548             return TCL_ERROR;
1549         }
1550         ccl_pr_tree (rpn, stderr);
1551         fprintf (stderr, "\n");
1552         assert((RPNquery = ccl_rpn_query(rpn)));
1553         RPNquery->attributeSetId = oid_getoidbyent (&bib1);
1554         query.which = Z_Query_type_1;
1555         query.u.type_1 = RPNquery;
1556         logf (LOG_DEBUG, "CCLRPN");
1557     }
1558 #endif
1559     else if (!strcmp (obj->set_inher.queryType, "ccl"))
1560     {
1561         query.which = Z_Query_type_2;
1562         query.u.type_2 = &ccl_query;
1563         ccl_query.buf = (unsigned char *) argv[2];
1564         ccl_query.len = strlen (argv[2]);
1565         logf (LOG_DEBUG, "CCL");
1566     }
1567     else
1568     {
1569         interp->result = "unknown query method";
1570         return TCL_ERROR;
1571     }
1572     if (!z_APDU (p->odr_out, &apdu, 0))
1573     {
1574         interp->result = odr_errlist [odr_geterror (p->odr_out)];
1575         odr_reset (p->odr_out);
1576         return TCL_ERROR;
1577     } 
1578     p->sbuf = odr_getbuf (p->odr_out, &p->slen, NULL);
1579     if ((r=cs_put (p->cs_link, p->sbuf, p->slen)) < 0)
1580     {
1581         interp->result = "cs_put failed in search";
1582         return TCL_ERROR;
1583     }
1584     else if (r == 1)
1585     {
1586         ir_select_add_write (cs_fileno(p->cs_link), p);
1587         logf (LOG_DEBUG, "Sent part of searchRequest (%d bytes)", p->slen);
1588     }
1589     else
1590     {
1591         logf (LOG_DEBUG, "Whole search request (%d bytes)", p->slen);
1592     }
1593     return TCL_OK;
1594 }
1595
1596 /*
1597  * do_resultCount: Get number of hits
1598  */
1599 static int do_resultCount (void *o, Tcl_Interp *interp,
1600                        int argc, char **argv)
1601 {
1602     IrTcl_SetObj *obj = o;
1603
1604     if (argc <= 0)
1605         return TCL_OK;
1606     return get_set_int (&obj->resultCount, interp, argc, argv);
1607 }
1608
1609 /*
1610  * do_searchStatus: Get search status (after search response)
1611  */
1612 static int do_searchStatus (void *o, Tcl_Interp *interp,
1613                             int argc, char **argv)
1614 {
1615     IrTcl_SetObj *obj = o;
1616
1617     if (argc <= 0)
1618         return TCL_OK;
1619     return get_set_int (&obj->searchStatus, interp, argc, argv);
1620 }
1621
1622 /*
1623  * do_presentStatus: Get search status (after search/present response)
1624  */
1625 static int do_presentStatus (void *o, Tcl_Interp *interp,
1626                             int argc, char **argv)
1627 {
1628     IrTcl_SetObj *obj = o;
1629
1630     if (argc <= 0)
1631         return TCL_OK;
1632     return get_set_int (&obj->presentStatus, interp, argc, argv);
1633 }
1634
1635 /*
1636  * do_nextResultSetPosition: Get next result set position
1637  *       (after search/present response)
1638  */
1639 static int do_nextResultSetPosition (void *o, Tcl_Interp *interp,
1640                                      int argc, char **argv)
1641 {
1642     IrTcl_SetObj *obj = o;
1643
1644     if (argc <= 0)
1645         return TCL_OK;
1646     return get_set_int (&obj->nextResultSetPosition, interp, argc, argv);
1647 }
1648
1649 /*
1650  * do_setName: Set result Set name
1651  */
1652 static int do_setName (void *o, Tcl_Interp *interp,
1653                        int argc, char **argv)
1654 {
1655     IrTcl_SetObj *obj = o;
1656
1657     if (argc == 0)
1658         return ir_strdup (interp, &obj->setName, "Default");
1659     else if (argc == -1)
1660         return ir_strdel (interp, &obj->setName);
1661     if (argc == 3)
1662     {
1663         free (obj->setName);
1664         if (ir_strdup (interp, &obj->setName, argv[2])
1665             == TCL_ERROR)
1666             return TCL_ERROR;
1667     }
1668     Tcl_AppendElement (interp, obj->setName);
1669     return TCL_OK;
1670 }
1671
1672 /*
1673  * do_numberOfRecordsReturned: Get number of records returned
1674  */
1675 static int do_numberOfRecordsReturned (void *o, Tcl_Interp *interp,
1676                                        int argc, char **argv)
1677 {
1678     IrTcl_SetObj *obj = o;
1679
1680     if (argc <= 0)
1681     {
1682         obj->numberOfRecordsReturned = 0;
1683         return TCL_OK;
1684     }
1685     return get_set_int (&obj->numberOfRecordsReturned, interp, argc, argv);
1686 }
1687
1688 /*
1689  * do_type: Return type (if any) at position.
1690  */
1691 static int do_type (void *o, Tcl_Interp *interp, int argc, char **argv)
1692 {
1693     IrTcl_SetObj *obj = o;
1694     int offset;
1695     IrTcl_RecordList *rl;
1696
1697     if (argc == 0)
1698     {
1699         obj->record_list = NULL;
1700         return TCL_OK;
1701     }
1702     else if (argc == -1)
1703     {
1704         delete_IR_records (obj);
1705         return TCL_OK;
1706     }
1707     if (argc < 3)
1708     {
1709         sprintf (interp->result, "wrong # args");
1710         return TCL_ERROR;
1711     }
1712     if (Tcl_GetInt (interp, argv[2], &offset)==TCL_ERROR)
1713         return TCL_ERROR;
1714     rl = find_IR_record (obj, offset);
1715     if (!rl)
1716         return TCL_OK;
1717     switch (rl->which)
1718     {
1719     case Z_NamePlusRecord_databaseRecord:
1720         interp->result = "DB";
1721         break;
1722     case Z_NamePlusRecord_surrogateDiagnostic:
1723         interp->result = "SD";
1724         break;
1725     }
1726     return TCL_OK;
1727 }
1728
1729
1730 /*
1731  * do_recordType: Return record type (if any) at position.
1732  */
1733 static int do_recordType (void *o, Tcl_Interp *interp, int argc, char **argv)
1734 {
1735     IrTcl_SetObj *obj = o;
1736     int offset;
1737     IrTcl_RecordList *rl;
1738
1739     if (argc == 0)
1740     {
1741         return TCL_OK;
1742     }
1743     else if (argc == -1)
1744     {
1745         return TCL_OK;
1746     }
1747     if (argc < 3)
1748     {
1749         sprintf (interp->result, "wrong # args");
1750         return TCL_ERROR;
1751     }
1752     if (Tcl_GetInt (interp, argv[2], &offset)==TCL_ERROR)
1753         return TCL_ERROR;
1754     rl = find_IR_record (obj, offset);
1755     if (!rl)
1756         return TCL_OK;
1757     if (rl->which != Z_NamePlusRecord_databaseRecord)
1758     {
1759         Tcl_AppendResult (interp, "No DB record at #", argv[2], NULL);
1760         return TCL_ERROR;
1761     }
1762     Tcl_AppendElement (interp, (char*)
1763                        IrTcl_getRecordSyntaxStr (rl->u.dbrec.type));
1764     return TCL_OK;
1765 }
1766
1767 /*
1768  * ir_diagResult 
1769  */
1770 static int ir_diagResult (Tcl_Interp *interp, IrTcl_Diagnostic *list, int num)
1771 {
1772     char buf[20];
1773     int i;
1774     const char *cp;
1775
1776     for (i = 0; i<num; i++)
1777     {
1778         logf (LOG_DEBUG, "Diagnostic, code %d", list[i].condition);
1779         sprintf (buf, "%d", list[i].condition);
1780         Tcl_AppendElement (interp, buf);
1781         cp = diagbib1_str (list[i].condition);
1782         if (cp)
1783             Tcl_AppendElement (interp, (char*) cp);
1784         else
1785             Tcl_AppendElement (interp, "");
1786         if (list[i].addinfo)
1787             Tcl_AppendElement (interp, (char*) list[i].addinfo);
1788         else
1789             Tcl_AppendElement (interp, "");
1790     }
1791     return TCL_OK;
1792 }
1793
1794 /*
1795  * do_diag: Return diagnostic record info
1796  */
1797 static int do_diag (void *o, Tcl_Interp *interp, int argc, char **argv)
1798 {
1799     IrTcl_SetObj *obj = o;
1800     int offset;
1801     IrTcl_RecordList *rl;
1802
1803     if (argc <= 0)
1804         return TCL_OK;
1805     if (argc < 3)
1806     {
1807         sprintf (interp->result, "wrong # args");
1808         return TCL_ERROR;
1809     }
1810     if (Tcl_GetInt (interp, argv[2], &offset)==TCL_ERROR)
1811         return TCL_ERROR;
1812     rl = find_IR_record (obj, offset);
1813     if (!rl)
1814     {
1815         Tcl_AppendResult (interp, "No record at #", argv[2], NULL);
1816         return TCL_ERROR;
1817     }
1818     if (rl->which != Z_NamePlusRecord_surrogateDiagnostic)
1819     {
1820         Tcl_AppendResult (interp, "No Diagnostic record at #", argv[2], NULL);
1821         return TCL_ERROR;
1822     }
1823     return ir_diagResult (interp, rl->u.surrogateDiagnostics.list,
1824                           rl->u.surrogateDiagnostics.num);
1825 }
1826
1827 /*
1828  * do_getMarc: Get ISO2709 Record lines/fields
1829  */
1830 static int do_getMarc (void *o, Tcl_Interp *interp, int argc, char **argv)
1831 {
1832     IrTcl_SetObj *obj = o;
1833     int offset;
1834     IrTcl_RecordList *rl;
1835
1836     if (argc <= 0)
1837         return TCL_OK;
1838     if (argc < 7)
1839     {
1840         sprintf (interp->result, "wrong # args");
1841         return TCL_ERROR;
1842     }
1843     if (Tcl_GetInt (interp, argv[2], &offset)==TCL_ERROR)
1844         return TCL_ERROR;
1845     rl = find_IR_record (obj, offset);
1846     if (!rl)
1847     {
1848         Tcl_AppendResult (interp, "No record at #", argv[2], NULL);
1849         return TCL_ERROR;
1850     }
1851     if (rl->which != Z_NamePlusRecord_databaseRecord)
1852     {
1853         Tcl_AppendResult (interp, "No DB record at #", argv[2], NULL);
1854         return TCL_ERROR;
1855     }
1856     return ir_tcl_get_marc (interp, rl->u.dbrec.buf, argc, argv);
1857 }
1858
1859
1860 /*
1861  * do_responseStatus: Return response status (present or search)
1862  */
1863 static int do_responseStatus (void *o, Tcl_Interp *interp, 
1864                              int argc, char **argv)
1865 {
1866     IrTcl_SetObj *obj = o;
1867
1868     if (argc == 0)
1869     {
1870         obj->recordFlag = 0;
1871         obj->nonSurrogateDiagnosticNum = 0;
1872         obj->nonSurrogateDiagnosticList = NULL;
1873         return TCL_OK;
1874     }
1875     else if (argc == -1)
1876     {
1877         ir_deleteDiags (&obj->nonSurrogateDiagnosticList,
1878                         &obj->nonSurrogateDiagnosticNum);
1879         return TCL_OK;
1880     }
1881     if (!obj->recordFlag)
1882     {
1883         Tcl_AppendElement (interp, "OK");
1884         return TCL_OK;
1885     }
1886     switch (obj->which)
1887     {
1888     case Z_Records_DBOSD:
1889         Tcl_AppendElement (interp, "DBOSD");
1890         break;
1891     case Z_Records_NSD:
1892         Tcl_AppendElement (interp, "NSD");
1893         return ir_diagResult (interp, obj->nonSurrogateDiagnosticList,
1894                               obj->nonSurrogateDiagnosticNum);
1895     }
1896     return TCL_OK;
1897 }
1898
1899 /*
1900  * do_present: Perform Present Request
1901  */
1902
1903 static int do_present (void *o, Tcl_Interp *interp,
1904                        int argc, char **argv)
1905 {
1906     IrTcl_SetObj *obj = o;
1907     IrTcl_Obj *p = obj->parent;
1908     Z_APDU *apdu;
1909     Z_PresentRequest *req;
1910     int start;
1911     int number;
1912     int r;
1913
1914     if (argc <= 0)
1915         return TCL_OK;
1916     if (argc >= 3)
1917     {
1918         if (Tcl_GetInt (interp, argv[2], &start) == TCL_ERROR)
1919             return TCL_ERROR;
1920     }
1921     else
1922         start = 1;
1923     if (argc >= 4)
1924     {
1925         if (Tcl_GetInt (interp, argv[3], &number) == TCL_ERROR)
1926             return TCL_ERROR;
1927     }
1928     else 
1929         number = 10;
1930     if (!p->cs_link)
1931     {
1932         interp->result = "not connected";
1933         return TCL_ERROR;
1934     }
1935     odr_reset (p->odr_out);
1936     obj->start = start;
1937     obj->number = number;
1938
1939     apdu = zget_APDU (p->odr_out, Z_APDU_presentRequest);
1940     req = apdu->u.presentRequest;
1941
1942     set_referenceId (p->odr_out, &req->referenceId,
1943                      obj->set_inher.referenceId);
1944
1945     req->resultSetId = obj->setName ? obj->setName : "Default";
1946     
1947     req->resultSetStartPoint = &start;
1948     req->numberOfRecordsRequested = &number;
1949     req->preferredRecordSyntax = 0;
1950
1951     if (!z_APDU (p->odr_out, &apdu, 0))
1952     {
1953         interp->result = odr_errlist [odr_geterror (p->odr_out)];
1954         odr_reset (p->odr_out);
1955         return TCL_ERROR;
1956     } 
1957     p->sbuf = odr_getbuf (p->odr_out, &p->slen, NULL);
1958     if ((r=cs_put (p->cs_link, p->sbuf, p->slen)) < 0)
1959     {
1960         interp->result = "cs_put failed in present";
1961         return TCL_ERROR;
1962     }
1963     else if (r == 1)
1964     {
1965         ir_select_add_write (cs_fileno(p->cs_link), p);
1966         logf (LOG_DEBUG, "Part of present request, start=%d, num=%d" 
1967               " (%d bytes)", start, number, p->slen);
1968     }
1969     else
1970     {
1971         logf (LOG_DEBUG, "Whole present request, start=%d, num=%d"
1972               " (%d bytes)", start, number, p->slen);
1973     }
1974     return TCL_OK;
1975 }
1976
1977 /*
1978  * do_loadFile: Load result set from file
1979  */
1980
1981 static int do_loadFile (void *o, Tcl_Interp *interp,
1982                         int argc, char **argv)
1983 {
1984     IrTcl_SetObj *setobj = o;
1985     FILE *inf;
1986     size_t size;
1987     int  no = 1;
1988     char *buf;
1989
1990     if (argc <= 0)
1991         return TCL_OK;
1992     if (argc < 3)
1993     {
1994         interp->result = "wrong # args";
1995         return TCL_ERROR;
1996     }
1997     inf = fopen (argv[2], "r");
1998     if (!inf)
1999     {
2000         Tcl_AppendResult (interp, "Cannot open ", argv[2], NULL);
2001         return TCL_ERROR;
2002     }
2003     while ((buf = ir_tcl_fread_marc (inf, &size)))
2004     {
2005         IrTcl_RecordList *rl;
2006
2007         rl = new_IR_record (setobj, no, Z_NamePlusRecord_databaseRecord);
2008         rl->u.dbrec.buf = buf;
2009         rl->u.dbrec.size = size;
2010         no++;
2011     }
2012     setobj->numberOfRecordsReturned = no-1;
2013     fclose (inf);
2014     return TCL_OK;
2015 }
2016
2017 static IrTcl_Method ir_set_method_tab[] = {
2018     { 0, "search",                  do_search },
2019     { 0, "searchStatus",            do_searchStatus },
2020     { 0, "presentStatus",           do_presentStatus },
2021     { 0, "nextResultSetPosition",   do_nextResultSetPosition },
2022     { 0, "setName",                 do_setName },
2023     { 0, "resultCount",             do_resultCount },
2024     { 0, "numberOfRecordsReturned", do_numberOfRecordsReturned },
2025     { 0, "present",                 do_present },
2026     { 0, "type",                    do_type },
2027     { 0, "getMarc",                 do_getMarc },
2028     { 0, "recordType",              do_recordType },
2029     { 0, "diag",                    do_diag },
2030     { 0, "responseStatus",          do_responseStatus },
2031     { 0, "loadFile",                do_loadFile },
2032     { 0, NULL, NULL}
2033 };
2034
2035 /* 
2036  * ir_set_obj_method: IR Set Object methods
2037  */
2038 static int ir_set_obj_method (ClientData clientData, Tcl_Interp *interp,
2039                           int argc, char **argv)
2040 {
2041     IrTcl_Methods tabs[3];
2042     IrTcl_SetObj *p = clientData;
2043
2044     if (argc < 2)
2045     {
2046         interp->result = "wrong # args";
2047         return TCL_ERROR;
2048     }
2049     tabs[0].tab = ir_set_method_tab;
2050     tabs[0].obj = p;
2051     tabs[1].tab = ir_set_c_method_tab;
2052     tabs[1].obj = &p->set_inher;
2053     tabs[2].tab = NULL;
2054
2055     return ir_method (interp, argc, argv, tabs);
2056 }
2057
2058 /* 
2059  * ir_set_obj_delete: IR Set Object disposal
2060  */
2061 static void ir_set_obj_delete (ClientData clientData)
2062 {
2063     IrTcl_Methods tabs[3];
2064     IrTcl_SetObj *p = clientData;
2065
2066     tabs[0].tab = ir_set_method_tab;
2067     tabs[0].obj = p;
2068     tabs[1].tab = ir_set_c_method_tab;
2069     tabs[1].obj = &p->set_inher;
2070     tabs[2].tab = NULL;
2071
2072     ir_method (NULL, -1, NULL, tabs);
2073
2074     free (p);
2075 }
2076
2077 /*
2078  * ir_set_obj_mk: IR Set Object creation
2079  */
2080 static int ir_set_obj_mk (ClientData clientData, Tcl_Interp *interp,
2081                           int argc, char **argv)
2082 {
2083     IrTcl_Methods tabs[3];
2084     IrTcl_SetObj *obj;
2085
2086     if (argc < 2 || argc > 3)
2087     {
2088         interp->result = "wrong # args";
2089         return TCL_ERROR;
2090     }
2091     if (!(obj = ir_malloc (interp, sizeof(*obj))))
2092         return TCL_ERROR;
2093     else if (argc == 3)
2094     {
2095         Tcl_CmdInfo parent_info;
2096         int i;
2097         IrTcl_SetCObj *dst;
2098         IrTcl_SetCObj *src;
2099
2100         if (!Tcl_GetCommandInfo (interp, argv[2], &parent_info))
2101         {
2102             interp->result = "No parent";
2103             return TCL_ERROR;
2104         }
2105         obj->parent = (IrTcl_Obj *) parent_info.clientData;
2106
2107         dst = &obj->set_inher;
2108         src = &obj->parent->set_inher;
2109
2110         dst->num_databaseNames = src->num_databaseNames;
2111         if (!(dst->databaseNames =
2112               ir_malloc (interp, sizeof (*dst->databaseNames)
2113                          * dst->num_databaseNames)))
2114             return TCL_ERROR;
2115         for (i = 0; i < dst->num_databaseNames; i++)
2116         {
2117             if (ir_strdup (interp, &dst->databaseNames[i],
2118                            src->databaseNames[i]) == TCL_ERROR)
2119                 return TCL_ERROR;
2120         }
2121         if (ir_strdup (interp, &dst->queryType, src->queryType)
2122             == TCL_ERROR)
2123             return TCL_ERROR;
2124
2125         if (ir_strdup (interp, &dst->referenceId, src->referenceId)
2126             == TCL_ERROR)
2127             return TCL_ERROR;
2128
2129         if (src->preferredRecordSyntax && 
2130             (dst->preferredRecordSyntax 
2131              = malloc (sizeof(*dst->preferredRecordSyntax))))
2132             *dst->preferredRecordSyntax = *src->preferredRecordSyntax;
2133         else
2134             dst->preferredRecordSyntax = NULL;
2135         dst->replaceIndicator = src->replaceIndicator;
2136         dst->smallSetUpperBound = src->smallSetUpperBound;
2137         dst->largeSetLowerBound = src->largeSetLowerBound;
2138         dst->mediumSetPresentNumber = src->mediumSetPresentNumber;
2139     }   
2140     else
2141         obj->parent = NULL;
2142
2143     tabs[0].tab = ir_set_method_tab;
2144     tabs[0].obj = obj;
2145     tabs[1].tab = NULL;
2146
2147     if (ir_method (interp, 0, NULL, tabs) == TCL_ERROR)
2148         return TCL_ERROR;
2149
2150     Tcl_CreateCommand (interp, argv[1], ir_set_obj_method,
2151                        (ClientData) obj, ir_set_obj_delete);
2152     return TCL_OK;
2153 }
2154
2155 /* ------------------------------------------------------- */
2156
2157 /*
2158  * do_scan: Perform scan 
2159  */
2160 static int do_scan (void *o, Tcl_Interp *interp, int argc, char **argv)
2161 {
2162     Z_ScanRequest *req;
2163     Z_APDU *apdu;
2164     IrTcl_ScanObj *obj = o;
2165     IrTcl_Obj *p = obj->parent;
2166     int r;
2167     oident bib1;
2168 #if CCL2RPN
2169     struct ccl_rpn_node *rpn;
2170     int pos;
2171 #endif
2172
2173     if (argc <= 0)
2174         return TCL_OK;
2175     p->scan_child = o;
2176     if (argc != 3)
2177     {
2178         interp->result = "wrong # args";
2179         return TCL_ERROR;
2180     }
2181     if (!p->set_inher.num_databaseNames)
2182     {
2183         interp->result = "no databaseNames";
2184         return TCL_ERROR;
2185     }
2186     if (!p->cs_link)
2187     {
2188         interp->result = "not connected";
2189         return TCL_ERROR;
2190     }
2191     odr_reset (p->odr_out);
2192
2193     bib1.proto = p->protocol_type;
2194     bib1.class = CLASS_ATTSET;
2195     bib1.value = VAL_BIB1;
2196
2197     apdu = zget_APDU (p->odr_out, Z_APDU_scanRequest);
2198     req = apdu->u.scanRequest;
2199
2200     set_referenceId (p->odr_out, &req->referenceId, p->set_inher.referenceId);
2201     req->num_databaseNames = p->set_inher.num_databaseNames;
2202     req->databaseNames = p->set_inher.databaseNames;
2203     req->attributeSet = oid_getoidbyent (&bib1);
2204
2205 #if !CCL2RPN
2206     if (!(req->termListAndStartPoint = p_query_scan (p->odr_out, argv[2])))
2207     {
2208         Tcl_AppendResult (interp, "Syntax error in query", NULL);
2209         return TCL_ERROR;
2210     }
2211 #else
2212     rpn = ccl_find_str(p->bibset, argv[2], &r, &pos);
2213     if (r)
2214     {
2215         Tcl_AppendResult (interp, "CCL error: ", ccl_err_msg (r), NULL);
2216         return TCL_ERROR;
2217     }
2218     ccl_pr_tree (rpn, stderr);
2219     fprintf (stderr, "\n");
2220     if (!(req->termListAndStartPoint = ccl_scan_query (rpn)))
2221         return TCL_ERROR;
2222 #endif
2223     req->stepSize = &obj->stepSize;
2224     req->numberOfTermsRequested = &obj->numberOfTermsRequested;
2225     req->preferredPositionInResponse = &obj->preferredPositionInResponse;
2226     logf (LOG_DEBUG, "stepSize=%d", *req->stepSize);
2227     logf (LOG_DEBUG, "numberOfTermsRequested=%d",
2228           *req->numberOfTermsRequested);
2229     logf (LOG_DEBUG, "preferredPositionInResponse=%d",
2230           *req->preferredPositionInResponse);
2231
2232     if (!z_APDU (p->odr_out, &apdu, 0))
2233     {
2234         interp->result = odr_errlist [odr_geterror (p->odr_out)];
2235         odr_reset (p->odr_out);
2236         return TCL_ERROR;
2237     } 
2238     p->sbuf = odr_getbuf (p->odr_out, &p->slen, NULL);
2239     if ((r=cs_put (p->cs_link, p->sbuf, p->slen)) < 0)
2240     {
2241         interp->result = "cs_put failed in scan";
2242         return TCL_ERROR;
2243     }
2244     else if (r == 1)
2245     {
2246         ir_select_add_write (cs_fileno(p->cs_link), p);
2247         logf (LOG_DEBUG, "Sent part of scanRequest (%d bytes)", p->slen);
2248     }
2249     else
2250     {
2251         logf (LOG_DEBUG, "Whole scan request (%d bytes)", p->slen);
2252     }
2253     return TCL_OK;
2254 }
2255
2256 /*
2257  * do_stepSize: Set/get replace Step Size
2258  */
2259 static int do_stepSize (void *obj, Tcl_Interp *interp,
2260                         int argc, char **argv)
2261 {
2262     IrTcl_ScanObj *p = obj;
2263     if (argc <= 0)
2264     {
2265         p->stepSize = 0;
2266         return TCL_OK;
2267     }
2268     return get_set_int (&p->stepSize, interp, argc, argv);
2269 }
2270
2271 /*
2272  * do_numberOfTermsRequested: Set/get Number of Terms requested
2273  */
2274 static int do_numberOfTermsRequested (void *obj, Tcl_Interp *interp,
2275                                       int argc, char **argv)
2276 {
2277     IrTcl_ScanObj *p = obj;
2278
2279     if (argc <= 0)
2280     {
2281         p->numberOfTermsRequested = 20;
2282         return TCL_OK;
2283     }
2284     return get_set_int (&p->numberOfTermsRequested, interp, argc, argv);
2285 }
2286
2287
2288 /*
2289  * do_preferredPositionInResponse: Set/get preferred Position
2290  */
2291 static int do_preferredPositionInResponse (void *obj, Tcl_Interp *interp,
2292                                            int argc, char **argv)
2293 {
2294     IrTcl_ScanObj *p = obj;
2295
2296     if (argc <= 0)
2297     {
2298         p->preferredPositionInResponse = 1;
2299         return TCL_OK;
2300     }
2301     return get_set_int (&p->preferredPositionInResponse, interp, argc, argv);
2302 }
2303
2304 /*
2305  * do_scanStatus: Get scan status
2306  */
2307 static int do_scanStatus (void *obj, Tcl_Interp *interp,
2308                           int argc, char **argv)
2309 {
2310     IrTcl_ScanObj *p = obj;
2311
2312     if (argc <= 0)
2313         return TCL_OK;
2314     return get_set_int (&p->scanStatus, interp, argc, argv);
2315 }
2316
2317 /*
2318  * do_numberOfEntriesReturned: Get number of Entries returned
2319  */
2320 static int do_numberOfEntriesReturned (void *obj, Tcl_Interp *interp,
2321                                        int argc, char **argv)
2322 {
2323     IrTcl_ScanObj *p = obj;
2324
2325     if (argc <= 0)
2326         return TCL_OK;
2327     return get_set_int (&p->numberOfEntriesReturned, interp, argc, argv);
2328 }
2329
2330 /*
2331  * do_positionOfTerm: Get position of Term
2332  */
2333 static int do_positionOfTerm (void *obj, Tcl_Interp *interp,
2334                               int argc, char **argv)
2335 {
2336     IrTcl_ScanObj *p = obj;
2337
2338     if (argc <= 0)
2339         return TCL_OK;
2340     return get_set_int (&p->positionOfTerm, interp, argc, argv);
2341 }
2342
2343 /*
2344  * do_scanLine: get Scan Line (surrogate or normal) after response
2345  */
2346 static int do_scanLine (void *obj, Tcl_Interp *interp, int argc, char **argv)
2347 {
2348     IrTcl_ScanObj *p = obj;
2349     int i;
2350     char numstr[20];
2351
2352     if (argc == 0)
2353     {
2354         p->entries_flag = 0;
2355         p->entries = NULL;
2356         p->nonSurrogateDiagnosticNum = 0;
2357         p->nonSurrogateDiagnosticList = 0;
2358         return TCL_OK;
2359     }
2360     else if (argc == -1)
2361     {
2362         p->entries_flag = 0;
2363         /* release entries */
2364         p->entries = NULL;
2365
2366         ir_deleteDiags (&p->nonSurrogateDiagnosticList, 
2367                         &p->nonSurrogateDiagnosticNum);
2368         return TCL_OK;
2369     }
2370     if (argc != 3)
2371     {
2372         interp->result = "wrong # args";
2373         return TCL_ERROR;
2374     }
2375     if (Tcl_GetInt (interp, argv[2], &i) == TCL_ERROR)
2376         return TCL_ERROR;
2377     if (!p->entries_flag || p->which != Z_ListEntries_entries || !p->entries
2378         || i >= p->num_entries || i < 0)
2379         return TCL_OK;
2380     switch (p->entries[i].which)
2381     {
2382     case Z_Entry_termInfo:
2383         Tcl_AppendElement (interp, "T");
2384         if (p->entries[i].u.term.buf)
2385             Tcl_AppendElement (interp, p->entries[i].u.term.buf);
2386         else
2387             Tcl_AppendElement (interp, "");
2388         sprintf (numstr, "%d", p->entries[i].u.term.globalOccurrences);
2389         Tcl_AppendElement (interp, numstr);
2390         break;
2391     case Z_Entry_surrogateDiagnostic:
2392         Tcl_AppendElement (interp, "SD");
2393         return ir_diagResult (interp, p->entries[i].u.diag.list,
2394                               p->entries[i].u.diag.num);
2395         break;
2396     }
2397     return TCL_OK;
2398 }
2399
2400 static IrTcl_Method ir_scan_method_tab[] = {
2401     { 0, "scan",                    do_scan },
2402     { 0, "stepSize",                do_stepSize },
2403     { 0, "numberOfTermsRequested",  do_numberOfTermsRequested },
2404     { 0, "preferredPositionInResponse", do_preferredPositionInResponse },
2405     { 0, "scanStatus",              do_scanStatus },
2406     { 0, "numberOfEntriesReturned", do_numberOfEntriesReturned },
2407     { 0, "positionOfTerm",          do_positionOfTerm },
2408     { 0, "scanLine",                do_scanLine },
2409     { 0, NULL, NULL}
2410 };
2411
2412 /* 
2413  * ir_scan_obj_method: IR Scan Object methods
2414  */
2415 static int ir_scan_obj_method (ClientData clientData, Tcl_Interp *interp,
2416                                int argc, char **argv)
2417 {
2418     IrTcl_Methods tabs[2];
2419
2420     if (argc < 2)
2421     {
2422         interp->result = "wrong # args";
2423         return TCL_ERROR;
2424     }
2425     tabs[0].tab = ir_scan_method_tab;
2426     tabs[0].obj = clientData;
2427     tabs[1].tab = NULL;
2428
2429     return ir_method (interp, argc, argv, tabs);
2430 }
2431
2432 /* 
2433  * ir_scan_obj_delete: IR Scan Object disposal
2434  */
2435 static void ir_scan_obj_delete (ClientData clientData)
2436 {
2437     IrTcl_Methods tabs[2];
2438     IrTcl_ScanObj *obj = clientData;
2439
2440     tabs[0].tab = ir_scan_method_tab;
2441     tabs[0].obj = obj;
2442     tabs[1].tab = NULL;
2443
2444     ir_method (NULL, -1, NULL, tabs);
2445     free (obj);
2446 }
2447
2448 /* 
2449  * ir_scan_obj_mk: IR Scan Object creation
2450  */
2451 static int ir_scan_obj_mk (ClientData clientData, Tcl_Interp *interp,
2452                            int argc, char **argv)
2453 {
2454     Tcl_CmdInfo parent_info;
2455     IrTcl_ScanObj *obj;
2456     IrTcl_Methods tabs[2];
2457
2458     if (argc != 3)
2459     {
2460         interp->result = "wrong # args";
2461         return TCL_ERROR;
2462     }
2463     if (!Tcl_GetCommandInfo (interp, argv[2], &parent_info))
2464     {
2465         interp->result = "No parent";
2466         return TCL_ERROR;
2467     }
2468     if (!(obj = ir_malloc (interp, sizeof(*obj))))
2469         return TCL_ERROR;
2470
2471     obj->parent = (IrTcl_Obj *) parent_info.clientData;
2472
2473     tabs[0].tab = ir_scan_method_tab;
2474     tabs[0].obj = obj;
2475     tabs[1].tab = NULL;
2476
2477     if (ir_method (interp, 0, NULL, tabs) == TCL_ERROR)
2478         return TCL_ERROR;
2479     Tcl_CreateCommand (interp, argv[1], ir_scan_obj_method,
2480                        (ClientData) obj, ir_scan_obj_delete);
2481     return TCL_OK;
2482 }
2483
2484 /* ------------------------------------------------------- */
2485
2486 static void ir_initResponse (void *obj, Z_InitResponse *initrs)
2487 {
2488     IrTcl_Obj *p = obj;
2489
2490     p->initResult = *initrs->result ? 1 : 0;
2491     if (!*initrs->result)
2492         logf (LOG_DEBUG, "Connection rejected by target");
2493     else
2494         logf (LOG_DEBUG, "Connection accepted by target");
2495
2496     get_referenceId (&p->set_inher.referenceId, initrs->referenceId);
2497
2498     free (p->targetImplementationId);
2499     ir_strdup (p->interp, &p->targetImplementationId,
2500                initrs->implementationId);
2501     free (p->targetImplementationName);
2502     ir_strdup (p->interp, &p->targetImplementationName,
2503                initrs->implementationName);
2504     free (p->targetImplementationVersion);
2505     ir_strdup (p->interp, &p->targetImplementationVersion,
2506                initrs->implementationVersion);
2507
2508     p->maximumRecordSize = *initrs->maximumRecordSize;
2509     p->preferredMessageSize = *initrs->preferredMessageSize;
2510     
2511     memcpy (&p->options, initrs->options, sizeof(initrs->options));
2512     memcpy (&p->protocolVersion, initrs->protocolVersion,
2513             sizeof(initrs->protocolVersion));
2514     free (p->userInformationField);
2515     p->userInformationField = NULL;
2516     if (initrs->userInformationField)
2517     {
2518         int len;
2519
2520         if (initrs->userInformationField->which == ODR_EXTERNAL_octet && 
2521             (p->userInformationField =
2522              malloc ((len = 
2523                       initrs->userInformationField->u.octet_aligned->len)
2524                      +1)))
2525         {
2526             memcpy (p->userInformationField,
2527                     initrs->userInformationField->u.octet_aligned->buf,
2528                         len);
2529             (p->userInformationField)[len] = '\0';
2530         }
2531     }
2532 }
2533
2534 static void ir_deleteDiags (IrTcl_Diagnostic **dst_list, int *dst_num)
2535 {
2536     int i;
2537     for (i = 0; i<*dst_num; i++)
2538         free (dst_list[i]->addinfo);
2539     free (*dst_list);
2540     *dst_list = NULL;
2541     *dst_num = 0;
2542 }
2543
2544 static void ir_handleDiags (IrTcl_Diagnostic **dst_list, int *dst_num,
2545                     Z_DiagRec **list, int num)
2546 {
2547     int i;
2548     char *addinfo;
2549
2550     *dst_num = num;
2551     *dst_list = malloc (sizeof(**dst_list) * num);
2552     if (!*dst_list) 
2553     {
2554         *dst_num = 0;
2555         return;
2556     }
2557     for (i = 0; i<num; i++)
2558     {
2559         switch (list[i]->which)
2560         {
2561         case Z_DiagRec_defaultFormat:
2562             (*dst_list)[i].condition = *list[i]->u.defaultFormat->condition;
2563             addinfo = list[i]->u.defaultFormat->addinfo;
2564             if (addinfo && 
2565                 ((*dst_list)[i].addinfo = malloc (strlen(addinfo)+1)))
2566                 strcpy ((*dst_list)[i].addinfo, addinfo);
2567             break;
2568         default:
2569             (*dst_list)[i].addinfo = NULL;
2570             (*dst_list)[i].condition = 0;
2571         }
2572     }
2573 }
2574
2575 static void ir_handleRecords (void *o, Z_Records *zrs)
2576 {
2577     IrTcl_Obj *p = o;
2578     IrTcl_SetObj *setobj = p->set_child;
2579
2580     int offset;
2581     IrTcl_RecordList *rl;
2582
2583     setobj->which = zrs->which;
2584     setobj->recordFlag = 1;
2585     
2586     ir_deleteDiags (&setobj->nonSurrogateDiagnosticList,
2587                     &setobj->nonSurrogateDiagnosticNum);
2588     if (zrs->which == Z_Records_DBOSD)
2589     {
2590         setobj->numberOfRecordsReturned = 
2591             zrs->u.databaseOrSurDiagnostics->num_records;
2592         logf (LOG_DEBUG, "Got %d records", setobj->numberOfRecordsReturned);
2593         for (offset = 0; offset<setobj->numberOfRecordsReturned; offset++)
2594         {
2595             rl = new_IR_record (setobj, setobj->start + offset,
2596                                 zrs->u.databaseOrSurDiagnostics->
2597                                 records[offset]->which);
2598             if (rl->which == Z_NamePlusRecord_surrogateDiagnostic)
2599             {
2600                 ir_handleDiags (&rl->u.surrogateDiagnostics.list,
2601                                 &rl->u.surrogateDiagnostics.num,
2602                                 &zrs->u.databaseOrSurDiagnostics->
2603                                 records[offset]->u.surrogateDiagnostic,
2604                                 1);
2605             } 
2606             else
2607             {
2608                 Z_DatabaseRecord *zr; 
2609                 Odr_external *oe;
2610                 
2611                 zr = zrs->u.databaseOrSurDiagnostics->records[offset]
2612                     ->u.databaseRecord;
2613                 oe = (Odr_external*) zr;
2614                 rl->u.dbrec.size = zr->u.octet_aligned->len;
2615                 rl->u.dbrec.type = VAL_USMARC;
2616                 if (oe->which == ODR_EXTERNAL_octet && rl->u.dbrec.size > 0)
2617                 {
2618                     const char *buf = (char*) zr->u.octet_aligned->buf;
2619                     if ((rl->u.dbrec.buf = malloc (rl->u.dbrec.size)))
2620                         memcpy (rl->u.dbrec.buf, buf, rl->u.dbrec.size);
2621                     if (oe->direct_reference)
2622                     {
2623                         struct oident *ident = 
2624                             oid_getentbyoid (oe->direct_reference);
2625                         rl->u.dbrec.type = ident->value;
2626                     }
2627                 }
2628                 else
2629                     rl->u.dbrec.buf = NULL;
2630             }
2631         }
2632     }
2633     else if (zrs->which == Z_Records_multipleNSD)
2634     {
2635         logf (LOG_DEBUG, "multipleNonSurrogateDiagnostic %d",
2636               zrs->u.multipleNonSurDiagnostics->num_diagRecs);
2637         setobj->numberOfRecordsReturned = 0;
2638         ir_handleDiags (&setobj->nonSurrogateDiagnosticList,
2639                         &setobj->nonSurrogateDiagnosticNum,
2640                         zrs->u.multipleNonSurDiagnostics->diagRecs,
2641                         zrs->u.multipleNonSurDiagnostics->num_diagRecs);
2642     }
2643     else
2644     {
2645         logf (LOG_DEBUG, "NonSurrogateDiagnostic");
2646         setobj->numberOfRecordsReturned = 0;
2647         ir_handleDiags (&setobj->nonSurrogateDiagnosticList,
2648                         &setobj->nonSurrogateDiagnosticNum,
2649                         &zrs->u.nonSurrogateDiagnostic,
2650                         1);
2651     }
2652 }
2653
2654 static void ir_searchResponse (void *o, Z_SearchResponse *searchrs)
2655 {    
2656     IrTcl_Obj *p = o;
2657     IrTcl_SetObj *setobj = p->set_child;
2658     Z_Records *zrs = searchrs->records;
2659
2660     logf (LOG_DEBUG, "Received search response");
2661     if (!setobj)
2662     {
2663         logf (LOG_DEBUG, "Search response, no object!");
2664         return;
2665     }
2666     setobj->searchStatus = searchrs->searchStatus ? 1 : 0;
2667     get_referenceId (&setobj->set_inher.referenceId, searchrs->referenceId);
2668     setobj->resultCount = *searchrs->resultCount;
2669     if (searchrs->presentStatus)
2670         setobj->presentStatus = *searchrs->presentStatus;
2671     if (searchrs->nextResultSetPosition)
2672         setobj->nextResultSetPosition = *searchrs->nextResultSetPosition;
2673
2674     logf (LOG_DEBUG, "Search response %d, %d hits", 
2675           setobj->searchStatus, setobj->resultCount);
2676     if (zrs)
2677         ir_handleRecords (o, zrs);
2678     else
2679         setobj->recordFlag = 0;
2680 }
2681
2682
2683 static void ir_presentResponse (void *o, Z_PresentResponse *presrs)
2684 {
2685     IrTcl_Obj *p = o;
2686     IrTcl_SetObj *setobj = p->set_child;
2687     Z_Records *zrs = presrs->records;
2688     
2689     logf (LOG_DEBUG, "Received present response");
2690     if (!setobj)
2691     {
2692         logf (LOG_DEBUG, "Present response, no object!");
2693         return;
2694     }
2695     setobj->presentStatus = *presrs->presentStatus;
2696     get_referenceId (&setobj->set_inher.referenceId, presrs->referenceId);
2697     setobj->nextResultSetPosition = *presrs->nextResultSetPosition;
2698     if (zrs)
2699         ir_handleRecords (o, zrs);
2700     else
2701     {
2702         setobj->recordFlag = 0;
2703         logf (LOG_DEBUG, "No records!");
2704     }
2705 }
2706
2707 static void ir_scanResponse (void *o, Z_ScanResponse *scanrs)
2708 {
2709     IrTcl_Obj *p = o;
2710     IrTcl_ScanObj *scanobj = p->scan_child;
2711     
2712     logf (LOG_DEBUG, "Received scanResponse");
2713
2714     get_referenceId (&p->set_inher.referenceId, scanrs->referenceId);
2715     scanobj->scanStatus = *scanrs->scanStatus;
2716     logf (LOG_DEBUG, "scanStatus=%d", scanobj->scanStatus);
2717
2718     if (scanrs->stepSize)
2719         scanobj->stepSize = *scanrs->stepSize;
2720     logf (LOG_DEBUG, "stepSize=%d", scanobj->stepSize);
2721
2722     scanobj->numberOfEntriesReturned = *scanrs->numberOfEntriesReturned;
2723     logf (LOG_DEBUG, "numberOfEntriesReturned=%d",
2724           scanobj->numberOfEntriesReturned);
2725
2726     if (scanrs->positionOfTerm)
2727         scanobj->positionOfTerm = *scanrs->positionOfTerm;
2728     else
2729         scanobj->positionOfTerm = -1;
2730     logf (LOG_DEBUG, "positionOfTerm=%d", scanobj->positionOfTerm);
2731
2732     free (scanobj->entries);
2733     scanobj->entries = NULL;
2734
2735     ir_deleteDiags (&scanobj->nonSurrogateDiagnosticList,
2736                     &scanobj->nonSurrogateDiagnosticNum);
2737     if (scanrs->entries)
2738     {
2739         int i;
2740         Z_Entry *ze;
2741
2742         scanobj->entries_flag = 1;
2743         scanobj->which = scanrs->entries->which;
2744         switch (scanobj->which)
2745         {
2746         case Z_ListEntries_entries:
2747             scanobj->num_entries = scanrs->entries->u.entries->num_entries;
2748             scanobj->entries = malloc (scanobj->num_entries * 
2749                                        sizeof(*scanobj->entries));
2750             for (i=0; i<scanobj->num_entries; i++)
2751             {
2752                 ze = scanrs->entries->u.entries->entries[i];
2753                 scanobj->entries[i].which = ze->which;
2754                 switch (ze->which)
2755                 {
2756                 case Z_Entry_termInfo:
2757                     if (ze->u.termInfo->term->which == Z_Term_general)
2758                     {
2759                         int l = ze->u.termInfo->term->u.general->len;
2760                         scanobj->entries[i].u.term.buf = malloc (1+l);
2761                         memcpy (scanobj->entries[i].u.term.buf, 
2762                                 ze->u.termInfo->term->u.general->buf,
2763                                 l);
2764                         scanobj->entries[i].u.term.buf[l] = '\0';
2765                     }
2766                     else
2767                         scanobj->entries[i].u.term.buf = NULL;
2768                     if (ze->u.termInfo->globalOccurrences)
2769                         scanobj->entries[i].u.term.globalOccurrences = 
2770                             *ze->u.termInfo->globalOccurrences;
2771                     else
2772                         scanobj->entries[i].u.term.globalOccurrences = 0;
2773                     break;
2774                 case Z_Entry_surrogateDiagnostic:
2775                     ir_handleDiags (&scanobj->entries[i].u.diag.list,
2776                                     &scanobj->entries[i].u.diag.num,
2777                                     &ze->u.surrogateDiagnostic,
2778                                     1);
2779                     break;
2780                 }
2781             }
2782             break;
2783         case Z_ListEntries_nonSurrogateDiagnostics:
2784             ir_handleDiags (&scanobj->nonSurrogateDiagnosticList,
2785                             &scanobj->nonSurrogateDiagnosticNum,
2786                             scanrs->entries->u.nonSurrogateDiagnostics->
2787                             diagRecs,
2788                             scanrs->entries->u.nonSurrogateDiagnostics->
2789                             num_diagRecs);
2790             break;
2791         }
2792     }
2793     else
2794         scanobj->entries_flag = 0;
2795 }
2796
2797 /*
2798  * ir_select_read: handle incoming packages
2799  */
2800 void ir_select_read (ClientData clientData)
2801 {
2802     IrTcl_Obj *p = clientData;
2803     Z_APDU *apdu;
2804     int r;
2805
2806     if (p->connectFlag)
2807     {
2808         r = cs_rcvconnect (p->cs_link);
2809         if (r == 1)
2810         {
2811             logf (LOG_WARN, "cs_rcvconnect returned 1");
2812             return;
2813         }
2814         p->connectFlag = 0;
2815         ir_select_remove_write (cs_fileno (p->cs_link), p);
2816         if (r < 0)
2817         {
2818             logf (LOG_DEBUG, "cs_rcvconnect error");
2819             if (p->failback)
2820                 IrTcl_eval (p->interp, p->failback);
2821             do_disconnect (p, NULL, 2, NULL);
2822             return;
2823         }
2824         if (p->callback)
2825             IrTcl_eval (p->interp, p->callback);
2826         return;
2827     }
2828     do
2829     {
2830         /* signal one more use of ir object - callbacks must not
2831            release the ir memory (p pointer) */
2832         ++(p->ref_count);
2833         if ((r=cs_get (p->cs_link, &p->buf_in, &p->len_in)) <= 0)
2834         {
2835             logf (LOG_DEBUG, "cs_get failed, code %d", r);
2836             ir_select_remove (cs_fileno (p->cs_link), p);
2837             if (p->failback)
2838                 IrTcl_eval (p->interp, p->failback);
2839             do_disconnect (p, NULL, 2, NULL);
2840
2841             /* relase ir object now if callback deleted it */
2842             ir_obj_delete (p);
2843             return;
2844         }        
2845         if (r == 1)
2846             return ;
2847         odr_setbuf (p->odr_in, p->buf_in, r, 0);
2848         logf (LOG_DEBUG, "cs_get ok, got %d", r);
2849         if (!z_APDU (p->odr_in, &apdu, 0))
2850         {
2851             logf (LOG_DEBUG, "%s", odr_errlist [odr_geterror (p->odr_in)]);
2852             if (p->failback)
2853                 IrTcl_eval (p->interp, p->failback);
2854             do_disconnect (p, NULL, 2, NULL);
2855
2856             /* release ir object now if failback deleted it */
2857             ir_obj_delete (p);
2858             return;
2859         }
2860         switch(apdu->which)
2861         {
2862         case Z_APDU_initResponse:
2863             ir_initResponse (p, apdu->u.initResponse);
2864             break;
2865         case Z_APDU_searchResponse:
2866             ir_searchResponse (p, apdu->u.searchResponse);
2867             break;
2868         case Z_APDU_presentResponse:
2869             ir_presentResponse (p, apdu->u.presentResponse);
2870             break;
2871         case Z_APDU_scanResponse:
2872             ir_scanResponse (p, apdu->u.scanResponse);
2873             break;
2874         default:
2875             logf (LOG_WARN, "Received unknown APDU type (%d)", apdu->which);
2876             if (p->failback)
2877                 IrTcl_eval (p->interp, p->failback);
2878             do_disconnect (p, NULL, 2, NULL);
2879         }
2880         odr_reset (p->odr_in);
2881         if (p->callback)
2882             IrTcl_eval (p->interp, p->callback);
2883         if (p->ref_count == 1)
2884         {
2885             ir_obj_delete (p);
2886             return;
2887         }
2888         --(p->ref_count);
2889     } while (p->cs_link && cs_more (p->cs_link));    
2890 }
2891
2892 /*
2893  * ir_select_write: handle outgoing packages - not yet written.
2894  */
2895 void ir_select_write (ClientData clientData)
2896 {
2897     IrTcl_Obj *p = clientData;
2898     int r;
2899
2900     logf (LOG_DEBUG, "In write handler");
2901     if (p->connectFlag)
2902     {
2903         r = cs_rcvconnect (p->cs_link);
2904         if (r == 1)
2905             return;
2906         p->connectFlag = 0;
2907         if (r < 0)
2908         {
2909             logf (LOG_DEBUG, "cs_rcvconnect error");
2910             ir_select_remove_write (cs_fileno (p->cs_link), p);
2911             if (p->failback)
2912                 IrTcl_eval (p->interp, p->failback);
2913             do_disconnect (p, NULL, 2, NULL);
2914             return;
2915         }
2916         ir_select_remove_write (cs_fileno (p->cs_link), p);
2917         if (p->callback)
2918             IrTcl_eval (p->interp, p->callback);
2919         return;
2920     }
2921     if ((r=cs_put (p->cs_link, p->sbuf, p->slen)) < 0)
2922     {   
2923         logf (LOG_DEBUG, "select write fail");
2924         if (p->failback)
2925             IrTcl_eval (p->interp, p->failback);
2926         do_disconnect (p, NULL, 2, NULL);
2927     }
2928     else if (r == 0)            /* remove select bit */
2929     {
2930         ir_select_remove_write (cs_fileno (p->cs_link), p);
2931     }
2932 }
2933
2934 /* ------------------------------------------------------- */
2935
2936 /*
2937  * ir_tcl_init: Registration of TCL commands.
2938  */
2939 int ir_tcl_init (Tcl_Interp *interp)
2940 {
2941     Tcl_CreateCommand (interp, "ir", ir_obj_mk, (ClientData) NULL,
2942                        (Tcl_CmdDeleteProc *) NULL);
2943     Tcl_CreateCommand (interp, "ir-set", ir_set_obj_mk,
2944                        (ClientData) NULL, (Tcl_CmdDeleteProc *) NULL);
2945     Tcl_CreateCommand (interp, "ir-scan", ir_scan_obj_mk,
2946                        (ClientData) NULL, (Tcl_CmdDeleteProc *) NULL);
2947     irTcl_interp = interp;
2948     return TCL_OK;
2949 }
2950
2951