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