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