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