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