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