Simplified select handling. Only one function ir_tcl_select_set has
[ir-tcl-moved-to-github.git] / ir-tcl.c
index bb22467..d87d4d8 100644 (file)
--- a/ir-tcl.c
+++ b/ir-tcl.c
@@ -5,7 +5,173 @@
  * Sebastian Hammer, Adam Dickmeiss
  *
  * $Log: ir-tcl.c,v $
- * Revision 1.34  1995-05-29 10:33:42  adam
+ * Revision 1.78  1996-02-21 10:16:08  adam
+ * Simplified select handling. Only one function ir_tcl_select_set has
+ * to be externally defined.
+ *
+ * Revision 1.77  1996/02/20  17:52:58  adam
+ * Uses the YAZ oid system to name record syntax object identifiers.
+ *
+ * Revision 1.76  1996/02/20  16:09:51  adam
+ * Bug fix: didn't set element set names stamp correctly on result
+ * set records when element set names were set to the empty string.
+ *
+ * Revision 1.75  1996/02/19  15:41:53  adam
+ * Better log messages.
+ * Minor improvement of connect method.
+ *
+ * Revision 1.74  1996/02/05  17:58:03  adam
+ * Ported ir-tcl to use the beta releases of tcl7.5/tk4.1.
+ *
+ * Revision 1.73  1996/01/29  11:35:19  adam
+ * Bug fix: cs_type member renamed to comstackType to avoid conflict with
+ * cs_type macro defined by YAZ.
+ *
+ * Revision 1.72  1996/01/19  17:45:34  quinn
+ * Added debugging output
+ *
+ * Revision 1.71  1996/01/19  16:22:38  adam
+ * New method: apduDump - returns information about last incoming APDU.
+ *
+ * Revision 1.70  1996/01/10  09:18:34  adam
+ * PDU specific callbacks implemented: initRespnse, searchResponse,
+ *  presentResponse and scanResponse.
+ * Bug fix in the command line shell (tclmain.c) - discovered on OSF/1.
+ *
+ * Revision 1.69  1996/01/04  16:12:12  adam
+ * Setting PDUType renamed to eventType.
+ *
+ * Revision 1.68  1996/01/04  11:05:22  adam
+ * New setting: PDUType - returns type of last PDU returned from the target.
+ * Fixed a bug in configure/Makefile.
+ *
+ * Revision 1.67  1996/01/03  09:00:51  adam
+ * Updated to use new version of Yaz (names changed to avoid C++ conflict).
+ *
+ * Revision 1.66  1995/11/28  17:26:39  adam
+ * Removed Carriage return from ir-tcl.c!
+ * Removed misc. debug logs.
+ *
+ * Revision 1.65  1995/11/28  13:53:00  quinn
+ * Windows port.
+ *
+ * Revision 1.64  1995/11/13  15:39:18  adam
+ * Bug fix: {small,medium}SetElementSetNames weren't set correctly.
+ * Bug fix: idAuthentication weren't set correctly.
+ *
+ * Revision 1.63  1995/11/13  09:55:39  adam
+ * Multiple records at a position in a result-set with differnt
+ * element specs.
+ *
+ * Revision 1.62  1995/10/18  17:20:33  adam
+ * Work on target setup in client.tcl.
+ *
+ * Revision 1.61  1995/10/18  16:42:42  adam
+ * New settings: smallSetElementSetNames and mediumSetElementSetNames.
+ *
+ * Revision 1.60  1995/10/18  15:43:31  adam
+ * In search: mediumSetElementSetNames and smallSetElementSetNames are
+ * set to elementSetNames.
+ *
+ * Revision 1.59  1995/10/17  12:18:58  adam
+ * Bug fix: when target connection closed, the connection was not
+ * properly reestablished.
+ *
+ * Revision 1.58  1995/10/16  17:00:55  adam
+ * New setting: elementSetNames.
+ * Various client improvements. Medium presentation format looks better.
+ *
+ * Revision 1.57  1995/09/21  13:11:51  adam
+ * Support of dynamic loading.
+ * Test script uses load command if necessary.
+ *
+ * Revision 1.56  1995/08/29  15:30:14  adam
+ * Work on GRS records.
+ *
+ * Revision 1.55  1995/08/28  09:43:25  adam
+ * Minor changes. configure only searches for yaz beta 3 and versions after
+ * that.
+ *
+ * Revision 1.54  1995/08/24  12:25:16  adam
+ * Modified to work with yaz 1.0b3.
+ *
+ * Revision 1.53  1995/08/04  12:49:26  adam
+ * Bug fix: reading uninitialized variable p.
+ *
+ * Revision 1.52  1995/08/04  11:32:38  adam
+ * More work on output queue. Memory related routines moved
+ * to mem.c
+ *
+ * Revision 1.51  1995/08/03  13:22:54  adam
+ * Request queue.
+ *
+ * Revision 1.50  1995/07/20  08:09:49  adam
+ * client.tcl: Targets removed from hotTargets list when targets
+ *  are removed/modified.
+ * ir-tcl.c: More work on triggerResourceControl.
+ *
+ * Revision 1.49  1995/06/30  12:39:21  adam
+ * Bug fix: loadFile didn't set record type.
+ * The MARC routines are a little less strict in the interpretation.
+ * Script display.tcl replaces the old marc.tcl.
+ * New interactive script: shell.tcl.
+ *
+ * Revision 1.48  1995/06/27  19:03:50  adam
+ * Bug fix in do_present in ir-tcl.c: p->set_child member weren't set.
+ * nextResultSetPosition used instead of setOffset.
+ *
+ * Revision 1.47  1995/06/25  10:25:04  adam
+ * Working on triggerResourceControl. Description of compile/install
+ * procedure moved to ir-tcl.sgml.
+ *
+ * Revision 1.46  1995/06/22  13:15:06  adam
+ * Feature: SUTRS. Setting getSutrs implemented.
+ * Work on display formats.
+ * Preferred record syntax can be set by the user.
+ *
+ * Revision 1.45  1995/06/20  08:07:30  adam
+ * New setting: failInfo.
+ * Working on better cancel mechanism.
+ *
+ * Revision 1.44  1995/06/19  17:01:20  adam
+ * Minor changes.
+ *
+ * Revision 1.43  1995/06/19  13:06:08  adam
+ * New define: IR_TCL_VERSION.
+ *
+ * Revision 1.42  1995/06/19  08:08:52  adam
+ * client.tcl: hotTargets now contain both database and target name.
+ * ir-tcl.c: setting protocol edited. Errors in callbacks are logged
+ * by logf(LOG_WARN, ...) calls.
+ *
+ * Revision 1.41  1995/06/16  12:28:16  adam
+ * Implemented preferredRecordSyntax.
+ * Minor changes in diagnostic handling.
+ * Record list deleted when connection closes.
+ *
+ * Revision 1.40  1995/06/14  13:37:18  adam
+ * Setting recordType implemented.
+ * Setting implementationVersion implemented.
+ * Settings implementationId / implementationName edited.
+ *
+ * Revision 1.39  1995/06/08  10:26:32  adam
+ * Bug fix in ir_strdup.
+ *
+ * Revision 1.38  1995/06/01  16:36:47  adam
+ * About buttons. Minor bug fixes.
+ *
+ * Revision 1.37  1995/06/01  07:31:20  adam
+ * Rename of many typedefs -> IrTcl_...
+ *
+ * Revision 1.36  1995/05/31  13:09:59  adam
+ * Client searches/presents may be interrupted.
+ * New moving book-logo.
+ *
+ * Revision 1.35  1995/05/31  08:36:33  adam
+ * Bug fix in client.tcl: didn't save options on clientrc.tcl.
+ * New method: referenceId. More work on scan.
+ *
+ * Revision 1.34  1995/05/29  10:33:42  adam
  * README and rename of startup script.
  *
  * Revision 1.33  1995/05/29  09:15:11  quinn
  *
  * Revision 1.8  1995/03/15  08:25:16  adam
  * New method presentStatus to check for error on present. Misc. cleanup
- * of IRRecordList manipulations. Full MARC record presentation in
+ * of IrTcl_RecordList manipulations. Full MARC record presentation in
  * search.tcl.
  *
  * Revision 1.7  1995/03/14  17:32:29  adam
 
 #include <stdlib.h>
 #include <stdio.h>
-#include <sys/time.h>
+#include <unistd.h>
+#include <time.h>
 #include <assert.h>
 
 #define CS_BLOCK 0
 
+#define IRTCL_GENERIC_FILES 0
+
 #include "ir-tclp.h"
 
 typedef struct {
     int type;
     char *name;
     int (*method) (void *obj, Tcl_Interp *interp, int argc, char **argv);
-} IRMethod;
+} IrTcl_Method;
 
 typedef struct {
     void *obj;
-    IRMethod *tab;
-} IRMethods;
+    IrTcl_Method *tab;
+} IrTcl_Methods;
+
+static void ir_deleteDiags (IrTcl_Diagnostic **dst_list, int *dst_num);
+static int do_disconnect (void *obj, Tcl_Interp *interp, 
+                          int argc, char **argv);
+
+static void ir_select_notify (ClientData clientData, int r, int w, int e);
 
-static int do_disconnect (void *obj,Tcl_Interp *interp, int argc, char **argv);
+void ir_select_add (int fd, void *obj)
+{
+    ir_tcl_select_set (ir_select_notify, fd, obj, 1, 0, 0);
+}
+
+void ir_select_add_write (int fd, void *obj)
+{
+    ir_tcl_select_set (ir_select_notify, fd, obj, 1, 1, 0);
+}
+
+void ir_select_remove (int fd, void *obj)
+{
+    ir_tcl_select_set (NULL, fd, obj, 0, 0, 0);
+}
 
-static IRRecordList *new_IR_record (IRSetObj *setobj, int no, int which)
+void ir_select_remove_write (int fd, void *obj)
 {
-    IRRecordList *rl;
+    ir_tcl_select_set (ir_select_notify, fd, obj, 1, 0, 0);
+}
+
+static IrTcl_RecordList *new_IR_record (IrTcl_SetObj *setobj, 
+                                        int no, int which, 
+                                        const char *elements)
+{
+    IrTcl_RecordList *rl;
 
+    if (elements && !*elements)
+        elements = NULL;
     for (rl = setobj->record_list; rl; rl = rl->next)
     {
-        if (no == rl->no)
+        if (no == rl->no && (!rl->elements || !elements ||
+                             !strcmp(elements, rl->elements)))
         {
+            free (rl->elements);
             switch (rl->which)
             {
             case Z_NamePlusRecord_databaseRecord:
-               free (rl->u.dbrec.buf);
-               rl->u.dbrec.buf = NULL;
+                free (rl->u.dbrec.buf);
+                rl->u.dbrec.buf = NULL;
                 break;
             case Z_NamePlusRecord_surrogateDiagnostic:
-                free (rl->u.diag.addinfo);
-                rl->u.diag.addinfo = NULL;
+                ir_deleteDiags (&rl->u.surrogateDiagnostics.list,
+                                &rl->u.surrogateDiagnostics.num);
                 break;
             }
             break;
@@ -157,49 +356,98 @@ static IRRecordList *new_IR_record (IRSetObj *setobj, int no, int which)
     }
     if (!rl)
     {
-        rl = malloc (sizeof(*rl));
-        assert (rl);
+        rl = ir_tcl_malloc (sizeof(*rl));
         rl->next = setobj->record_list;
         rl->no = no;
         setobj->record_list = rl;
     }
     rl->which = which;
+    ir_tcl_strdup (NULL, &rl->elements, elements);
     return rl;
 }
 
-static IRRecordList *find_IR_record (IRSetObj *setobj, int no)
+/* 
+ * IrTcl_eval
+ */
+int IrTcl_eval (Tcl_Interp *interp, const char *command)
+{
+    char *tmp = ir_tcl_malloc (strlen(command)+1);
+    int r;
+
+    strcpy (tmp, command);
+    r = Tcl_Eval (interp, tmp);
+    if (r == TCL_ERROR)
+        logf (LOG_WARN, "Tcl error in line %d: %s", interp->errorLine, 
+              interp->result);
+    Tcl_FreeResult (interp);
+    free (tmp);
+    return r;
+}
+
+/*
+ * IrTcl_getRecordSyntaxStr: Return record syntax name of object id
+ */
+static char *IrTcl_getRecordSyntaxStr (enum oid_value value)
+{
+    int *o;
+    struct oident ent, *entp;
+
+    ent.proto = PROTO_Z3950;
+    ent.oclass = CLASS_RECSYN;
+    ent.value = value;
+
+    o = oid_getoidbyent (&ent);
+    entp = oid_getentbyoid (o);
+    
+    if (!entp)
+        return "";
+    return entp->desc;
+}
+
+/*
+ * IrTcl_getRecordSyntaxVal: Return record syntax value of string
+ */
+static enum oid_value IrTcl_getRecordSyntaxVal (const char *name)
+{
+    return oid_getvalbyname (name);
+}
+
+static IrTcl_RecordList *find_IR_record (IrTcl_SetObj *setobj, int no)
 {
-    IRRecordList *rl;
+    IrTcl_RecordList *rl;
 
     for (rl = setobj->record_list; rl; rl = rl->next)
-        if (no == rl->no)
+        if (no == rl->no && 
+            (!setobj->recordElements || !rl->elements || 
+             !strcmp (setobj->recordElements, rl->elements)))
             return rl;
     return NULL;
 }
 
-static void delete_IR_records (IRSetObj *setobj)
+static void delete_IR_records (IrTcl_SetObj *setobj)
 {
-    IRRecordList *rl, *rl1;
+    IrTcl_RecordList *rl, *rl1;
 
     for (rl = setobj->record_list; rl; rl = rl1)
     {
         switch (rl->which)
         {
         case Z_NamePlusRecord_databaseRecord:
-           free (rl->u.dbrec.buf);
+            free (rl->u.dbrec.buf);
             break;
         case Z_NamePlusRecord_surrogateDiagnostic:
-            free (rl->u.diag.addinfo);
+            ir_deleteDiags (&rl->u.surrogateDiagnostics.list,
+                            &rl->u.surrogateDiagnostics.num);
             break;
-       }
-       rl1 = rl->next;
-       free (rl);
+        }
+        rl1 = rl->next;
+        free (rl);
     }
     setobj->record_list = NULL;
 }
 
 /*
- * getsetint: Set/get integer value
+ * get_set_int: Set/get integer value
  */
 static int get_set_int (int *val, Tcl_Interp *interp, int argc, char **argv)
 {
@@ -216,83 +464,28 @@ static int get_set_int (int *val, Tcl_Interp *interp, int argc, char **argv)
 }
 
 /*
- * mk_nonSurrogateDiagnostics: Make Tcl result with diagnostic info
- */
-static int mk_nonSurrogateDiagnostics (Tcl_Interp *interp, 
-                                       int condition,
-                                      const char *addinfo)
-{
-    char buf[20];
-    const char *cp;
-
-    Tcl_AppendElement (interp, "NSD");
-    sprintf (buf, "%d", condition);
-    Tcl_AppendElement (interp, buf);
-    cp = diagbib1_str (condition);
-    if (cp)
-        Tcl_AppendElement (interp, (char*) cp);
-    else
-        Tcl_AppendElement (interp, "");
-    if (addinfo)
-        Tcl_AppendElement (interp, (char*) addinfo);
-    else
-        Tcl_AppendElement (interp, "");
-    return TCL_OK;
-}
-
-/*
- * get_parent_info: Returns information about parent object.
- */
-static int get_parent_info (Tcl_Interp *interp, const char *name,
-                           Tcl_CmdInfo *parent_info,
-                           const char **suffix)
-{
-    char parent_name[128];
-    const char *csep = strrchr (name, '.');
-    int pos;
-
-    if (!csep)
-    {
-        interp->result = "missing .";
-        return TCL_ERROR;
-    }
-    if (suffix)
-        *suffix = csep+1;
-    pos = csep-name;
-    if (pos > 127)
-        pos = 127;
-    memcpy (parent_name, name, pos);
-    parent_name[pos] = '\0';
-    if (!Tcl_GetCommandInfo (interp, parent_name, parent_info))
-    {
-        interp->result = "No parent";
-        return TCL_ERROR;
-    }
-    return TCL_OK;
-}
-
-/*
  * ir_method: Search for method in table and invoke method handler
  */
-int ir_method (Tcl_Interp *interp, int argc, char **argv, IRMethods *tab)
+int ir_method (Tcl_Interp *interp, int argc, char **argv, IrTcl_Methods *tab)
 {
-    IRMethods *tab_i = tab;
-    IRMethod *t;
+    IrTcl_Methods *tab_i = tab;
+    IrTcl_Method *t;
 
     for (tab_i = tab; tab_i->tab; tab_i++)
         for (t = tab_i->tab; t->name; t++)
-           if (argc <= 0)
-           {
-               if ((*t->method)(tab_i->obj, interp, argc, argv) == TCL_ERROR)
-                   return TCL_ERROR;
+            if (argc <= 0)
+            {
+                if ((*t->method)(tab_i->obj, interp, argc, argv) == TCL_ERROR)
+                    return TCL_ERROR;
             }
-           else
+            else
                 if (!strcmp (t->name, argv[1]))
                     return (*t->method)(tab_i->obj, interp, argc, argv);
 
     if (argc <= 0)
         return TCL_OK;
-    Tcl_AppendResult (interp, "Bad method. Possible methods:", NULL);
+    Tcl_AppendResult (interp, "Bad method: ", argv[1], 
+                      ". Possible methods:", NULL);
     for (tab_i = tab; tab_i->tab; tab_i++)
         for (t = tab_i->tab; t->name; t++)
             Tcl_AppendResult (interp, " ", t->name, NULL);
@@ -303,7 +496,7 @@ int ir_method (Tcl_Interp *interp, int argc, char **argv, IRMethods *tab)
  * ir_method_r: Get status for all readable elements
  */
 int ir_method_r (void *obj, Tcl_Interp *interp, int argc, char **argv,
-                 IRMethod *tab)
+                 IrTcl_Method *tab)
 {
     char *argv_n[3];
     int argc_n;
@@ -354,46 +547,30 @@ int ir_named_bits (struct ir_named_entry *tab, Odr_bitmask *ob,
     return TCL_OK;
 }
 
-/*
- * ir_strdup: Duplicate string
- */
-int ir_strdup (Tcl_Interp *interp, char** p, const char *s)
+static void set_referenceId (ODR o, Z_ReferenceId **dst, const char *src)
 {
-    *p = malloc (strlen(s)+1);
-    if (!*p)
+    if (!src || !*src)
+        *dst = NULL;
+    else
     {
-        interp->result = "strdup fail";
-        return TCL_ERROR;
+        *dst = odr_malloc (o, sizeof(**dst));
+        (*dst)->size = (*dst)->len = strlen(src);
+        (*dst)->buf = odr_malloc (o, (*dst)->len);
+        memcpy ((*dst)->buf, src, (*dst)->len);
     }
-    strcpy (*p, s);
-    return TCL_OK;
-}
-
-/*
- * ir_strdel: Delete string
- */
-int ir_strdel (Tcl_Interp *interp, char **p)
-{
-    free (*p);
-    *p = NULL;
-    return TCL_OK;
 }
 
-/*
- * ir_malloc: Malloc function
- */
-void *ir_malloc (Tcl_Interp *interp, size_t size)
+static void get_referenceId (char **dst, Z_ReferenceId *src)
 {
-    static char buf[128];
-    void *p = malloc (size);
-
-    if (!p)
+    free (*dst);
+    if (!src)
     {
-        sprintf (buf, "Malloc fail. %ld bytes requested", (long) size);
-        interp->result = buf;
-        return NULL;
+        *dst = NULL;
+        return;
     }
-    return p;
+    *dst = ir_tcl_malloc (src->len+1);
+    memcpy (*dst, src->buf, src->len);
+    (*dst)[src->len] = '\0';
 }
 
 /* ------------------------------------------------------- */
@@ -402,33 +579,35 @@ void *ir_malloc (Tcl_Interp *interp, size_t size)
  * do_init_request: init method on IR object
  */
 static int do_init_request (void *obj, Tcl_Interp *interp,
-                      int argc, char **argv)
+                            int argc, char **argv)
 {
-    Z_APDU apdu, *apdup = &apdu;
-    IRObj *p = obj;
-    Z_InitRequest req;
-    int r;
+    Z_APDU *apdu;
+    IrTcl_Obj *p = obj;
+    Z_InitRequest *req;
 
     if (argc <= 0)
         return TCL_OK;
     if (!p->cs_link)
     {
-        interp->result = "not connected";
+        interp->result = "init: not connected";
         return TCL_ERROR;
     }
-    odr_reset (p->odr_out);
+    apdu = zget_APDU (p->odr_out, Z_APDU_initRequest);
+    req = apdu->u.initRequest;
 
-    req.referenceId = 0;
-    req.options = &p->options;
-    req.protocolVersion = &p->protocolVersion;
-    req.preferredMessageSize = &p->preferredMessageSize;
-    req.maximumRecordSize = &p->maximumRecordSize;
+    set_referenceId (p->odr_out, &req->referenceId, p->set_inher.referenceId);
+    req->options = &p->options;
+    req->protocolVersion = &p->protocolVersion;
+    req->preferredMessageSize = &p->preferredMessageSize;
+    req->maximumRecordSize = &p->maximumRecordSize;
 
     if (p->idAuthenticationGroupId)
     {
         Z_IdPass *pass = odr_malloc (p->odr_out, sizeof(*pass));
         Z_IdAuthentication *auth = odr_malloc (p->odr_out, sizeof(*auth));
 
+        logf (LOG_DEBUG, "using pass authentication");
+
         auth->which = Z_IdAuthentication_idPass;
         auth->u.idPass = pass;
         if (p->idAuthenticationGroupId && *p->idAuthenticationGroupId)
@@ -443,48 +622,25 @@ static int do_init_request (void *obj, Tcl_Interp *interp,
             pass->password = p->idAuthenticationPassword;
         else
             pass->password = NULL;
-        req.idAuthentication = auth;
+        req->idAuthentication = auth;
     }
     else if (!p->idAuthenticationOpen || !*p->idAuthenticationOpen)
-        req.idAuthentication = NULL;
+        req->idAuthentication = NULL;
     else
     {
         Z_IdAuthentication *auth = odr_malloc (p->odr_out, sizeof(*auth));
 
+        logf (LOG_DEBUG, "using open authentication");
         auth->which = Z_IdAuthentication_open;
         auth->u.open = p->idAuthenticationOpen;
-        req.idAuthentication = auth;
+        req->idAuthentication = auth;
     }
-    req.implementationId = p->implementationId;
-    req.implementationName = p->implementationName;
-    req.implementationVersion = "0.1";
-    req.userInformationField = 0;
+    req->implementationId = p->implementationId;
+    req->implementationName = p->implementationName;
+    req->implementationVersion = p->implementationVersion;
+    req->userInformationField = 0;
 
-    apdu.u.initRequest = &req;
-    apdu.which = Z_APDU_initRequest;
-
-    if (!z_APDU (p->odr_out, &apdup, 0))
-    {
-        Tcl_AppendResult (interp, odr_errlist [odr_geterror (p->odr_out)],
-                          NULL);
-        odr_reset (p->odr_out);
-        return TCL_ERROR;
-    }
-    p->sbuf = odr_getbuf (p->odr_out, &p->slen, NULL);
-    if ((r=cs_put (p->cs_link, p->sbuf, p->slen)) < 0)
-    {     
-        interp->result = "cs_put failed in init";
-        do_disconnect (p, NULL, 2, NULL);
-        return TCL_ERROR;
-    }
-    else if (r == 1)
-    {
-        ir_select_add_write (cs_fileno(p->cs_link), p);
-        logf (LOG_DEBUG, "Sent part of initializeRequest (%d bytes)", p->slen);
-    }
-    else
-        logf (LOG_DEBUG, "Sent whole initializeRequest (%d bytes)", p->slen);
-    return TCL_OK;
+    return ir_tcl_send_APDU (interp, p, apdu, "init", *argv);
 }
 
 /*
@@ -493,24 +649,31 @@ static int do_init_request (void *obj, Tcl_Interp *interp,
 static int do_protocolVersion (void *obj, Tcl_Interp *interp,
                                int argc, char **argv)
 {
-    static struct ir_named_entry version_tab[] = {
-    { "1", 0 },
-    { "2", 1 },
-    { "3", 2 },
-    { "4", 3 },
-    { NULL,0}
-    };
-    IRObj *p = obj;
+    int version, i;
+    char buf[10];
+    IrTcl_Obj *p = obj;
 
     if (argc <= 0)
     {
         ODR_MASK_ZERO (&p->protocolVersion);
-       ODR_MASK_SET (&p->protocolVersion, 0);
-       ODR_MASK_SET (&p->protocolVersion, 1);
+        ODR_MASK_SET (&p->protocolVersion, 0);
+        ODR_MASK_SET (&p->protocolVersion, 1);
         return TCL_OK;
     }
-    return ir_named_bits (version_tab, &p->protocolVersion,
-                          interp, argc-2, argv+2);
+    if (argc == 3)
+    {
+        if (Tcl_GetInt (interp, argv[2], &version)==TCL_ERROR)
+            return TCL_ERROR;
+        ODR_MASK_ZERO (&p->protocolVersion);
+        for (i = 0; i<version; i++)
+            ODR_MASK_SET (&p->protocolVersion, i);
+    }
+    for (i = 4; --i >= 0; )
+        if (ODR_MASK_GET (&p->protocolVersion, i))
+            break;
+    sprintf (buf, "%d", i+1);
+    interp->result = buf;
+    return TCL_OK;
 }
 
 /*
@@ -529,39 +692,130 @@ static int do_options (void *obj, Tcl_Interp *interp,
     { "accessCtrl", 6},
     { "scan", 7},
     { "sort", 8},
-    { "extentedServices", 10},
+    { "extendedServices", 10},
     { "level-1Segmentation", 11},
     { "level-2Segmentation", 12},
     { "concurrentOperations", 13},
     { "namedResultSets", 14},
     { NULL, 0}
     };
-    IRObj *p = obj;
+    IrTcl_Obj *p = obj;
 
     if (argc <= 0)
     {
         ODR_MASK_ZERO (&p->options);
-       ODR_MASK_SET (&p->options, 0);
-       ODR_MASK_SET (&p->options, 1);
-       ODR_MASK_SET (&p->options, 7);
-       ODR_MASK_SET (&p->options, 14);
-       return TCL_OK;
+        ODR_MASK_SET (&p->options, 0);
+        ODR_MASK_SET (&p->options, 1);
+        ODR_MASK_SET (&p->options, 4);
+        ODR_MASK_SET (&p->options, 7);
+        ODR_MASK_SET (&p->options, 14);
+        return TCL_OK;
     }
     return ir_named_bits (options_tab, &p->options, interp, argc-2, argv+2);
 }
 
 /*
+ * do_apduInfo: Get APDU information
+ */
+static int do_apduInfo (void *obj, Tcl_Interp *interp, int argc, char **argv)
+{
+    char buf[16];
+    FILE *apduf;
+    IrTcl_Obj *p = obj;
+
+    if (argc <= 0)
+        return TCL_OK;
+    sprintf (buf, "%d", p->apduLen);
+    Tcl_AppendElement (interp, buf);
+    sprintf (buf, "%d", p->apduOffset);
+    Tcl_AppendElement (interp, buf);
+    if (!p->buf_in)
+    {
+        Tcl_AppendElement (interp, "");
+        return TCL_OK;
+    }
+    apduf = fopen ("apdu.tmp", "w");
+    if (!apduf)
+    {
+        Tcl_AppendElement (interp, "");
+        return TCL_OK;
+    }
+    odr_dumpBER (apduf, p->buf_in, p->apduLen);
+    fclose (apduf);
+    if (!(apduf = fopen ("apdu.tmp", "r")))
+        Tcl_AppendElement (interp, "");
+    else
+    {
+        int c;
+        
+        Tcl_AppendResult (interp, " {", NULL);
+        while ((c = getc (apduf)) != EOF)
+        {
+            buf[0] = c;
+            buf[1] = '\0';
+            Tcl_AppendResult (interp, buf, NULL);
+        }
+        fclose (apduf);
+        Tcl_AppendResult (interp, "}", NULL);
+    }
+    unlink ("apdu.tmp");
+    return TCL_OK;
+}
+
+/*
+ * do_failInfo: Get fail information
+ */
+static int do_failInfo (void *obj, Tcl_Interp *interp, int argc, char **argv)
+{
+    char buf[16], *cp;
+    IrTcl_Obj *p = obj;
+
+    if (argc <= 0)
+    {
+        p->failInfo = 0;
+        return TCL_OK;
+    }
+    sprintf (buf, "%d", p->failInfo);
+    switch (p->failInfo)
+    {
+    case 0:
+        cp = "ok";
+        break;
+    case IR_TCL_FAIL_CONNECT:
+        cp = "connect failed";
+        break;
+    case IR_TCL_FAIL_READ:
+        cp = "connection closed";
+        break;
+    case IR_TCL_FAIL_WRITE:
+        cp = "connection closed";
+        break;
+    case IR_TCL_FAIL_IN_APDU:
+        cp = "failed to decode incoming APDU";
+        break;
+    case IR_TCL_FAIL_UNKNOWN_APDU:
+        cp = "unknown APDU";
+        break;
+    default:
+        cp = "";
+    } 
+    Tcl_AppendElement (interp, buf);
+    Tcl_AppendElement (interp, cp);
+    return TCL_OK;
+}
+
+/*
  * do_preferredMessageSize: Set/get preferred message size
  */
 static int do_preferredMessageSize (void *obj, Tcl_Interp *interp,
                                     int argc, char **argv)
 {
-    IRObj *p = obj;
+    IrTcl_Obj *p = obj;
 
     if (argc <= 0)
     {
-        p->preferredMessageSize = 4096;
-       return TCL_OK;
+        p->preferredMessageSize = 30000;
+        return TCL_OK;
     }
     return get_set_int (&p->preferredMessageSize, interp, argc, argv);
 }
@@ -570,14 +824,14 @@ static int do_preferredMessageSize (void *obj, Tcl_Interp *interp,
  * do_maximumRecordSize: Set/get maximum record size
  */
 static int do_maximumRecordSize (void *obj, Tcl_Interp *interp,
-                                    int argc, char **argv)
+                                 int argc, char **argv)
 {
-    IRObj *p = obj;
+    IrTcl_Obj *p = obj;
 
     if (argc <= 0)
     {
-        p->maximumRecordSize = 32768;
-       return TCL_OK;
+        p->maximumRecordSize = 30000;
+        return TCL_OK;
     }
     return get_set_int (&p->maximumRecordSize, interp, argc, argv);
 }
@@ -588,7 +842,7 @@ static int do_maximumRecordSize (void *obj, Tcl_Interp *interp,
 static int do_initResult (void *obj, Tcl_Interp *interp,
                           int argc, char **argv)
 {
-    IRObj *p = obj;
+    IrTcl_Obj *p = obj;
    
     if (argc <= 0)
         return TCL_OK;
@@ -602,63 +856,73 @@ static int do_initResult (void *obj, Tcl_Interp *interp,
 static int do_implementationName (void *obj, Tcl_Interp *interp,
                                     int argc, char **argv)
 {
-    IRObj *p = obj;
+    IrTcl_Obj *p = obj;
 
     if (argc == 0)
-        return ir_strdup (interp, &p->implementationName, "TCL/TK on YAZ");
+        return ir_tcl_strdup (interp, &p->implementationName,
+                          "Index Data/IrTcl on YAZ");
     else if (argc == -1)
-        return ir_strdel (interp, &p->implementationName);
+        return ir_tcl_strdel (interp, &p->implementationName);
     if (argc == 3)
     {
         free (p->implementationName);
-        if (ir_strdup (interp, &p->implementationName, argv[2])
+        if (ir_tcl_strdup (interp, &p->implementationName, argv[2])
             == TCL_ERROR)
             return TCL_ERROR;
     }
-    Tcl_AppendResult (interp, p->implementationName,
-                      (char*) NULL);
+    Tcl_AppendResult (interp, p->implementationName, (char*) NULL);
     return TCL_OK;
 }
 
 /*
- * do_implementationId: Set/get Implementation Id.
+ * do_implementationId: Get Implementation Id.
  */
 static int do_implementationId (void *obj, Tcl_Interp *interp,
                                 int argc, char **argv)
 {
-    IRObj *p = obj;
+    IrTcl_Obj *p = obj;
 
     if (argc == 0)
-        return ir_strdup (interp, &p->implementationId, "81");
+        return ir_tcl_strdup (interp, &p->implementationId, "YAZ (id=81)");
     else if (argc == -1)
-        return ir_strdel (interp, &p->implementationId);
-    if (argc == 3)
-    {
-        free (p->implementationId);
-        if (ir_strdup (interp, &p->implementationId, argv[2]) == TCL_ERROR)
-            return TCL_ERROR;
-    }
+        return ir_tcl_strdel (interp, &p->implementationId);
     Tcl_AppendResult (interp, p->implementationId, (char*) NULL);
     return TCL_OK;
 }
 
 /*
+ * do_implementationVersion: get Implementation Version.
+ */
+static int do_implementationVersion (void *obj, Tcl_Interp *interp,
+                                     int argc, char **argv)
+{
+    IrTcl_Obj *p = obj;
+
+    if (argc == 0)
+        return ir_tcl_strdup (interp, &p->implementationVersion, 
+                          "YAZ: " YAZ_VERSION " / IrTcl: " IR_TCL_VERSION);
+    else if (argc == -1)
+        return ir_tcl_strdel (interp, &p->implementationVersion);
+    Tcl_AppendResult (interp, p->implementationVersion, (char*) NULL);
+    return TCL_OK;
+}
+
+/*
  * do_targetImplementationName: Get Implementation Name of target.
  */
 static int do_targetImplementationName (void *obj, Tcl_Interp *interp,
-                                    int argc, char **argv)
+                                        int argc, char **argv)
 {
-    IRObj *p = obj;
-
+    IrTcl_Obj *p = obj;
+    
     if (argc == 0)
     {
         p->targetImplementationName = NULL;
-       return TCL_OK;
+        return TCL_OK;
     }
     else if (argc == -1)
-        return ir_strdel (interp, &p->targetImplementationName);
-    Tcl_AppendResult (interp, p->targetImplementationName,
-                      (char*) NULL);
+        return ir_tcl_strdel (interp, &p->targetImplementationName);
+    Tcl_AppendResult (interp, p->targetImplementationName, (char*) NULL);
     return TCL_OK;
 }
 
@@ -668,15 +932,15 @@ static int do_targetImplementationName (void *obj, Tcl_Interp *interp,
 static int do_targetImplementationId (void *obj, Tcl_Interp *interp,
                                       int argc, char **argv)
 {
-    IRObj *p = obj;
+    IrTcl_Obj *p = obj;
 
     if (argc == 0)
     {
         p->targetImplementationId = NULL;
-       return TCL_OK;
+        return TCL_OK;
     }
     else if (argc == -1)
-        return ir_strdel (interp, &p->targetImplementationId);
+        return ir_tcl_strdel (interp, &p->targetImplementationId);
     Tcl_AppendResult (interp, p->targetImplementationId, (char*) NULL);
     return TCL_OK;
 }
@@ -687,15 +951,15 @@ static int do_targetImplementationId (void *obj, Tcl_Interp *interp,
 static int do_targetImplementationVersion (void *obj, Tcl_Interp *interp,
                                            int argc, char **argv)
 {
-    IRObj *p = obj;
+    IrTcl_Obj *p = obj;
 
     if (argc == 0)
     {
         p->targetImplementationVersion = NULL;
-       return TCL_OK;
+        return TCL_OK;
     }
     else if (argc == -1)
-        return ir_strdel (interp, &p->targetImplementationVersion);
+        return ir_tcl_strdel (interp, &p->targetImplementationVersion);
     Tcl_AppendResult (interp, p->targetImplementationVersion, (char*) NULL);
     return TCL_OK;
 }
@@ -706,7 +970,7 @@ static int do_targetImplementationVersion (void *obj, Tcl_Interp *interp,
 static int do_idAuthentication (void *obj, Tcl_Interp *interp,
                                 int argc, char **argv)
 {
-    IRObj *p = obj;
+    IrTcl_Obj *p = obj;
 
     if (argc >= 3 || argc == -1)
     {
@@ -728,19 +992,23 @@ static int do_idAuthentication (void *obj, Tcl_Interp *interp,
     {
         if (argc == 3)
         {
-            if (ir_strdup (interp, &p->idAuthenticationOpen, argv[2])
+            if (argv[2][0] && 
+                ir_tcl_strdup (interp, &p->idAuthenticationOpen, argv[2])
                 == TCL_ERROR)
                 return TCL_ERROR;
         }
         else if (argc == 5)
         {
-            if (ir_strdup (interp, &p->idAuthenticationGroupId, argv[2])
+            if (argv[2][0] && 
+                ir_tcl_strdup (interp, &p->idAuthenticationGroupId, argv[2])
                 == TCL_ERROR)
                 return TCL_ERROR;
-            if (ir_strdup (interp, &p->idAuthenticationUserId, argv[3])
+            if (argv[3][0] && 
+                ir_tcl_strdup (interp, &p->idAuthenticationUserId, argv[3])
                 == TCL_ERROR)
                 return TCL_ERROR;
-            if (ir_strdup (interp, &p->idAuthenticationPassword, argv[4])
+            if (argv[4][0] &&
+                ir_tcl_strdup (interp, &p->idAuthenticationPassword, argv[4])
                 == TCL_ERROR)
                 return TCL_ERROR;
         }
@@ -760,12 +1028,11 @@ static int do_idAuthentication (void *obj, Tcl_Interp *interp,
  * do_connect: connect method on IR object
  */
 static int do_connect (void *obj, Tcl_Interp *interp,
-                      int argc, char **argv)
+                       int argc, char **argv)
 {
     void *addr;
-    IRObj *p = obj;
+    IrTcl_Obj *p = obj;
     int r;
-    int protocol_type = PROTO_Z3950;
 
     if (argc <= 0)
         return TCL_OK;
@@ -776,18 +1043,9 @@ static int do_connect (void *obj, Tcl_Interp *interp,
             interp->result = "already connected";
             return TCL_ERROR;
         }
-        if (!strcmp (p->protocol_type, "Z3950"))
-            protocol_type = PROTO_Z3950;
-        else if (!strcmp (p->protocol_type, "SR"))
-            protocol_type = PROTO_SR;
-        else
-        {
-            interp->result = "bad protocol type";
-            return TCL_ERROR;
-        }
-        if (!strcmp (p->cs_type, "tcpip"))
+        if (!strcmp (p->comstackType, "tcpip"))
         {
-            p->cs_link = cs_create (tcpip_type, CS_BLOCK, protocol_type);
+            p->cs_link = cs_create (tcpip_type, CS_BLOCK, p->protocol_type);
             addr = tcpip_strtoaddr (argv[2]);
             if (!addr)
             {
@@ -796,10 +1054,10 @@ static int do_connect (void *obj, Tcl_Interp *interp,
             }
             logf (LOG_DEBUG, "tcp/ip connect %s", argv[2]);
         }
-#if MOSI
-        else if (!strcmp (p->cs_type, "mosi"))
+        else if (!strcmp (p->comstackType, "mosi"))
         {
-            p->cs_link = cs_create (mosi_type, CS_BLOCK, protocol_type);
+#if MOSI
+            p->cs_link = cs_create (mosi_type, CS_BLOCK, p->protocol_type);
             addr = mosi_strtoaddr (argv[2]);
             if (!addr)
             {
@@ -807,36 +1065,58 @@ static int do_connect (void *obj, Tcl_Interp *interp,
                 return TCL_ERROR;
             }
             logf (LOG_DEBUG, "mosi connect %s", argv[2]);
-        }
+#else
+            interp->result = "MOSI support not there";
+            return TCL_ERROR;
 #endif
+        }
         else 
         {
-            interp->result = "unknown comstack type";
+            Tcl_AppendResult (interp, "Bad comstack type: ", 
+                              p->comstackType, NULL);
             return TCL_ERROR;
         }
-        if (ir_strdup (interp, &p->hostname, argv[2]) == TCL_ERROR)
+        if (ir_tcl_strdup (interp, &p->hostname, argv[2]) == TCL_ERROR)
             return TCL_ERROR;
+#if IRTCL_GENERIC_FILES
+#ifdef WINDOWS
+        p->csFile = Tcl_GetFile (cs_fileno(p->cs_link), TCL_WIN_SOCKET);
+#else
+        p->csFile = Tcl_GetFile (cs_fileno(p->cs_link), TCL_UNIX_FD);
+#endif
+#endif
         if ((r=cs_connect (p->cs_link, addr)) < 0)
         {
-            interp->result = "cs_connect fail";
+            interp->result = "connect fail";
             do_disconnect (p, NULL, 2, NULL);
             return TCL_ERROR;
         }
+       logf(LOG_DEBUG, "cs_connect() returned %d fd=%d", r,
+             cs_fileno(p->cs_link));
+        p->eventType = "connect";
+#if IRTCL_GENERIC_FILES
+        ir_select_add (p->csFile, p);
+#else
         ir_select_add (cs_fileno (p->cs_link), p);
+#endif
         if (r == 1)
         {
+#if IRTCL_GENERIC_FILES
+            ir_select_add_write (p->csFile, p);
+#else
             ir_select_add_write (cs_fileno (p->cs_link), p);
-            p->connectFlag = 1;
+#endif
+            p->state = IR_TCL_R_Connecting;
         }
         else
         {
-            p->connectFlag = 0;
+            p->state = IR_TCL_R_Idle;
             if (p->callback)
-                Tcl_Eval (p->interp, p->callback);
+                IrTcl_eval (p->interp, p->callback);
         }
     }
-    if (p->hostname)
-        Tcl_AppendElement (interp, p->hostname);
+    else
+        Tcl_AppendResult (interp, p->hostname, NULL);
     return TCL_OK;
 }
 
@@ -846,25 +1126,53 @@ static int do_connect (void *obj, Tcl_Interp *interp,
 static int do_disconnect (void *obj, Tcl_Interp *interp,
                           int argc, char **argv)
 {
-    IRObj *p = obj;
+    IrTcl_Obj *p = obj;
 
     if (argc == 0)
     {
-        p->connectFlag = 0;
+        p->state = IR_TCL_R_Idle;
+        p->eventType = NULL;
         p->hostname = NULL;
-       p->cs_link = NULL;
+        p->cs_link = NULL;
+#if IRTCL_GENERIC_FILES
+        p->csFile = 0;
+#endif
         return TCL_OK;
     }
     if (p->hostname)
     {
+       logf(LOG_DEBUG, "Closing connection to %s", p->hostname);
         free (p->hostname);
         p->hostname = NULL;
+#if IRTCL_GENERIC_FILES
+        ir_select_remove_write (p->csFile, p);
+        ir_select_remove (p->csFile, p);
+#else
         ir_select_remove_write (cs_fileno (p->cs_link), p);
         ir_select_remove (cs_fileno (p->cs_link), p);
+#endif
+
+        odr_reset (p->odr_in);
 
         assert (p->cs_link);
         cs_close (p->cs_link);
         p->cs_link = NULL;
+#if IRTCL_GENERIC_FILES
+        Tcl_FreeFile (p->csFile);
+        p->csFile = NULL;
+#endif
+
+        ODR_MASK_ZERO (&p->options);
+        ODR_MASK_SET (&p->options, 0);
+        ODR_MASK_SET (&p->options, 1);
+        ODR_MASK_SET (&p->options, 4);
+        ODR_MASK_SET (&p->options, 7);
+        ODR_MASK_SET (&p->options, 14);
+
+        ODR_MASK_ZERO (&p->protocolVersion);
+        ODR_MASK_SET (&p->protocolVersion, 0);
+        ODR_MASK_SET (&p->protocolVersion, 1);
+        ir_tcl_del_q (p);
     }
     assert (!p->cs_link);
     return TCL_OK;
@@ -874,72 +1182,85 @@ static int do_disconnect (void *obj, Tcl_Interp *interp,
  * do_comstack: Set/get comstack method on IR object
  */
 static int do_comstack (void *o, Tcl_Interp *interp,
-                       int argc, char **argv)
+                        int argc, char **argv)
 {
-    IRObj *obj = o;
+    IrTcl_Obj *obj = o;
 
     if (argc == 0)
-        return ir_strdup (interp, &obj->cs_type, "tcpip");
+        return ir_tcl_strdup (interp, &obj->comstackType, "tcpip");
     else if (argc == -1)
-        return ir_strdel (interp, &obj->cs_type);
+        return ir_tcl_strdel (interp, &obj->comstackType);
     else if (argc == 3)
     {
-        free (obj->cs_type);
-        if (ir_strdup (interp, &obj->cs_type, argv[2]) == TCL_ERROR)
+        free (obj->comstackType);
+        if (ir_tcl_strdup (interp, &obj->comstackType, argv[2]) == TCL_ERROR)
             return TCL_ERROR;
     }
-    Tcl_AppendElement (interp, obj->cs_type);
+    Tcl_AppendElement (interp, obj->comstackType);
     return TCL_OK;
 }
 
 /*
- * do_protocol: Set/get protocol method on IR object
+ * do_logLevel: Set log level
  */
-static int do_protocol (void *o, Tcl_Interp *interp,
-                       int argc, char **argv)
+static int do_logLevel (void *o, Tcl_Interp *interp,
+                        int argc, char **argv)
 {
-    IRObj *obj = o;
-
-    if (argc == 0)
-        return ir_strdup (interp, &obj->protocol_type, "Z3950");
-    else if (argc == -1)
-        return ir_strdel (interp, &obj->protocol_type);
-    else if (argc == 3)
+    if (argc <= 2)
+        return TCL_OK;
+    if (argc == 3)
+        log_init (log_mask_str (argv[2]), "", NULL);
+    else if (argc == 4)
+        log_init (log_mask_str (argv[2]), argv[3], NULL);
+    else if (argc == 5)
+        log_init (log_mask_str (argv[2]), argv[3], argv[4]);
+    return TCL_OK;
+}
+
+
+/*
+ * do_eventType: Return type of last event
+ */
+static int do_eventType (void *obj, Tcl_Interp *interp,
+                         int argc, char **argv)
+{
+    IrTcl_Obj *p = obj;
+
+    if (argc <= 0)
     {
-        free (obj->protocol_type);
-        if (ir_strdup (interp, &obj->protocol_type, argv[2]) == TCL_ERROR)
-            return TCL_ERROR;
+        p->eventType = NULL;
+        return TCL_OK;
     }
-    Tcl_AppendElement (interp, obj->protocol_type);
+    Tcl_AppendElement (interp, p->eventType ? p->eventType : "");
     return TCL_OK;
 }
 
+
 /*
  * do_callback: add callback
  */
 static int do_callback (void *obj, Tcl_Interp *interp,
-                          int argc, char **argv)
+                        int argc, char **argv)
 {
-    IRObj *p = obj;
+    IrTcl_Obj *p = obj;
 
     if (argc == 0)
     {
         p->callback = NULL;
-       return TCL_OK;
+        return TCL_OK;
     }
     else if (argc == -1)
-        return ir_strdel (interp, &p->callback);
+        return ir_tcl_strdel (interp, &p->callback);
     if (argc == 3)
     {
         free (p->callback);
-       if (argv[2][0])
-       {
-            if (ir_strdup (interp, &p->callback, argv[2]) == TCL_ERROR)
+        if (argv[2][0])
+        {
+            if (ir_tcl_strdup (interp, &p->callback, argv[2]) == TCL_ERROR)
                 return TCL_ERROR;
-       }
-       else
-           p->callback = NULL;
-        p->interp = interp;
+        }
+        else
+            p->callback = NULL;
     }
     return TCL_OK;
 }
@@ -950,38 +1271,129 @@ static int do_callback (void *obj, Tcl_Interp *interp,
 static int do_failback (void *obj, Tcl_Interp *interp,
                           int argc, char **argv)
 {
-    IRObj *p = obj;
+    IrTcl_Obj *p = obj;
 
     if (argc == 0)
     {
         p->failback = NULL;
-       return TCL_OK;
+        return TCL_OK;
     }
     else if (argc == -1)
-        return ir_strdel (interp, &p->failback);
+        return ir_tcl_strdel (interp, &p->failback);
     else if (argc == 3)
     {
         free (p->failback);
-       if (argv[2][0])
-       {
-            if (ir_strdup (interp, &p->failback, argv[2]) == TCL_ERROR)
+        if (argv[2][0])
+        {
+            if (ir_tcl_strdup (interp, &p->failback, argv[2]) == TCL_ERROR)
                 return TCL_ERROR;
-       }
-       else
-           p->failback = NULL;
-        p->interp = interp;
+        }
+        else
+            p->failback = NULL;
     }
     return TCL_OK;
 }
 
 /*
+ * do_initResponse: add init response handler
+ */
+static int do_initResponse (void *obj, Tcl_Interp *interp,
+                            int argc, char **argv)
+{
+    IrTcl_Obj *p = obj;
+
+    if (argc == 0)
+    {
+        p->initResponse = NULL;
+        return TCL_OK;
+    }
+    else if (argc == -1)
+        return ir_tcl_strdel (interp, &p->initResponse);
+    if (argc == 3)
+    {
+        free (p->initResponse);
+        if (argv[2][0])
+        {
+            if (ir_tcl_strdup (interp, &p->initResponse, argv[2]) == TCL_ERROR)
+                return TCL_ERROR;
+        }
+        else
+            p->initResponse = NULL;
+    }
+    return TCL_OK;
+}
+/*
+ * do_protocol: Set/get protocol method on IR object
+ */
+static int do_protocol (void *o, Tcl_Interp *interp, int argc, char **argv)
+{
+    IrTcl_Obj *p = o;
+
+    if (argc <= 0)
+    {
+        p->protocol_type = PROTO_Z3950;
+        return TCL_OK;
+    }
+    else if (argc == 3)
+    {
+        if (!strcmp (argv[2], "Z39"))
+            p->protocol_type = PROTO_Z3950;
+        else if (!strcmp (argv[2], "SR"))
+            p->protocol_type = PROTO_SR;
+        else
+        {
+            Tcl_AppendResult (interp, "Bad protocol: ", argv[2], NULL);
+            return TCL_ERROR;
+        }
+        return TCL_OK;
+    }
+    switch (p->protocol_type)
+    {
+    case PROTO_Z3950:
+        Tcl_AppendElement (interp, "Z39");
+        break;
+    case PROTO_SR:
+        Tcl_AppendElement (interp, "SR");
+        break;
+    }
+    return TCL_OK;
+}
+
+/*
+ * do_triggerResourceControl:
+ */
+static int do_triggerResourceControl (void *obj, Tcl_Interp *interp,
+                                      int argc, char **argv)
+{
+    IrTcl_Obj *p = obj;
+    Z_APDU *apdu;
+    Z_TriggerResourceControlRequest *req;
+    bool_t is_false = 0;
+
+    if (argc <= 0)
+        return TCL_OK;
+    if (!p->cs_link)
+    {
+        interp->result = "triggerResourceControl: not connected";
+        return TCL_ERROR;
+    }
+    apdu = zget_APDU (p->odr_out, Z_APDU_triggerResourceControlRequest);
+    req = apdu->u.triggerResourceControlRequest;
+    *req->requestedAction = Z_TriggerResourceCtrl_cancel;
+    req->resultSetWanted = &is_false; 
+    
+    return ir_tcl_send_APDU (interp, p, apdu, "triggerResourceControl",
+                             argv[0]);
+}
+
+/*
  * do_databaseNames: specify database names
  */
 static int do_databaseNames (void *obj, Tcl_Interp *interp,
-                          int argc, char **argv)
+                             int argc, char **argv)
 {
     int i;
-    IRSetCObj *p = obj;
+    IrTcl_SetCObj *p = obj;
 
     if (argc == -1)
     {
@@ -992,8 +1404,8 @@ static int do_databaseNames (void *obj, Tcl_Interp *interp,
     if (argc <= 0)
     {
         p->num_databaseNames = 0;
-       p->databaseNames = NULL;
-       return TCL_OK;
+        p->databaseNames = NULL;
+        return TCL_OK;
     }
     if (argc < 3)
     {
@@ -1008,12 +1420,11 @@ static int do_databaseNames (void *obj, Tcl_Interp *interp,
         free (p->databaseNames);
     }
     p->num_databaseNames = argc - 2;
-    if (!(p->databaseNames = ir_malloc (interp, 
-          sizeof(*p->databaseNames) * p->num_databaseNames)))
-        return TCL_ERROR;
+    p->databaseNames =
+        ir_tcl_malloc (sizeof(*p->databaseNames) * p->num_databaseNames);
     for (i=0; i<p->num_databaseNames; i++)
     {
-        if (ir_strdup (interp, &p->databaseNames[i], argv[2+i]) 
+        if (ir_tcl_strdup (interp, &p->databaseNames[i], argv[2+i]) 
             == TCL_ERROR)
             return TCL_ERROR;
     }
@@ -1026,12 +1437,12 @@ static int do_databaseNames (void *obj, Tcl_Interp *interp,
 static int do_replaceIndicator (void *obj, Tcl_Interp *interp,
                                 int argc, char **argv)
 {
-    IRSetCObj *p = obj;
+    IrTcl_SetCObj *p = obj;
 
     if (argc <= 0)
     {
         p->replaceIndicator = 1;
-       return TCL_OK;
+        return TCL_OK;
     }
     return get_set_int (&p->replaceIndicator, interp, argc, argv);
 }
@@ -1040,18 +1451,18 @@ static int do_replaceIndicator (void *obj, Tcl_Interp *interp,
  * do_queryType: Set/Get query method
  */
 static int do_queryType (void *obj, Tcl_Interp *interp,
-                      int argc, char **argv)
+                       int argc, char **argv)
 {
-    IRSetCObj *p = obj;
+    IrTcl_SetCObj *p = obj;
 
     if (argc == 0)
-        return ir_strdup (interp, &p->queryType, "rpn");
+        return ir_tcl_strdup (interp, &p->queryType, "rpn");
     else if (argc == -1)
-        return ir_strdel (interp, &p->queryType);
+        return ir_tcl_strdel (interp, &p->queryType);
     if (argc == 3)
     {
         free (p->queryType);
-        if (ir_strdup (interp, &p->queryType, argv[2]) == TCL_ERROR)
+        if (ir_tcl_strdup (interp, &p->queryType, argv[2]) == TCL_ERROR)
             return TCL_ERROR;
     }
     Tcl_AppendResult (interp, p->queryType, NULL);
@@ -1064,15 +1475,15 @@ static int do_queryType (void *obj, Tcl_Interp *interp,
 static int do_userInformationField (void *obj, Tcl_Interp *interp,
                                     int argc, char **argv)
 {
-    IRObj *p = obj;
+    IrTcl_Obj *p = obj;
     
     if (argc == 0)
     {
         p->userInformationField = NULL;
-       return TCL_OK;
+        return TCL_OK;
     }
     else if (argc == -1)
-        return ir_strdel (interp, &p->userInformationField);
+        return ir_tcl_strdel (interp, &p->userInformationField);
     Tcl_AppendResult (interp, p->userInformationField, NULL);
     return TCL_OK;
 }
@@ -1081,14 +1492,14 @@ static int do_userInformationField (void *obj, Tcl_Interp *interp,
  * do_smallSetUpperBound: Set/get small set upper bound
  */
 static int do_smallSetUpperBound (void *o, Tcl_Interp *interp,
-                      int argc, char **argv)
+                       int argc, char **argv)
 {
-    IRSetCObj *p = o;
+    IrTcl_SetCObj *p = o;
 
     if (argc <= 0)
     {
         p->smallSetUpperBound = 0;
-       return TCL_OK;
+        return TCL_OK;
     }
     return get_set_int (&p->smallSetUpperBound, interp, argc, argv);
 }
@@ -1099,12 +1510,12 @@ static int do_smallSetUpperBound (void *o, Tcl_Interp *interp,
 static int do_largeSetLowerBound (void *o, Tcl_Interp *interp,
                                   int argc, char **argv)
 {
-    IRSetCObj *p = o;
+    IrTcl_SetCObj *p = o;
 
     if (argc <= 0)
     {
         p->largeSetLowerBound = 2;
-       return TCL_OK;
+        return TCL_OK;
     }
     return get_set_int (&p->largeSetLowerBound, interp, argc, argv);
 }
@@ -1115,28 +1526,170 @@ static int do_largeSetLowerBound (void *o, Tcl_Interp *interp,
 static int do_mediumSetPresentNumber (void *o, Tcl_Interp *interp,
                                       int argc, char **argv)
 {
-    IRSetCObj *p = o;
+    IrTcl_SetCObj *p = o;
    
     if (argc <= 0)
     {
         p->mediumSetPresentNumber = 0;
-       return TCL_OK;
+        return TCL_OK;
     }
     return get_set_int (&p->mediumSetPresentNumber, interp, argc, argv);
 }
 
+/*
+ * do_referenceId: Set/Get referenceId
+ */
+static int do_referenceId (void *obj, Tcl_Interp *interp,
+                           int argc, char **argv)
+{
+    IrTcl_SetCObj *p = obj;
 
-static IRMethod ir_method_tab[] = {
+    if (argc == 0)
+    {
+        p->referenceId = NULL;
+        return TCL_OK;
+    }
+    else if (argc == -1)
+        return ir_tcl_strdel (interp, &p->referenceId);
+    if (argc == 3)
+    {
+        free (p->referenceId);
+        if (ir_tcl_strdup (interp, &p->referenceId, argv[2]) == TCL_ERROR)
+            return TCL_ERROR;
+    }
+    Tcl_AppendResult (interp, p->referenceId, NULL);
+    return TCL_OK;
+}
+
+/*
+ * do_preferredRecordSyntax: Set/get preferred record syntax
+ */
+static int do_preferredRecordSyntax (void *obj, Tcl_Interp *interp,
+                                     int argc, char **argv)
+{
+    IrTcl_SetCObj *p = obj;
+
+    if (argc == 0)
+    {
+        p->preferredRecordSyntax = NULL;
+        return TCL_OK;
+    }
+    else if (argc == -1)
+    {
+        free (p->preferredRecordSyntax);
+        p->preferredRecordSyntax = NULL;
+        return TCL_OK;
+    }
+    if (argc == 3)
+    {
+        free (p->preferredRecordSyntax);
+        p->preferredRecordSyntax = NULL;
+        if (argv[2][0] && (p->preferredRecordSyntax = 
+                           ir_tcl_malloc (sizeof(*p->preferredRecordSyntax))))
+            *p->preferredRecordSyntax = IrTcl_getRecordSyntaxVal (argv[2]);
+    }
+    else if (argc == 2)
+    {
+        Tcl_AppendElement (interp, IrTcl_getRecordSyntaxStr
+                           (*p->preferredRecordSyntax));
+    }
+    return TCL_OK;
+            
+}
+
+/*
+ * do_elementSetNames: Set/Get element Set Names
+ */
+static int do_elementSetNames (void *obj, Tcl_Interp *interp,
+                               int argc, char **argv)
+{
+    IrTcl_SetCObj *p = obj;
+
+    if (argc == 0)
+    {
+        p->elementSetNames = NULL;
+        return TCL_OK;
+    }
+    else if (argc == -1)
+        return ir_tcl_strdel (interp, &p->elementSetNames);
+    if (argc == 3)
+    {
+        free (p->elementSetNames);
+        if (ir_tcl_strdup (interp, &p->elementSetNames, argv[2]) == TCL_ERROR)
+            return TCL_ERROR;
+    }
+    Tcl_AppendResult (interp, p->elementSetNames, NULL);
+    return TCL_OK;
+}
+
+/*
+ * do_smallSetElementSetNames: Set/Get small Set Element Set Names
+ */
+static int do_smallSetElementSetNames (void *obj, Tcl_Interp *interp,
+                               int argc, char **argv)
+{
+    IrTcl_SetCObj *p = obj;
+
+    if (argc == 0)
+    {
+        p->smallSetElementSetNames = NULL;
+        return TCL_OK;
+    }
+    else if (argc == -1)
+        return ir_tcl_strdel (interp, &p->smallSetElementSetNames);
+    if (argc == 3)
+    {
+        free (p->smallSetElementSetNames);
+        if (ir_tcl_strdup (interp, &p->smallSetElementSetNames,
+                           argv[2]) == TCL_ERROR)
+            return TCL_ERROR;
+    }
+    Tcl_AppendResult (interp, p->smallSetElementSetNames, NULL);
+    return TCL_OK;
+}
+
+/*
+ * do_mediumSetElementSetNames: Set/Get medium Set Element Set Names
+ */
+static int do_mediumSetElementSetNames (void *obj, Tcl_Interp *interp,
+                               int argc, char **argv)
+{
+    IrTcl_SetCObj *p = obj;
+
+    if (argc == 0)
+    {
+        p->mediumSetElementSetNames = NULL;
+        return TCL_OK;
+    }
+    else if (argc == -1)
+        return ir_tcl_strdel (interp, &p->mediumSetElementSetNames);
+    if (argc == 3)
+    {
+        free (p->mediumSetElementSetNames);
+        if (ir_tcl_strdup (interp, &p->mediumSetElementSetNames,
+                           argv[2]) == TCL_ERROR)
+            return TCL_ERROR;
+    }
+    Tcl_AppendResult (interp, p->mediumSetElementSetNames, NULL);
+    return TCL_OK;
+}
+
+static IrTcl_Method ir_method_tab[] = {
 { 1, "comstack",                    do_comstack },
 { 1, "protocol",                    do_protocol },
 { 0, "failback",                    do_failback },
+{ 0, "failInfo",                    do_failInfo },
+{ 0, "apduInfo",                    do_apduInfo },
+{ 0, "logLevel",                    do_logLevel },
 
+{ 0, "eventType",                   do_eventType },
 { 1, "connect",                     do_connect },
 { 0, "protocolVersion",             do_protocolVersion },
 { 1, "preferredMessageSize",        do_preferredMessageSize },
 { 1, "maximumRecordSize",           do_maximumRecordSize },
 { 1, "implementationName",          do_implementationName },
 { 1, "implementationId",            do_implementationId },
+{ 1, "implementationVersion",       do_implementationVersion },
 { 0, "targetImplementationName",    do_targetImplementationName },
 { 0, "targetImplementationId",      do_targetImplementationId },
 { 0, "targetImplementationVersion", do_targetImplementationVersion },
@@ -1147,16 +1700,24 @@ static IRMethod ir_method_tab[] = {
 { 0, "initResult",                  do_initResult },
 { 0, "disconnect",                  do_disconnect },
 { 0, "callback",                    do_callback },
+{ 0, "initResponse",                do_initResponse },
+{ 0, "triggerResourceControl",      do_triggerResourceControl },
+{ 0, "initResponse",                do_initResponse },
 { 0, NULL, NULL}
 };
 
-static IRMethod ir_set_c_method_tab[] = {
+static IrTcl_Method ir_set_c_method_tab[] = {
 { 0, "databaseNames",               do_databaseNames},
 { 0, "replaceIndicator",            do_replaceIndicator},
 { 0, "queryType",                   do_queryType },
+{ 0, "preferredRecordSyntax",       do_preferredRecordSyntax },
 { 0, "smallSetUpperBound",          do_smallSetUpperBound},
 { 0, "largeSetLowerBound",          do_largeSetLowerBound},
 { 0, "mediumSetPresentNumber",      do_mediumSetPresentNumber},
+{ 0, "referenceId",                 do_referenceId },
+{ 0, "elementSetNames",             do_elementSetNames },
+{ 0, "smallSetElementSetNames",     do_smallSetElementSetNames },
+{ 0, "mediumSetElementSetNames",    do_mediumSetElementSetNames },
 { 0, NULL, NULL}
 };
 
@@ -1164,10 +1725,10 @@ static IRMethod ir_set_c_method_tab[] = {
  * ir_obj_method: IR Object methods
  */
 static int ir_obj_method (ClientData clientData, Tcl_Interp *interp,
-int argc, char **argv)
+                          int argc, char **argv)
 {
-    IRMethods tab[3];
-    IRObj *p = clientData;
+    IrTcl_Methods tab[3];
+    IrTcl_Obj *p = clientData;
 
     if (argc < 2)
         return ir_method_r (clientData, interp, argc, argv, ir_method_tab);
@@ -1186,14 +1747,15 @@ int argc, char **argv)
  */
 static void ir_obj_delete (ClientData clientData)
 {
-    IRObj *obj = clientData;
-    IRMethods tab[3];
+    IrTcl_Obj *obj = clientData;
+    IrTcl_Methods tab[3];
 
     --(obj->ref_count);
     if (obj->ref_count > 0)
         return;
     assert (obj->ref_count == 0);
 
+    logf (LOG_DEBUG, "ir object delete");
     tab[0].tab = ir_method_tab;
     tab[0].obj = obj;
     tab[1].tab = ir_set_c_method_tab;
@@ -1201,11 +1763,11 @@ static void ir_obj_delete (ClientData clientData)
     tab[2].tab = NULL;
 
     ir_method (NULL, -1, NULL, tab);
+
+    ir_tcl_del_q (obj);
     odr_destroy (obj->odr_in);
     odr_destroy (obj->odr_out);
     odr_destroy (obj->odr_pr);
-    free (obj->buf_out);
-    free (obj->buf_in);
     free (obj);
 }
 
@@ -1213,10 +1775,10 @@ static void ir_obj_delete (ClientData clientData)
  * ir_obj_mk: IR Object creation
  */
 static int ir_obj_mk (ClientData clientData, Tcl_Interp *interp,
-              int argc, char **argv)
+                      int argc, char **argv)
 {
-    IRMethods tab[3];
-    IRObj *obj;
+    IrTcl_Methods tab[3];
+    IrTcl_Obj *obj;
 #if CCL2RPN
     FILE *inf;
 #endif
@@ -1226,30 +1788,27 @@ static int ir_obj_mk (ClientData clientData, Tcl_Interp *interp,
         interp->result = "wrong # args";
         return TCL_ERROR;
     }
-    if (!(obj = ir_malloc (interp, sizeof(*obj))))
-        return TCL_ERROR;
-
+    obj = ir_tcl_malloc (sizeof(*obj));
     obj->ref_count = 1;
 #if CCL2RPN
     obj->bibset = ccl_qual_mk (); 
     if ((inf = fopen ("default.bib", "r")))
     {
-       ccl_qual_file (obj->bibset, inf);
-       fclose (inf);
+        ccl_qual_file (obj->bibset, inf);
+        fclose (inf);
     }
 #endif
 
+    logf (LOG_DEBUG, "ir object create %s", argv[1]);
     obj->odr_in = odr_createmem (ODR_DECODE);
     obj->odr_out = odr_createmem (ODR_ENCODE);
     obj->odr_pr = odr_createmem (ODR_PRINT);
-
-    obj->len_out = 10000;
-    if (!(obj->buf_out = ir_malloc (interp, obj->len_out)))
-        return TCL_ERROR;
-    odr_setbuf (obj->odr_out, obj->buf_out, obj->len_out, 0);
+    obj->state = IR_TCL_R_Idle;
+    obj->interp = interp;
 
     obj->len_in = 0;
     obj->buf_in = NULL;
+    obj->request_queue = NULL;
 
     tab[0].tab = ir_method_tab;
     tab[0].obj = obj;
@@ -1268,68 +1827,105 @@ static int ir_obj_mk (ClientData clientData, Tcl_Interp *interp,
 /*
  * do_search: Do search request
  */
-static int do_search (void *o, Tcl_Interp *interp,
-                      int argc, char **argv)
+static int do_search (void *o, Tcl_Interp *interp, int argc, char **argv)
 {
-    Z_SearchRequest req;
+    Z_SearchRequest *req;
     Z_Query query;
-    Z_APDU apdu, *apdup = &apdu;
+    Z_APDU *apdu;
     Odr_oct ccl_query;
-    IRSetObj *obj = o;
-    IRObj *p = obj->parent;
+    IrTcl_SetObj *obj = o;
+    IrTcl_Obj *p;
     int r;
     oident bib1;
 
     if (argc <= 0)
         return TCL_OK;
 
-    p->set_child = o;
+    p = obj->parent;
     if (argc != 3)
     {
         interp->result = "wrong # args";
         return TCL_ERROR;
     }
-    if (!p->set_inher.num_databaseNames)
+    if (!obj->set_inher.num_databaseNames)
     {
         interp->result = "no databaseNames";
         return TCL_ERROR;
     }
     if (!p->cs_link)
     {
-        interp->result = "not connected";
+        interp->result = "search: not connected";
         return TCL_ERROR;
     }
-    odr_reset (p->odr_out);
-    apdu.which = Z_APDU_searchRequest;
-    apdu.u.searchRequest = &req;
-    
-    bib1.proto = PROTO_Z3950;
-    bib1.class = CLASS_ATTSET;
+    apdu = zget_APDU (p->odr_out, Z_APDU_searchRequest);
+    req = apdu->u.searchRequest;
+
+    obj->start = 1;
+
+    bib1.proto = p->protocol_type;
+    bib1.oclass = CLASS_ATTSET;
     bib1.value = VAL_BIB1;
 
-    req.referenceId = 0;
-    req.smallSetUpperBound = &p->set_inher.smallSetUpperBound;
-    req.largeSetLowerBound = &p->set_inher.largeSetLowerBound;
-    req.mediumSetPresentNumber = &p->set_inher.mediumSetPresentNumber;
-    req.replaceIndicator = &p->set_inher.replaceIndicator;
-    req.resultSetName = obj->setName ? obj->setName : "Default";
-    logf (LOG_DEBUG, "Search, resultSetName %s", req.resultSetName);
-    req.num_databaseNames = p->set_inher.num_databaseNames;
-    req.databaseNames = p->set_inher.databaseNames;
-    for (r=0; r < p->set_inher.num_databaseNames; r++)
-        logf (LOG_DEBUG, " Database %s", p->set_inher.databaseNames[r]);
-    req.smallSetElementSetNames = 0;
-    req.mediumSetElementSetNames = 0;
-    req.preferredRecordSyntax = 0;
-    req.query = &query;
-
-    if (!strcmp (p->set_inher.queryType, "rpn"))
+    set_referenceId (p->odr_out, &req->referenceId,
+                     obj->set_inher.referenceId);
+
+    req->smallSetUpperBound = &obj->set_inher.smallSetUpperBound;
+    req->largeSetLowerBound = &obj->set_inher.largeSetLowerBound;
+    req->mediumSetPresentNumber = &obj->set_inher.mediumSetPresentNumber;
+    req->replaceIndicator = &obj->set_inher.replaceIndicator;
+    req->resultSetName = obj->setName ? obj->setName : "Default";
+    logf (LOG_DEBUG, "Search, resultSetName %s", req->resultSetName);
+    req->num_databaseNames = obj->set_inher.num_databaseNames;
+    req->databaseNames = obj->set_inher.databaseNames;
+    for (r=0; r < obj->set_inher.num_databaseNames; r++)
+        logf (LOG_DEBUG, " Database %s", obj->set_inher.databaseNames[r]);
+    if (obj->set_inher.preferredRecordSyntax)
+    {
+        struct oident ident;
+
+        ident.proto = p->protocol_type;
+        ident.oclass = CLASS_RECSYN;
+        ident.value = *obj->set_inher.preferredRecordSyntax;
+        logf (LOG_DEBUG, "Preferred record syntax is %d", ident.value);
+        req->preferredRecordSyntax = odr_oiddup (p->odr_out, 
+                                                 oid_getoidbyent (&ident));
+    }
+    else
+        req->preferredRecordSyntax = 0;
+
+    if (obj->set_inher.smallSetElementSetNames &&
+        *obj->set_inher.smallSetElementSetNames)
+    {
+        Z_ElementSetNames *esn = odr_malloc (p->odr_out, sizeof(*esn));
+        
+        esn->which = Z_ElementSetNames_generic;
+        esn->u.generic = obj->set_inher.smallSetElementSetNames;
+        req->smallSetElementSetNames = esn;
+    }
+    else
+        req->smallSetElementSetNames = NULL; 
+    
+    if (obj->set_inher.mediumSetElementSetNames &&
+        *obj->set_inher.mediumSetElementSetNames)
+    {
+        Z_ElementSetNames *esn = odr_malloc (p->odr_out, sizeof(*esn));
+        
+        esn->which = Z_ElementSetNames_generic;
+        esn->u.generic = obj->set_inher.mediumSetElementSetNames;
+        req->mediumSetElementSetNames = esn;
+    }
+    else
+        req->mediumSetElementSetNames = NULL; 
+    
+    req->query = &query;
+    
+    if (!strcmp (obj->set_inher.queryType, "rpn"))
     {
         Z_RPNQuery *RPNquery;
 
         RPNquery = p_query_rpn (p->odr_out, argv[2]);
-       if (!RPNquery)
-       {
+        if (!RPNquery)
+        {
             Tcl_AppendResult (interp, "Syntax error in query", NULL);
             return TCL_ERROR;
         }
@@ -1339,7 +1935,7 @@ static int do_search (void *o, Tcl_Interp *interp,
         logf (LOG_DEBUG, "RPN");
     }
 #if CCL2RPN
-    else if (!strcmp (p->set_inher.queryType, "cclrpn"))
+    else if (!strcmp (obj->set_inher.queryType, "cclrpn"))
     {
         int error;
         int pos;
@@ -1349,7 +1945,8 @@ static int do_search (void *o, Tcl_Interp *interp,
         rpn = ccl_find_str(p->bibset, argv[2], &error, &pos);
         if (error)
         {
-            Tcl_AppendResult (interp, "CCL error: ", ccl_err_msg(error),NULL);
+            Tcl_AppendResult (interp, "CCL error: ", 
+                              ccl_err_msg(error), NULL);
             return TCL_ERROR;
         }
         ccl_pr_tree (rpn, stderr);
@@ -1361,7 +1958,7 @@ static int do_search (void *o, Tcl_Interp *interp,
         logf (LOG_DEBUG, "CCLRPN");
     }
 #endif
-    else if (!strcmp (p->set_inher.queryType, "ccl"))
+    else if (!strcmp (obj->set_inher.queryType, "ccl"))
     {
         query.which = Z_Query_type_2;
         query.u.type_2 = &ccl_query;
@@ -1374,26 +1971,65 @@ static int do_search (void *o, Tcl_Interp *interp,
         interp->result = "unknown query method";
         return TCL_ERROR;
     }
-    if (!z_APDU (p->odr_out, &apdup, 0))
+    return ir_tcl_send_APDU (interp, p, apdu, "search", *argv);
+}
+
+/*
+ * do_searchResponse: add search response handler
+ */
+static int do_searchResponse (void *o, Tcl_Interp *interp,
+                              int argc, char **argv)
+{
+    IrTcl_SetObj *obj = o;
+
+    if (argc == 0)
     {
-        interp->result = odr_errlist [odr_geterror (p->odr_out)];
-        odr_reset (p->odr_out);
-        return TCL_ERROR;
-    } 
-    p->sbuf = odr_getbuf (p->odr_out, &p->slen, NULL);
-    if ((r=cs_put (p->cs_link, p->sbuf, p->slen)) < 0)
+        obj->searchResponse = NULL;
+        return TCL_OK;
+    }
+    else if (argc == -1)
+        return ir_tcl_strdel (interp, &obj->searchResponse);
+    if (argc == 3)
     {
-        interp->result = "cs_put failed in search";
-        return TCL_ERROR;
+        free (obj->searchResponse);
+        if (argv[2][0])
+        {
+            if (ir_tcl_strdup (interp, &obj->searchResponse, argv[2])
+                == TCL_ERROR)
+                return TCL_ERROR;
+        }
+        else
+            obj->searchResponse = NULL;
     }
-    else if (r == 1)
+    return TCL_OK;
+}
+
+/*
+ * do_presentResponse: add present response handler
+ */
+static int do_presentResponse (void *o, Tcl_Interp *interp,
+                               int argc, char **argv)
+{
+    IrTcl_SetObj *obj = o;
+
+    if (argc == 0)
     {
-        ir_select_add_write (cs_fileno(p->cs_link), p);
-        logf (LOG_DEBUG, "Sent part of searchRequest (%d bytes)", p->slen);
+        obj->presentResponse = NULL;
+        return TCL_OK;
     }
-    else
+    else if (argc == -1)
+        return ir_tcl_strdel (interp, &obj->presentResponse);
+    if (argc == 3)
     {
-        logf (LOG_DEBUG, "Whole search request (%d bytes)", p->slen);
+        free (obj->presentResponse);
+        if (argv[2][0])
+        {
+            if (ir_tcl_strdup (interp, &obj->presentResponse, argv[2])
+                == TCL_ERROR)
+                return TCL_ERROR;
+        }
+        else
+            obj->presentResponse = NULL;
     }
     return TCL_OK;
 }
@@ -1402,12 +2038,15 @@ static int do_search (void *o, Tcl_Interp *interp,
  * do_resultCount: Get number of hits
  */
 static int do_resultCount (void *o, Tcl_Interp *interp,
-                      int argc, char **argv)
+                       int argc, char **argv)
 {
-    IRSetObj *obj = o;
+    IrTcl_SetObj *obj = o;
 
     if (argc <= 0)
+    {
+        obj->resultCount = 0;
         return TCL_OK;
+    }
     return get_set_int (&obj->resultCount, interp, argc, argv);
 }
 
@@ -1415,9 +2054,9 @@ static int do_resultCount (void *o, Tcl_Interp *interp,
  * do_searchStatus: Get search status (after search response)
  */
 static int do_searchStatus (void *o, Tcl_Interp *interp,
-                           int argc, char **argv)
+                            int argc, char **argv)
 {
-    IRSetObj *obj = o;
+    IrTcl_SetObj *obj = o;
 
     if (argc <= 0)
         return TCL_OK;
@@ -1428,9 +2067,9 @@ static int do_searchStatus (void *o, Tcl_Interp *interp,
  * do_presentStatus: Get search status (after search/present response)
  */
 static int do_presentStatus (void *o, Tcl_Interp *interp,
-                           int argc, char **argv)
+                            int argc, char **argv)
 {
-    IRSetObj *obj = o;
+    IrTcl_SetObj *obj = o;
 
     if (argc <= 0)
         return TCL_OK;
@@ -1444,10 +2083,13 @@ static int do_presentStatus (void *o, Tcl_Interp *interp,
 static int do_nextResultSetPosition (void *o, Tcl_Interp *interp,
                                      int argc, char **argv)
 {
-    IRSetObj *obj = o;
+    IrTcl_SetObj *obj = o;
 
     if (argc <= 0)
+    {
+        obj->nextResultSetPosition = 0;
         return TCL_OK;
+    }
     return get_set_int (&obj->nextResultSetPosition, interp, argc, argv);
 }
 
@@ -1455,18 +2097,18 @@ static int do_nextResultSetPosition (void *o, Tcl_Interp *interp,
  * do_setName: Set result Set name
  */
 static int do_setName (void *o, Tcl_Interp *interp,
-                      int argc, char **argv)
+                       int argc, char **argv)
 {
-    IRSetObj *obj = o;
+    IrTcl_SetObj *obj = o;
 
     if (argc == 0)
-        return ir_strdup (interp, &obj->setName, "Default");
+        return ir_tcl_strdup (interp, &obj->setName, "Default");
     else if (argc == -1)
-        return ir_strdel (interp, &obj->setName);
+        return ir_tcl_strdel (interp, &obj->setName);
     if (argc == 3)
     {
         free (obj->setName);
-        if (ir_strdup (interp, &obj->setName, argv[2])
+        if (ir_tcl_strdup (interp, &obj->setName, argv[2])
             == TCL_ERROR)
             return TCL_ERROR;
     }
@@ -1478,35 +2120,202 @@ static int do_setName (void *o, Tcl_Interp *interp,
  * do_numberOfRecordsReturned: Get number of records returned
  */
 static int do_numberOfRecordsReturned (void *o, Tcl_Interp *interp,
-                      int argc, char **argv)
+                                       int argc, char **argv)
 {
-    IRSetObj *obj = o;
+    IrTcl_SetObj *obj = o;
 
-    if (argc < 0)
+    if (argc <= 0)
+    {
+        obj->numberOfRecordsReturned = 0;
         return TCL_OK;
+    }
     return get_set_int (&obj->numberOfRecordsReturned, interp, argc, argv);
 }
 
 /*
- * do_recordType: Return record type (if any) at position.
+ * do_type: Return type (if any) at position.
  */
-static int do_recordType (void *o, Tcl_Interp *interp, int argc, char **argv)
+static int do_type (void *o, Tcl_Interp *interp, int argc, char **argv)
 {
-    IRSetObj *obj = o;
+    IrTcl_SetObj *obj = o;
     int offset;
-    IRRecordList *rl;
+    IrTcl_RecordList *rl;
 
     if (argc == 0)
     {
         obj->record_list = NULL;
-       return TCL_OK;
+        return TCL_OK;
     }
     else if (argc == -1)
     {
         delete_IR_records (obj);
-       return TCL_OK;
+        return TCL_OK;
     }
-    if (argc < 3)
+    if (argc != 3)
+    {
+        sprintf (interp->result, "wrong # args");
+        return TCL_ERROR;
+    }
+    if (Tcl_GetInt (interp, argv[2], &offset)==TCL_ERROR)
+        return TCL_ERROR;
+    rl = find_IR_record (obj, offset);
+    if (!rl)
+    {
+        logf (LOG_DEBUG, "No record at position %d", offset);
+        return TCL_OK;
+    }
+    switch (rl->which)
+    {
+    case Z_NamePlusRecord_databaseRecord:
+        interp->result = "DB";
+        break;
+    case Z_NamePlusRecord_surrogateDiagnostic:
+        interp->result = "SD";
+        break;
+    }
+    return TCL_OK;
+}
+
+
+/*
+ * do_recordType: Return record type (if any) at position.
+ */
+static int do_recordType (void *o, Tcl_Interp *interp, int argc, char **argv)
+{
+    IrTcl_SetObj *obj = o;
+    int offset;
+    IrTcl_RecordList *rl;
+
+    if (argc == 0)
+    {
+        return TCL_OK;
+    }
+    else if (argc == -1)
+    {
+        return TCL_OK;
+    }
+    if (argc != 3)
+    {
+        sprintf (interp->result, "wrong # args");
+        return TCL_ERROR;
+    }
+    if (Tcl_GetInt (interp, argv[2], &offset)==TCL_ERROR)
+        return TCL_ERROR;
+    rl = find_IR_record (obj, offset);
+    if (!rl)
+        return TCL_OK;
+    if (rl->which != Z_NamePlusRecord_databaseRecord)
+    {
+        Tcl_AppendResult (interp, "No DB record at #", argv[2], NULL);
+        return TCL_ERROR;
+    }
+    Tcl_AppendElement (interp, (char*)
+                       IrTcl_getRecordSyntaxStr (rl->u.dbrec.type));
+    return TCL_OK;
+}
+
+/*
+ * set record elements (for record extraction)
+ */
+static int do_recordElements (void *o, Tcl_Interp *interp,
+                              int argc, char **argv)
+{
+    IrTcl_SetObj *obj = o;
+
+    if (argc == 0)
+    {
+        obj->recordElements = NULL;
+        return TCL_OK;
+    }
+    else if (argc == -1)
+        return ir_tcl_strdel (NULL, &obj->recordElements);
+    if (argc > 3)
+    {
+        sprintf (interp->result, "wrong # args");
+        return TCL_ERROR;
+    }
+    if (argc == 3)
+    {
+        free (obj->recordElements);
+        return ir_tcl_strdup (NULL, &obj->recordElements, 
+                              (*argv[2] ? argv[2] : NULL));
+    }
+    Tcl_AppendResult (interp, obj->recordElements, NULL);
+    return TCL_OK;
+}
+
+/*
+ * ir_diagResult 
+ */
+static int ir_diagResult (Tcl_Interp *interp, IrTcl_Diagnostic *list, int num)
+{
+    char buf[20];
+    int i;
+    const char *cp;
+
+    for (i = 0; i<num; i++)
+    {
+        logf (LOG_DEBUG, "Diagnostic, code %d", list[i].condition);
+        sprintf (buf, "%d", list[i].condition);
+        Tcl_AppendElement (interp, buf);
+        cp = diagbib1_str (list[i].condition);
+        if (cp)
+            Tcl_AppendElement (interp, (char*) cp);
+        else
+            Tcl_AppendElement (interp, "");
+        if (list[i].addinfo)
+            Tcl_AppendElement (interp, (char*) list[i].addinfo);
+        else
+            Tcl_AppendElement (interp, "");
+    }
+    return TCL_OK;
+}
+
+/*
+ * do_diag: Return diagnostic record info
+ */
+static int do_diag (void *o, Tcl_Interp *interp, int argc, char **argv)
+{
+    IrTcl_SetObj *obj = o;
+    int offset;
+    IrTcl_RecordList *rl;
+
+    if (argc <= 0)
+        return TCL_OK;
+    if (argc != 3)
+    {
+        sprintf (interp->result, "wrong # args");
+        return TCL_ERROR;
+    }
+    if (Tcl_GetInt (interp, argv[2], &offset)==TCL_ERROR)
+        return TCL_ERROR;
+    rl = find_IR_record (obj, offset);
+    if (!rl)
+    {
+        Tcl_AppendResult (interp, "No record at #", argv[2], NULL);
+        return TCL_ERROR;
+    }
+    if (rl->which != Z_NamePlusRecord_surrogateDiagnostic)
+    {
+        Tcl_AppendResult (interp, "No Diagnostic record at #", argv[2], NULL);
+        return TCL_ERROR;
+    }
+    return ir_diagResult (interp, rl->u.surrogateDiagnostics.list,
+                          rl->u.surrogateDiagnostics.num);
+}
+
+/*
+ * do_getMarc: Get ISO2709 Record lines/fields
+ */
+static int do_getMarc (void *o, Tcl_Interp *interp, int argc, char **argv)
+{
+    IrTcl_SetObj *obj = o;
+    int offset;
+    IrTcl_RecordList *rl;
+
+    if (argc <= 0)
+        return TCL_OK;
+    if (argc < 7)
     {
         sprintf (interp->result, "wrong # args");
         return TCL_ERROR;
@@ -1515,32 +2324,30 @@ static int do_recordType (void *o, Tcl_Interp *interp, int argc, char **argv)
         return TCL_ERROR;
     rl = find_IR_record (obj, offset);
     if (!rl)
-        return TCL_OK;
-    switch (rl->which)
     {
-    case Z_NamePlusRecord_databaseRecord:
-        interp->result = "databaseRecord";
-        break;
-    case Z_NamePlusRecord_surrogateDiagnostic:
-        interp->result = "surrogateDiagnostic";
-        break;
+        Tcl_AppendResult (interp, "No record at #", argv[2], NULL);
+        return TCL_ERROR;
     }
-    return TCL_OK;
+    if (rl->which != Z_NamePlusRecord_databaseRecord)
+    {
+        Tcl_AppendResult (interp, "No DB record at #", argv[2], NULL);
+        return TCL_ERROR;
+    }
+    return ir_tcl_get_marc (interp, rl->u.dbrec.buf, argc, argv);
 }
 
 /*
- * do_recordDiag: Return diagnostic record info
+ * do_getSutrs: Get SUTRS Record
  */
-static int do_recordDiag (void *o, Tcl_Interp *interp, int argc, char **argv)
+static int do_getSutrs (void *o, Tcl_Interp *interp, int argc, char **argv)
 {
-    IRSetObj *obj = o;
+    IrTcl_SetObj *obj = o;
     int offset;
-    IRRecordList *rl;
-    char buf[20];
+    IrTcl_RecordList *rl;
 
     if (argc <= 0)
         return TCL_OK;
-    if (argc < 3)
+    if (argc != 3)
     {
         sprintf (interp->result, "wrong # args");
         return TCL_ERROR;
@@ -1553,30 +2360,30 @@ static int do_recordDiag (void *o, Tcl_Interp *interp, int argc, char **argv)
         Tcl_AppendResult (interp, "No record at #", argv[2], NULL);
         return TCL_ERROR;
     }
-    if (rl->which != Z_NamePlusRecord_surrogateDiagnostic)
+    if (rl->which != Z_NamePlusRecord_databaseRecord)
     {
-        Tcl_AppendResult (interp, "No Diagnostic record at #", argv[2], NULL);
+        Tcl_AppendResult (interp, "No DB record at #", argv[2], NULL);
         return TCL_ERROR;
     }
-    sprintf (buf, "%d", rl->u.diag.condition);
-    Tcl_AppendResult (interp, buf, " {", 
-                      (rl->u.diag.addinfo ? rl->u.diag.addinfo : ""),
-                      "}", NULL);
+    if (rl->u.dbrec.type != VAL_SUTRS)
+        return TCL_OK;
+    Tcl_AppendElement (interp, rl->u.dbrec.buf);
     return TCL_OK;
 }
 
+
 /*
- * do_getMarc: Get ISO2709 Record lines/fields
+ * do_getGrs: Get a GRS1 Record
  */
-static int do_getMarc (void *o, Tcl_Interp *interp, int argc, char **argv)
+static int do_getGrs (void *o, Tcl_Interp *interp, int argc, char **argv)
 {
-    IRSetObj *obj = o;
+    IrTcl_SetObj *obj = o;
     int offset;
-    IRRecordList *rl;
+    IrTcl_RecordList *rl;
 
     if (argc <= 0)
         return TCL_OK;
-    if (argc < 7)
+    if (argc < 3)
     {
         sprintf (interp->result, "wrong # args");
         return TCL_ERROR;
@@ -1591,10 +2398,12 @@ static int do_getMarc (void *o, Tcl_Interp *interp, int argc, char **argv)
     }
     if (rl->which != Z_NamePlusRecord_databaseRecord)
     {
-        Tcl_AppendResult (interp, "No MARC record at #", argv[2], NULL);
+        Tcl_AppendResult (interp, "No DB record at #", argv[2], NULL);
         return TCL_ERROR;
     }
-    return ir_tcl_get_marc (interp, rl->u.dbrec.buf, argc, argv);
+    if (rl->u.dbrec.type != VAL_GRS1)
+        return TCL_OK;
+    return ir_tcl_get_grs (interp, rl->u.dbrec.u.grs1, argc, argv);
 }
 
 
@@ -1604,16 +2413,21 @@ static int do_getMarc (void *o, Tcl_Interp *interp, int argc, char **argv)
 static int do_responseStatus (void *o, Tcl_Interp *interp, 
                              int argc, char **argv)
 {
-    IRSetObj *obj = o;
+    IrTcl_SetObj *obj = o;
 
     if (argc == 0)
     {
         obj->recordFlag = 0;
-       obj->addinfo = NULL;
-       return TCL_OK;
+        obj->nonSurrogateDiagnosticNum = 0;
+        obj->nonSurrogateDiagnosticList = NULL;
+        return TCL_OK;
     }
     else if (argc == -1)
-        return ir_strdel (interp, &obj->addinfo);
+    {
+        ir_deleteDiags (&obj->nonSurrogateDiagnosticList,
+                        &obj->nonSurrogateDiagnosticNum);
+        return TCL_OK;
+    }
     if (!obj->recordFlag)
     {
         Tcl_AppendElement (interp, "OK");
@@ -1622,11 +2436,12 @@ static int do_responseStatus (void *o, Tcl_Interp *interp,
     switch (obj->which)
     {
     case Z_Records_DBOSD:
-       Tcl_AppendElement (interp, "DBOSD");
+        Tcl_AppendElement (interp, "DBOSD");
         break;
     case Z_Records_NSD:
-        return mk_nonSurrogateDiagnostics (interp, obj->condition, 
-                                          obj->addinfo);
+        Tcl_AppendElement (interp, "NSD");
+        return ir_diagResult (interp, obj->nonSurrogateDiagnosticList,
+                              obj->nonSurrogateDiagnosticNum);
     }
     return TCL_OK;
 }
@@ -1635,16 +2450,14 @@ static int do_responseStatus (void *o, Tcl_Interp *interp,
  * do_present: Perform Present Request
  */
 
-static int do_present (void *o, Tcl_Interp *interp,
-                       int argc, char **argv)
+static int do_present (void *o, Tcl_Interp *interp, int argc, char **argv)
 {
-    IRSetObj *obj = o;
-    IRObj *p = obj->parent;
-    Z_APDU apdu, *apdup = &apdu;
-    Z_PresentRequest req;
+    IrTcl_SetObj *obj = o;
+    IrTcl_Obj *p;
+    Z_APDU *apdu;
+    Z_PresentRequest *req;
     int start;
     int number;
-    int r;
 
     if (argc <= 0)
         return TCL_OK;
@@ -1662,51 +2475,55 @@ static int do_present (void *o, Tcl_Interp *interp,
     }
     else 
         number = 10;
+    p = obj->parent;
     if (!p->cs_link)
     {
-        interp->result = "not connected";
+        interp->result = "present: not connected";
         return TCL_ERROR;
     }
-    odr_reset (p->odr_out);
+
     obj->start = start;
     obj->number = number;
 
-    apdu.which = Z_APDU_presentRequest;
-    apdu.u.presentRequest = &req;
-    req.referenceId = 0;
-    /* sprintf(setstring, "%d", setnumber); */
+    apdu = zget_APDU (p->odr_out, Z_APDU_presentRequest);
+    req = apdu->u.presentRequest;
 
-    req.resultSetId = obj->setName ? obj->setName : "Default";
-    
-    req.resultSetStartPoint = &start;
-    req.numberOfRecordsRequested = &number;
-    req.elementSetNames = 0;
-    req.preferredRecordSyntax = 0;
+    set_referenceId (p->odr_out, &req->referenceId,
+                     obj->set_inher.referenceId);
 
-    if (!z_APDU (p->odr_out, &apdup, 0))
-    {
-        interp->result = odr_errlist [odr_geterror (p->odr_out)];
-        odr_reset (p->odr_out);
-        return TCL_ERROR;
-    } 
-    p->sbuf = odr_getbuf (p->odr_out, &p->slen, NULL);
-    if ((r=cs_put (p->cs_link, p->sbuf, p->slen)) < 0)
-    {
-        interp->result = "cs_put failed in present";
-        return TCL_ERROR;
-    }
-    else if (r == 1)
+    req->resultSetId = obj->setName ? obj->setName : "Default";
+    
+    req->resultSetStartPoint = &start;
+    req->numberOfRecordsRequested = &number;
+    if (obj->set_inher.preferredRecordSyntax)
     {
-        ir_select_add_write (cs_fileno(p->cs_link), p);
-        logf (LOG_DEBUG, "Part of present request, start=%d, num=%d" 
-              " (%d bytes)", start, number, p->slen);
+        struct oident ident;
+
+        ident.proto = p->protocol_type;
+        ident.oclass = CLASS_RECSYN;
+        ident.value = *obj->set_inher.preferredRecordSyntax;
+        logf (LOG_DEBUG, "Preferred record syntax is %d", ident.value);
+        req->preferredRecordSyntax = odr_oiddup (p->odr_out, 
+                                                 oid_getoidbyent (&ident));
     }
     else
+        req->preferredRecordSyntax = 0;
+
+    if (obj->set_inher.elementSetNames && *obj->set_inher.elementSetNames)
     {
-        logf (LOG_DEBUG, "Whole present request, start=%d, num=%d"
-              " (%d bytes)", start, number, p->slen);
+        Z_ElementSetNames *esn = odr_malloc (p->odr_out, sizeof(*esn));
+        Z_RecordComposition *compo = odr_malloc (p->odr_out, sizeof(*compo));
+
+        esn->which = Z_ElementSetNames_generic;
+        esn->u.generic = obj->set_inher.elementSetNames;
+
+        req->recordComposition = compo;
+        compo->which = Z_RecordComp_simple;
+        compo->u.simple = esn;
     }
-    return TCL_OK;
+    else
+        req->recordComposition = NULL;
+    return ir_tcl_send_APDU (interp, p, apdu, "present", *argv);
 }
 
 /*
@@ -1716,7 +2533,7 @@ static int do_present (void *o, Tcl_Interp *interp,
 static int do_loadFile (void *o, Tcl_Interp *interp,
                         int argc, char **argv)
 {
-    IRSetObj *setobj = o;
+    IrTcl_SetObj *setobj = o;
     FILE *inf;
     size_t size;
     int  no = 1;
@@ -1724,7 +2541,7 @@ static int do_loadFile (void *o, Tcl_Interp *interp,
 
     if (argc <= 0)
         return TCL_OK;
-    if (argc < 3)
+    if (argc != 3)
     {
         interp->result = "wrong # args";
         return TCL_ERROR;
@@ -1737,11 +2554,12 @@ static int do_loadFile (void *o, Tcl_Interp *interp,
     }
     while ((buf = ir_tcl_fread_marc (inf, &size)))
     {
-        IRRecordList *rl;
+        IrTcl_RecordList *rl;
 
-        rl = new_IR_record (setobj, no, Z_NamePlusRecord_databaseRecord);
+        rl = new_IR_record (setobj, no, Z_NamePlusRecord_databaseRecord, "F");
+        rl->u.dbrec.type = VAL_USMARC;
         rl->u.dbrec.buf = buf;
-       rl->u.dbrec.size = size;
+        rl->u.dbrec.size = size;
         no++;
     }
     setobj->numberOfRecordsReturned = no-1;
@@ -1749,8 +2567,10 @@ static int do_loadFile (void *o, Tcl_Interp *interp,
     return TCL_OK;
 }
 
-static IRMethod ir_set_method_tab[] = {
+static IrTcl_Method ir_set_method_tab[] = {
     { 0, "search",                  do_search },
+    { 0, "searchResponse",          do_searchResponse },
+    { 0, "presentResponse",         do_presentResponse },
     { 0, "searchStatus",            do_searchStatus },
     { 0, "presentStatus",           do_presentStatus },
     { 0, "nextResultSetPosition",   do_nextResultSetPosition },
@@ -1758,9 +2578,13 @@ static IRMethod ir_set_method_tab[] = {
     { 0, "resultCount",             do_resultCount },
     { 0, "numberOfRecordsReturned", do_numberOfRecordsReturned },
     { 0, "present",                 do_present },
-    { 0, "recordType",              do_recordType },
+    { 0, "type",                    do_type },
     { 0, "getMarc",                 do_getMarc },
-    { 0, "Diag",                    do_recordDiag },
+    { 0, "getSutrs",                do_getSutrs },
+    { 0, "getGrs",                  do_getGrs },
+    { 0, "recordType",              do_recordType },
+    { 0, "recordElements",          do_recordElements },
+    { 0, "diag",                    do_diag },
     { 0, "responseStatus",          do_responseStatus },
     { 0, "loadFile",                do_loadFile },
     { 0, NULL, NULL}
@@ -1772,8 +2596,8 @@ static IRMethod ir_set_method_tab[] = {
 static int ir_set_obj_method (ClientData clientData, Tcl_Interp *interp,
                           int argc, char **argv)
 {
-    IRMethods tabs[3];
-    IRSetObj *p = clientData;
+    IrTcl_Methods tabs[3];
+    IrTcl_SetObj *p = clientData;
 
     if (argc < 2)
     {
@@ -1794,8 +2618,10 @@ static int ir_set_obj_method (ClientData clientData, Tcl_Interp *interp,
  */
 static void ir_set_obj_delete (ClientData clientData)
 {
-    IRMethods tabs[3];
-    IRSetObj *p = clientData;
+    IrTcl_Methods tabs[3];
+    IrTcl_SetObj *p = clientData;
+
+    logf (LOG_DEBUG, "ir set delete");
 
     tabs[0].tab = ir_set_method_tab;
     tabs[0].obj = p;
@@ -1814,48 +2640,72 @@ static void ir_set_obj_delete (ClientData clientData)
 static int ir_set_obj_mk (ClientData clientData, Tcl_Interp *interp,
                           int argc, char **argv)
 {
-    IRMethods tabs[3];
-    IRSetObj *obj;
+    IrTcl_Methods tabs[3];
+    IrTcl_SetObj *obj;
 
     if (argc < 2 || argc > 3)
     {
         interp->result = "wrong # args";
         return TCL_ERROR;
     }
-    if (!(obj = ir_malloc (interp, sizeof(*obj))))
-        return TCL_ERROR;
-    else if (argc == 3)
+    obj = ir_tcl_malloc (sizeof(*obj));
+    logf (LOG_DEBUG, "ir set create");
+    if (argc == 3)
     {
         Tcl_CmdInfo parent_info;
         int i;
-        IRSetCObj *dst;
-        IRSetCObj *src;
+        IrTcl_SetCObj *dst;
+        IrTcl_SetCObj *src;
 
         if (!Tcl_GetCommandInfo (interp, argv[2], &parent_info))
         {
             interp->result = "No parent";
             return TCL_ERROR;
         }
-        obj->parent = (IRObj *) parent_info.clientData;
+        obj->parent = (IrTcl_Obj *) parent_info.clientData;
 
         dst = &obj->set_inher;
         src = &obj->parent->set_inher;
 
-        dst->num_databaseNames = src->num_databaseNames;
-        if (!(dst->databaseNames =
-              ir_malloc (interp, sizeof (*dst->databaseNames)
-                         * dst->num_databaseNames)))
-            return TCL_ERROR;
+        if ((dst->num_databaseNames = src->num_databaseNames))
+            dst->databaseNames =
+                ir_tcl_malloc (sizeof (*dst->databaseNames)
+                               * dst->num_databaseNames);
+        else
+            dst->databaseNames = NULL;
         for (i = 0; i < dst->num_databaseNames; i++)
-        {
-            if (ir_strdup (interp, &dst->databaseNames[i],
+            if (ir_tcl_strdup (interp, &dst->databaseNames[i],
                            src->databaseNames[i]) == TCL_ERROR)
                 return TCL_ERROR;
-        }
-        if (ir_strdup (interp, &dst->queryType, src->queryType)
+        if (ir_tcl_strdup (interp, &dst->queryType, src->queryType)
             == TCL_ERROR)
             return TCL_ERROR;
-        
+
+        if (ir_tcl_strdup (interp, &dst->referenceId, src->referenceId)
+            == TCL_ERROR)
+            return TCL_ERROR;
+
+        if (ir_tcl_strdup (interp, &dst->elementSetNames, src->elementSetNames)
+            == TCL_ERROR)
+            return TCL_ERROR;
+
+        if (ir_tcl_strdup (interp, &dst->smallSetElementSetNames,
+                           src->smallSetElementSetNames)
+            == TCL_ERROR)
+            return TCL_ERROR;
+
+        if (ir_tcl_strdup (interp, &dst->mediumSetElementSetNames,
+                           src->mediumSetElementSetNames)
+            == TCL_ERROR)
+            return TCL_ERROR;
+
+        if (src->preferredRecordSyntax && 
+            (dst->preferredRecordSyntax 
+             = ir_tcl_malloc (sizeof(*dst->preferredRecordSyntax))))
+            *dst->preferredRecordSyntax = *src->preferredRecordSyntax;
+        else
+            dst->preferredRecordSyntax = NULL;
+        dst->replaceIndicator = src->replaceIndicator;
         dst->smallSetUpperBound = src->smallSetUpperBound;
         dst->largeSetLowerBound = src->largeSetLowerBound;
         dst->mediumSetPresentNumber = src->mediumSetPresentNumber;
@@ -1882,11 +2732,10 @@ static int ir_set_obj_mk (ClientData clientData, Tcl_Interp *interp,
  */
 static int do_scan (void *o, Tcl_Interp *interp, int argc, char **argv)
 {
-    Z_ScanRequest req;
-    Z_APDU apdu, *apdup = &apdu;
-    IRScanObj *obj = o;
-    IRObj *p = obj->parent;
-    int r;
+    Z_ScanRequest *req;
+    Z_APDU *apdu;
+    IrTcl_ScanObj *obj = o;
+    IrTcl_Obj *p = obj->parent;
     oident bib1;
 #if CCL2RPN
     struct ccl_rpn_node *rpn;
@@ -1895,7 +2744,6 @@ static int do_scan (void *o, Tcl_Interp *interp, int argc, char **argv)
 
     if (argc <= 0)
         return TCL_OK;
-    p->scan_child = o;
     if (argc != 3)
     {
         interp->result = "wrong # args";
@@ -1904,31 +2752,31 @@ static int do_scan (void *o, Tcl_Interp *interp, int argc, char **argv)
     if (!p->set_inher.num_databaseNames)
     {
         interp->result = "no databaseNames";
-       return TCL_ERROR;
+        return TCL_ERROR;
     }
     if (!p->cs_link)
     {
-        interp->result = "not connected";
-       return TCL_ERROR;
+        interp->result = "scan: not connected";
+        return TCL_ERROR;
     }
-    odr_reset (p->odr_out);
 
-    bib1.proto = PROTO_Z3950;
-    bib1.class = CLASS_ATTSET;
+    bib1.proto = p->protocol_type;
+    bib1.oclass = CLASS_ATTSET;
     bib1.value = VAL_BIB1;
 
-    apdu.which = Z_APDU_scanRequest;
-    apdu.u.scanRequest = &req;
-    req.referenceId = NULL;
-    req.num_databaseNames = p->set_inher.num_databaseNames;
-    req.databaseNames = p->set_inher.databaseNames;
-    req.attributeSet = oid_getoidbyent (&bib1);
+    apdu = zget_APDU (p->odr_out, Z_APDU_scanRequest);
+    req = apdu->u.scanRequest;
+
+    set_referenceId (p->odr_out, &req->referenceId, p->set_inher.referenceId);
+    req->num_databaseNames = p->set_inher.num_databaseNames;
+    req->databaseNames = p->set_inher.databaseNames;
+    req->attributeSet = oid_getoidbyent (&bib1);
 
 #if !CCL2RPN
-    if (!(req.termListAndStartPoint = p_query_scan (p->odr_out, argv[2])))
+    if (!(req->termListAndStartPoint = p_query_scan (p->odr_out, argv[2])))
     {
         Tcl_AppendResult (interp, "Syntax error in query", NULL);
-       return TCL_ERROR;
+        return TCL_ERROR;
     }
 #else
     rpn = ccl_find_str(p->bibset, argv[2], &r, &pos);
@@ -1939,38 +2787,47 @@ static int do_scan (void *o, Tcl_Interp *interp, int argc, char **argv)
     }
     ccl_pr_tree (rpn, stderr);
     fprintf (stderr, "\n");
-    if (!(req.termListAndStartPoint = ccl_scan_query (rpn)))
+    if (!(req->termListAndStartPoint = ccl_scan_query (rpn)))
         return TCL_ERROR;
 #endif
-    req.stepSize = &obj->stepSize;
-    req.numberOfTermsRequested = &obj->numberOfTermsRequested;
-    req.preferredPositionInResponse = &obj->preferredPositionInResponse;
-    logf (LOG_DEBUG, "stepSize=%d", *req.stepSize);
+    req->stepSize = &obj->stepSize;
+    req->numberOfTermsRequested = &obj->numberOfTermsRequested;
+    req->preferredPositionInResponse = &obj->preferredPositionInResponse;
+    logf (LOG_DEBUG, "stepSize=%d", *req->stepSize);
     logf (LOG_DEBUG, "numberOfTermsRequested=%d",
-          *req.numberOfTermsRequested);
+          *req->numberOfTermsRequested);
     logf (LOG_DEBUG, "preferredPositionInResponse=%d",
-          *req.preferredPositionInResponse);
+          *req->preferredPositionInResponse);
+    
+    return ir_tcl_send_APDU (interp, p, apdu, "scan", *argv);
+}
 
-    if (!z_APDU (p->odr_out, &apdup, 0))
-    {
-        interp->result = odr_errlist [odr_geterror (p->odr_out)];
-        odr_reset (p->odr_out);
-        return TCL_ERROR;
-    } 
-    p->sbuf = odr_getbuf (p->odr_out, &p->slen, NULL);
-    if ((r=cs_put (p->cs_link, p->sbuf, p->slen)) < 0)
-    {
-        interp->result = "cs_put failed in scan";
-        return TCL_ERROR;
-    }
-    else if (r == 1)
+/*
+ * do_scanResponse: add scan response handler
+ */
+static int do_scanResponse (void *o, Tcl_Interp *interp,
+                            int argc, char **argv)
+{
+    IrTcl_ScanObj *obj = o;
+
+    if (argc == 0)
     {
-        ir_select_add_write (cs_fileno(p->cs_link), p);
-        logf (LOG_DEBUG, "Sent part of scanRequest (%d bytes)", p->slen);
+        obj->scanResponse = NULL;
+        return TCL_OK;
     }
-    else
+    else if (argc == -1)
+        return ir_tcl_strdel (interp, &obj->scanResponse);
+    if (argc == 3)
     {
-        logf (LOG_DEBUG, "Whole scan request (%d bytes)", p->slen);
+        free (obj->scanResponse);
+        if (argv[2][0])
+        {
+            if (ir_tcl_strdup (interp, &obj->scanResponse, argv[2])
+                == TCL_ERROR)
+                return TCL_ERROR;
+        }
+        else
+            obj->scanResponse = NULL;
     }
     return TCL_OK;
 }
@@ -1981,7 +2838,7 @@ static int do_scan (void *o, Tcl_Interp *interp, int argc, char **argv)
 static int do_stepSize (void *obj, Tcl_Interp *interp,
                         int argc, char **argv)
 {
-    IRScanObj *p = obj;
+    IrTcl_ScanObj *p = obj;
     if (argc <= 0)
     {
         p->stepSize = 0;
@@ -1996,7 +2853,7 @@ static int do_stepSize (void *obj, Tcl_Interp *interp,
 static int do_numberOfTermsRequested (void *obj, Tcl_Interp *interp,
                                       int argc, char **argv)
 {
-    IRScanObj *p = obj;
+    IrTcl_ScanObj *p = obj;
 
     if (argc <= 0)
     {
@@ -2013,7 +2870,7 @@ static int do_numberOfTermsRequested (void *obj, Tcl_Interp *interp,
 static int do_preferredPositionInResponse (void *obj, Tcl_Interp *interp,
                                            int argc, char **argv)
 {
-    IRScanObj *p = obj;
+    IrTcl_ScanObj *p = obj;
 
     if (argc <= 0)
     {
@@ -2029,7 +2886,7 @@ static int do_preferredPositionInResponse (void *obj, Tcl_Interp *interp,
 static int do_scanStatus (void *obj, Tcl_Interp *interp,
                           int argc, char **argv)
 {
-    IRScanObj *p = obj;
+    IrTcl_ScanObj *p = obj;
 
     if (argc <= 0)
         return TCL_OK;
@@ -2042,7 +2899,7 @@ static int do_scanStatus (void *obj, Tcl_Interp *interp,
 static int do_numberOfEntriesReturned (void *obj, Tcl_Interp *interp,
                                        int argc, char **argv)
 {
-    IRScanObj *p = obj;
+    IrTcl_ScanObj *p = obj;
 
     if (argc <= 0)
         return TCL_OK;
@@ -2055,7 +2912,7 @@ static int do_numberOfEntriesReturned (void *obj, Tcl_Interp *interp,
 static int do_positionOfTerm (void *obj, Tcl_Interp *interp,
                               int argc, char **argv)
 {
-    IRScanObj *p = obj;
+    IrTcl_ScanObj *p = obj;
 
     if (argc <= 0)
         return TCL_OK;
@@ -2067,30 +2924,32 @@ static int do_positionOfTerm (void *obj, Tcl_Interp *interp,
  */
 static int do_scanLine (void *obj, Tcl_Interp *interp, int argc, char **argv)
 {
-    IRScanObj *p = obj;
+    IrTcl_ScanObj *p = obj;
     int i;
     char numstr[20];
 
     if (argc == 0)
     {
         p->entries_flag = 0;
-       p->entries = NULL;
-       p->nonSurrogateDiagnostics = NULL;
-       return TCL_OK;
+        p->entries = NULL;
+        p->nonSurrogateDiagnosticNum = 0;
+        p->nonSurrogateDiagnosticList = 0;
+        return TCL_OK;
     }
     else if (argc == -1)
     {
         p->entries_flag = 0;
-       /* release entries */
-       p->entries = NULL;
-       /* release non diagnostics */
-       p->nonSurrogateDiagnostics = NULL;
-       return TCL_OK;
+        /* release entries */
+        p->entries = NULL;
+
+        ir_deleteDiags (&p->nonSurrogateDiagnosticList, 
+                        &p->nonSurrogateDiagnosticNum);
+        return TCL_OK;
     }
     if (argc != 3)
     {
         interp->result = "wrong # args";
-       return TCL_ERROR;
+        return TCL_ERROR;
     }
     if (Tcl_GetInt (interp, argv[2], &i) == TCL_ERROR)
         return TCL_ERROR;
@@ -2101,24 +2960,25 @@ static int do_scanLine (void *obj, Tcl_Interp *interp, int argc, char **argv)
     {
     case Z_Entry_termInfo:
         Tcl_AppendElement (interp, "T");
-       if (p->entries[i].u.term.buf)
-           Tcl_AppendElement (interp, p->entries[i].u.term.buf);
-       else
-           Tcl_AppendElement (interp, "");
-       sprintf (numstr, "%d", p->entries[i].u.term.globalOccurrences);
-       Tcl_AppendElement (interp, numstr);
-       break;
+        if (p->entries[i].u.term.buf)
+            Tcl_AppendElement (interp, p->entries[i].u.term.buf);
+        else
+            Tcl_AppendElement (interp, "");
+        sprintf (numstr, "%d", p->entries[i].u.term.globalOccurrences);
+        Tcl_AppendElement (interp, numstr);
+        break;
     case Z_Entry_surrogateDiagnostic:
-        return 
-           mk_nonSurrogateDiagnostics (interp, p->entries[i].u.diag.condition,
-                                       p->entries[i].u.diag.addinfo);
-       break;
+        Tcl_AppendElement (interp, "SD");
+        return ir_diagResult (interp, p->entries[i].u.diag.list,
+                              p->entries[i].u.diag.num);
+        break;
     }
     return TCL_OK;
 }
 
-static IRMethod ir_scan_method_tab[] = {
+static IrTcl_Method ir_scan_method_tab[] = {
     { 0, "scan",                    do_scan },
+    { 0, "scanResponse",            do_scanResponse },
     { 0, "stepSize",                do_stepSize },
     { 0, "numberOfTermsRequested",  do_numberOfTermsRequested },
     { 0, "preferredPositionInResponse", do_preferredPositionInResponse },
@@ -2135,7 +2995,7 @@ static IRMethod ir_scan_method_tab[] = {
 static int ir_scan_obj_method (ClientData clientData, Tcl_Interp *interp,
                                int argc, char **argv)
 {
-    IRMethods tabs[3];
+    IrTcl_Methods tabs[2];
 
     if (argc < 2)
     {
@@ -2154,7 +3014,15 @@ static int ir_scan_obj_method (ClientData clientData, Tcl_Interp *interp,
  */
 static void ir_scan_obj_delete (ClientData clientData)
 {
-    free ( (void*) clientData);
+    IrTcl_Methods tabs[2];
+    IrTcl_ScanObj *obj = clientData;
+
+    tabs[0].tab = ir_scan_method_tab;
+    tabs[0].obj = obj;
+    tabs[1].tab = NULL;
+
+    ir_method (NULL, -1, NULL, tabs);
+    free (obj);
 }
 
 /* 
@@ -2164,18 +3032,21 @@ static int ir_scan_obj_mk (ClientData clientData, Tcl_Interp *interp,
                            int argc, char **argv)
 {
     Tcl_CmdInfo parent_info;
-    IRScanObj *obj;
-    IRMethods tabs[3];
+    IrTcl_ScanObj *obj;
+    IrTcl_Methods tabs[2];
 
-    if (argc != 2)
+    if (argc != 3)
     {
         interp->result = "wrong # args";
         return TCL_ERROR;
     }
-    if (get_parent_info (interp, argv[1], &parent_info, NULL) == TCL_ERROR)
-        return TCL_ERROR;
-    if (!(obj = ir_malloc (interp, sizeof(*obj))))
+    if (!Tcl_GetCommandInfo (interp, argv[2], &parent_info))
+    {
+        interp->result = "No parent";
         return TCL_ERROR;
+    }
+    obj = ir_tcl_malloc (sizeof(*obj));
+    obj->parent = (IrTcl_Obj *) parent_info.clientData;
 
     tabs[0].tab = ir_scan_method_tab;
     tabs[0].obj = obj;
@@ -2183,16 +3054,6 @@ static int ir_scan_obj_mk (ClientData clientData, Tcl_Interp *interp,
 
     if (ir_method (interp, 0, NULL, tabs) == TCL_ERROR)
         return TCL_ERROR;
-#if 0
-    obj->stepSize = 0;
-    obj->numberOfTermsRequested = 20;
-    obj->preferredPositionInResponse = 1;
-
-    obj->entries = NULL;
-    obj->nonSurrogateDiagnostics = NULL;
-#endif
-
-    obj->parent = (IRObj *) parent_info.clientData;
     Tcl_CreateCommand (interp, argv[1], ir_scan_obj_method,
                        (ClientData) obj, ir_scan_obj_delete);
     return TCL_OK;
@@ -2202,7 +3063,7 @@ static int ir_scan_obj_mk (ClientData clientData, Tcl_Interp *interp,
 
 static void ir_initResponse (void *obj, Z_InitResponse *initrs)
 {
-    IRObj *p = obj;
+    IrTcl_Obj *p = obj;
 
     p->initResult = *initrs->result ? 1 : 0;
     if (!*initrs->result)
@@ -2210,14 +3071,16 @@ static void ir_initResponse (void *obj, Z_InitResponse *initrs)
     else
         logf (LOG_DEBUG, "Connection accepted by target");
 
+    get_referenceId (&p->set_inher.referenceId, initrs->referenceId);
+
     free (p->targetImplementationId);
-    ir_strdup (p->interp, &p->targetImplementationId,
+    ir_tcl_strdup (p->interp, &p->targetImplementationId,
                initrs->implementationId);
     free (p->targetImplementationName);
-    ir_strdup (p->interp, &p->targetImplementationName,
+    ir_tcl_strdup (p->interp, &p->targetImplementationName,
                initrs->implementationName);
     free (p->targetImplementationVersion);
-    ir_strdup (p->interp, &p->targetImplementationVersion,
+    ir_tcl_strdup (p->interp, &p->targetImplementationVersion,
                initrs->implementationVersion);
 
     p->maximumRecordSize = *initrs->maximumRecordSize;
@@ -2234,9 +3097,9 @@ static void ir_initResponse (void *obj, Z_InitResponse *initrs)
 
         if (initrs->userInformationField->which == ODR_EXTERNAL_octet && 
             (p->userInformationField =
-             malloc ((len = 
-                      initrs->userInformationField->u.octet_aligned->len)
-                     +1)))
+             ir_tcl_malloc ((len = 
+                             initrs->userInformationField->
+                             u.octet_aligned->len) +1)))
         {
             memcpy (p->userInformationField,
                     initrs->userInformationField->u.octet_aligned->buf,
@@ -2246,34 +3109,57 @@ static void ir_initResponse (void *obj, Z_InitResponse *initrs)
     }
 }
 
-static void ir_handleRecords (void *o, Z_Records *zrs)
+static void ir_deleteDiags (IrTcl_Diagnostic **dst_list, int *dst_num)
 {
-    IRObj *p = o;
-    IRSetObj *setobj = p->set_child;
+    int i;
+    for (i = 0; i<*dst_num; i++)
+        free (dst_list[i]->addinfo);
+    free (*dst_list);
+    *dst_list = NULL;
+    *dst_num = 0;
+}
 
-    setobj->which = zrs->which;
-    setobj->recordFlag = 1;
-    if (zrs->which == Z_Records_NSD)
+static void ir_handleDiags (IrTcl_Diagnostic **dst_list, int *dst_num,
+                    Z_DiagRec **list, int num)
+{
+    int i;
+    char *addinfo;
+
+    *dst_num = num;
+    *dst_list = ir_tcl_malloc (sizeof(**dst_list) * num);
+    for (i = 0; i<num; i++)
     {
-        const char *addinfo;
-        
-        setobj->numberOfRecordsReturned = 0;
-        setobj->condition = *zrs->u.nonSurrogateDiagnostic->condition;
-        free (setobj->addinfo);
-        setobj->addinfo = NULL;
-        addinfo = zrs->u.nonSurrogateDiagnostic->addinfo;
-        if (addinfo && (setobj->addinfo = malloc (strlen(addinfo) + 1)))
-            strcpy (setobj->addinfo, addinfo);
-        logf (LOG_DEBUG, "Diagnostic response. %s (%d): %s",
-              diagbib1_str (setobj->condition),
-              setobj->condition,
-              setobj->addinfo ? setobj->addinfo : "");
+        switch (list[i]->which)
+        {
+        case Z_DiagRec_defaultFormat:
+            (*dst_list)[i].condition = *list[i]->u.defaultFormat->condition;
+            addinfo = list[i]->u.defaultFormat->addinfo;
+            if (addinfo && 
+                ((*dst_list)[i].addinfo = ir_tcl_malloc (strlen(addinfo)+1)))
+                strcpy ((*dst_list)[i].addinfo, addinfo);
+            break;
+        default:
+            (*dst_list)[i].addinfo = NULL;
+            (*dst_list)[i].condition = 0;
+        }
     }
-    else
+}
+
+static void ir_handleRecords (void *o, Z_Records *zrs, IrTcl_SetObj *setobj,
+                              const char *elements)
+{
+    IrTcl_Obj *p = o;
+
+    int offset;
+    IrTcl_RecordList *rl;
+
+    setobj->which = zrs->which;
+    setobj->recordFlag = 1;
+    
+    ir_deleteDiags (&setobj->nonSurrogateDiagnosticList,
+                    &setobj->nonSurrogateDiagnosticNum);
+    if (zrs->which == Z_Records_DBOSD)
     {
-        int offset;
-        IRRecordList *rl;
-        
         setobj->numberOfRecordsReturned = 
             zrs->u.databaseOrSurDiagnostics->num_records;
         logf (LOG_DEBUG, "Got %d records", setobj->numberOfRecordsReturned);
@@ -2281,79 +3167,134 @@ static void ir_handleRecords (void *o, Z_Records *zrs)
         {
             rl = new_IR_record (setobj, setobj->start + offset,
                                 zrs->u.databaseOrSurDiagnostics->
-                                records[offset]->which);
+                                records[offset]->which,
+                                elements);
             if (rl->which == Z_NamePlusRecord_surrogateDiagnostic)
             {
-                Z_DiagRec *diagrec;
-                
-                diagrec = zrs->u.databaseOrSurDiagnostics->
-                    records[offset]->u.surrogateDiagnostic;
-                
-                rl->u.diag.condition = *diagrec->condition;
-                if (diagrec->addinfo && (rl->u.diag.addinfo =
-                                         malloc (strlen (diagrec->addinfo)+1)))
-                    strcpy (rl->u.diag.addinfo, diagrec->addinfo);
-            }
+                ir_handleDiags (&rl->u.surrogateDiagnostics.list,
+                                &rl->u.surrogateDiagnostics.num,
+                                &zrs->u.databaseOrSurDiagnostics->
+                                records[offset]->u.surrogateDiagnostic,
+                                1);
+            } 
             else
             {
                 Z_DatabaseRecord *zr; 
-                Odr_external *oe;
+                Z_External *oe;
+                struct oident *ident;
                 
                 zr = zrs->u.databaseOrSurDiagnostics->records[offset]
                     ->u.databaseRecord;
-                oe = (Odr_external*) zr;
-               rl->u.dbrec.size = zr->u.octet_aligned->len;
+                oe = (Z_External*) zr;
+                rl->u.dbrec.size = zr->u.octet_aligned->len;
+
+                if ((ident = oid_getentbyoid (oe->direct_reference)))
+                    rl->u.dbrec.type = ident->value;
+                else
+                    rl->u.dbrec.type = VAL_USMARC;
+
                 if (oe->which == ODR_EXTERNAL_octet && rl->u.dbrec.size > 0)
                 {
-                    const char *buf = (char*) zr->u.octet_aligned->buf;
-                    if ((rl->u.dbrec.buf = malloc (rl->u.dbrec.size)))
-                       memcpy (rl->u.dbrec.buf, buf, rl->u.dbrec.size);
+                    char *buf = (char*) zr->u.octet_aligned->buf;
+                    if ((rl->u.dbrec.buf = ir_tcl_malloc (rl->u.dbrec.size)))
+                        memcpy (rl->u.dbrec.buf, buf, rl->u.dbrec.size);
+                }
+                else if (rl->u.dbrec.type == VAL_SUTRS && 
+                         oe->which == Z_External_sutrs)
+                {
+                    odr_setbuf (p->odr_in, (char*) oe->u.single_ASN1_type->buf,
+                                oe->u.single_ASN1_type->len, 0);
+                    if ((rl->u.dbrec.buf = ir_tcl_malloc (oe->u.sutrs->len+1)))
+                    {
+                        memcpy (rl->u.dbrec.buf, oe->u.sutrs->buf,
+                                oe->u.sutrs->len);
+                        rl->u.dbrec.buf[oe->u.sutrs->len] = '\0';
+                    }
+                    rl->u.dbrec.size = oe->u.sutrs->len;
+                }
+                else if (rl->u.dbrec.type == VAL_GRS1 && 
+                         oe->which == Z_External_grs1)
+                {
+                    ir_tcl_read_grs (oe->u.grs1, &rl->u.dbrec.u.grs1);
+                    rl->u.dbrec.buf = NULL;
                 }
                 else
                     rl->u.dbrec.buf = NULL;
             }
         }
     }
+    else if (zrs->which == Z_Records_multipleNSD)
+    {
+        logf (LOG_DEBUG, "multipleNonSurrogateDiagnostic %d",
+              zrs->u.multipleNonSurDiagnostics->num_diagRecs);
+        setobj->numberOfRecordsReturned = 0;
+        ir_handleDiags (&setobj->nonSurrogateDiagnosticList,
+                        &setobj->nonSurrogateDiagnosticNum,
+                        zrs->u.multipleNonSurDiagnostics->diagRecs,
+                        zrs->u.multipleNonSurDiagnostics->num_diagRecs);
+    }
+    else
+    {
+        logf (LOG_DEBUG, "NonSurrogateDiagnostic");
+        setobj->numberOfRecordsReturned = 0;
+        ir_handleDiags (&setobj->nonSurrogateDiagnosticList,
+                        &setobj->nonSurrogateDiagnosticNum,
+                        &zrs->u.nonSurrogateDiagnostic,
+                        1);
+    }
 }
 
-static void ir_searchResponse (void *o, Z_SearchResponse *searchrs)
+static void ir_searchResponse (void *o, Z_SearchResponse *searchrs,
+                               IrTcl_SetObj *setobj)
 {    
-    IRObj *p = o;
-    IRSetObj *setobj = p->set_child;
     Z_Records *zrs = searchrs->records;
 
-    if (setobj)
+    logf (LOG_DEBUG, "Received search response");
+    if (!setobj)
     {
-        setobj->searchStatus = searchrs->searchStatus ? 1 : 0;
-        setobj->resultCount = *searchrs->resultCount;
-        if (searchrs->presentStatus)
-            setobj->presentStatus = *searchrs->presentStatus;
-        if (searchrs->nextResultSetPosition)
-            setobj->nextResultSetPosition = *searchrs->nextResultSetPosition;
+        logf (LOG_DEBUG, "Search response, no object!");
+        return;
+    }
+    setobj->searchStatus = searchrs->searchStatus ? 1 : 0;
+    get_referenceId (&setobj->set_inher.referenceId, searchrs->referenceId);
+    setobj->resultCount = *searchrs->resultCount;
+    if (searchrs->presentStatus)
+        setobj->presentStatus = *searchrs->presentStatus;
+    if (searchrs->nextResultSetPosition)
+        setobj->nextResultSetPosition = *searchrs->nextResultSetPosition;
 
-        logf (LOG_DEBUG, "Search response %d, %d hits", 
-              setobj->searchStatus, setobj->resultCount);
-        if (zrs)
-            ir_handleRecords (o, zrs);
-        else
-            setobj->recordFlag = 0;
+    logf (LOG_DEBUG, "Search response %d, %d hits", 
+          setobj->searchStatus, setobj->resultCount);
+    if (zrs)
+    {
+        const char *es;
+        if (setobj->resultCount <= setobj->set_inher.smallSetUpperBound)
+            es = setobj->set_inher.smallSetElementSetNames;
+        else 
+            es = setobj->set_inher.mediumSetElementSetNames;
+        ir_handleRecords (o, zrs, setobj, es);
     }
     else
-        logf (LOG_DEBUG, "Search response, no object!");
+        setobj->recordFlag = 0;
 }
 
 
-static void ir_presentResponse (void *o, Z_PresentResponse *presrs)
+static void ir_presentResponse (void *o, Z_PresentResponse *presrs,
+                                IrTcl_SetObj *setobj)
 {
-    IRObj *p = o;
-    IRSetObj *setobj = p->set_child;
     Z_Records *zrs = presrs->records;
     
-    logf (LOG_DEBUG, "Received presentResponse");
+    logf (LOG_DEBUG, "Received present response");
+    if (!setobj)
+    {
+        logf (LOG_DEBUG, "Present response, no object!");
+        return;
+    }
     setobj->presentStatus = *presrs->presentStatus;
+    get_referenceId (&setobj->set_inher.referenceId, presrs->referenceId);
     setobj->nextResultSetPosition = *presrs->nextResultSetPosition;
     if (zrs)
-        ir_handleRecords (o, zrs);
+        ir_handleRecords (o, zrs, setobj, setobj->set_inher.elementSetNames);
     else
     {
         setobj->recordFlag = 0;
@@ -2361,13 +3302,14 @@ static void ir_presentResponse (void *o, Z_PresentResponse *presrs)
     }
 }
 
-static void ir_scanResponse (void *o, Z_ScanResponse *scanrs)
+static void ir_scanResponse (void *o, Z_ScanResponse *scanrs,
+                             IrTcl_ScanObj *scanobj)
 {
-    IRObj *p = o;
-    IRScanObj *scanobj = p->scan_child;
+    IrTcl_Obj *p = o;
     
     logf (LOG_DEBUG, "Received scanResponse");
 
+    get_referenceId (&p->set_inher.referenceId, scanrs->referenceId);
     scanobj->scanStatus = *scanrs->scanStatus;
     logf (LOG_DEBUG, "scanStatus=%d", scanobj->scanStatus);
 
@@ -2387,65 +3329,64 @@ static void ir_scanResponse (void *o, Z_ScanResponse *scanrs)
 
     free (scanobj->entries);
     scanobj->entries = NULL;
-    free (scanobj->nonSurrogateDiagnostics);
-    scanobj->nonSurrogateDiagnostics = NULL;
 
+    ir_deleteDiags (&scanobj->nonSurrogateDiagnosticList,
+                    &scanobj->nonSurrogateDiagnosticNum);
     if (scanrs->entries)
     {
         int i;
-       Z_Entry *ze;
+        Z_Entry *ze;
 
         scanobj->entries_flag = 1;
         scanobj->which = scanrs->entries->which;
-       switch (scanobj->which)
-       {
-       case Z_ListEntries_entries:
-           scanobj->num_entries = scanrs->entries->u.entries->num_entries;
-           scanobj->entries = malloc (scanobj->num_entries * 
-                                      sizeof(*scanobj->entries));
+        switch (scanobj->which)
+        {
+        case Z_ListEntries_entries:
+            scanobj->num_entries = scanrs->entries->u.entries->num_entries;
+            scanobj->entries = ir_tcl_malloc (scanobj->num_entries * 
+                                       sizeof(*scanobj->entries));
             for (i=0; i<scanobj->num_entries; i++)
-           {
-               ze = scanrs->entries->u.entries->entries[i];
+            {
+                ze = scanrs->entries->u.entries->entries[i];
                 scanobj->entries[i].which = ze->which;
-               switch (ze->which)
-               {
-               case Z_Entry_termInfo:
-                   if (ze->u.termInfo->term->which == Z_Term_general)
-                   {
+                switch (ze->which)
+                {
+                case Z_Entry_termInfo:
+                    if (ze->u.termInfo->term->which == Z_Term_general)
+                    {
                         int l = ze->u.termInfo->term->u.general->len;
-                        scanobj->entries[i].u.term.buf = malloc (1+l);
-                       memcpy (scanobj->entries[i].u.term.buf, 
-                               ze->u.termInfo->term->u.general->buf,
+                        scanobj->entries[i].u.term.buf = ir_tcl_malloc (1+l);
+                        memcpy (scanobj->entries[i].u.term.buf, 
+                                ze->u.termInfo->term->u.general->buf,
                                 l);
                         scanobj->entries[i].u.term.buf[l] = '\0';
-                   }
-                   else
+                    }
+                    else
                         scanobj->entries[i].u.term.buf = NULL;
-                   if (ze->u.termInfo->globalOccurrences)
-                       scanobj->entries[i].u.term.globalOccurrences = 
-                           *ze->u.termInfo->globalOccurrences;
-                   else
-                       scanobj->entries[i].u.term.globalOccurrences = 0;
+                    if (ze->u.termInfo->globalOccurrences)
+                        scanobj->entries[i].u.term.globalOccurrences = 
+                            *ze->u.termInfo->globalOccurrences;
+                    else
+                        scanobj->entries[i].u.term.globalOccurrences = 0;
                     break;
-               case Z_Entry_surrogateDiagnostic:
-                   scanobj->entries[i].u.diag.addinfo = 
-                           malloc (1+strlen(ze->u.surrogateDiagnostic->
-                                            addinfo));
-                    strcpy (scanobj->entries[i].u.diag.addinfo,
-                           ze->u.surrogateDiagnostic->addinfo);
-                   scanobj->entries[i].u.diag.condition = 
-                       *ze->u.surrogateDiagnostic->condition;
-                   break;
-               }
-           }
+                case Z_Entry_surrogateDiagnostic:
+                    ir_handleDiags (&scanobj->entries[i].u.diag.list,
+                                    &scanobj->entries[i].u.diag.num,
+                                    &ze->u.surrogateDiagnostic,
+                                    1);
+                    break;
+                }
+            }
             break;
-       case Z_ListEntries_nonSurrogateDiagnostics:
-           scanobj->num_diagRecs = scanrs->entries->
-                                 u.nonSurrogateDiagnostics->num_diagRecs;
-           scanobj->nonSurrogateDiagnostics = malloc (scanobj->num_diagRecs *
-                                 sizeof(*scanobj->nonSurrogateDiagnostics));
+        case Z_ListEntries_nonSurrogateDiagnostics:
+            ir_handleDiags (&scanobj->nonSurrogateDiagnosticList,
+                            &scanobj->nonSurrogateDiagnosticNum,
+                            scanrs->entries->u.nonSurrogateDiagnostics->
+                            diagRecs,
+                            scanrs->entries->u.nonSurrogateDiagnostics->
+                            num_diagRecs);
             break;
-       }
+        }
     }
     else
         scanobj->entries_flag = 0;
@@ -2454,151 +3395,270 @@ static void ir_scanResponse (void *o, Z_ScanResponse *scanrs)
 /*
  * ir_select_read: handle incoming packages
  */
-void ir_select_read (ClientData clientData)
+static void ir_select_read (ClientData clientData)
 {
-    IRObj *p = clientData;
+    IrTcl_Obj *p = clientData;
     Z_APDU *apdu;
     int r;
+    IrTcl_Request *rq;
+    char *object_name;
+    Tcl_CmdInfo cmd_info;
+    const char *apdu_call;
 
-    if (p->connectFlag)
+    logf(LOG_DEBUG, "Read handler fd=%d", cs_fileno(p->cs_link));
+    if (p->state == IR_TCL_R_Connecting)
     {
+       logf(LOG_DEBUG, "Connect handler");
         r = cs_rcvconnect (p->cs_link);
         if (r == 1)
+        {
+            logf (LOG_WARN, "cs_rcvconnect returned 1");
             return;
-        p->connectFlag = 0;
+        }
+        p->state = IR_TCL_R_Idle;
+#if IRTCL_GENERIC_FILES
+        ir_select_remove_write (p->csFile, p);
+#else
         ir_select_remove_write (cs_fileno (p->cs_link), p);
+#endif
         if (r < 0)
         {
             logf (LOG_DEBUG, "cs_rcvconnect error");
             if (p->failback)
-                Tcl_Eval (p->interp, p->failback);
+            {
+                p->failInfo = IR_TCL_FAIL_CONNECT;
+                IrTcl_eval (p->interp, p->failback);
+            }
             do_disconnect (p, NULL, 2, NULL);
             return;
         }
+        p->state = IR_TCL_R_Idle;
         if (p->callback)
-           Tcl_Eval (p->interp, p->callback);
+            IrTcl_eval (p->interp, p->callback);
+        if (p->cs_link && p->request_queue && p->state == IR_TCL_R_Idle)
+            ir_tcl_send_q (p, p->request_queue, "x");
         return;
     }
     do
     {
-       /* signal one more use of ir object - callbacks must not
-          release the ir memory (p pointer) */
-       ++(p->ref_count);
+        /* signal one more use of ir object - callbacks must not
+           release the ir memory (p pointer) */
+        p->state = IR_TCL_R_Reading;
+        ++(p->ref_count);
+
+        /* read incoming APDU */
         if ((r=cs_get (p->cs_link, &p->buf_in, &p->len_in)) <= 0)
         {
             logf (LOG_DEBUG, "cs_get failed, code %d", r);
+#if IRTCL_GENERIC_FILES
+            ir_select_remove (p->csFile, p);
+#else
             ir_select_remove (cs_fileno (p->cs_link), p);
-            if (p->failback)
-                Tcl_Eval (p->interp, p->failback);
+#endif
             do_disconnect (p, NULL, 2, NULL);
-
-           /* relase ir object now if callback deleted it */
-           ir_obj_delete (p);
+            if (p->failback)
+            {
+                p->failInfo = IR_TCL_FAIL_READ;
+                IrTcl_eval (p->interp, p->failback);
+            }
+            /* release ir object now if callback deleted it */
+            ir_obj_delete (p);
             return;
         }        
         if (r == 1)
+       {
+           logf(LOG_DEBUG, "PDU Fraction read");
             return ;
+       }
+        /* got complete APDU. Now decode */
+        p->apduLen = r;
+        p->apduOffset = -1;
         odr_setbuf (p->odr_in, p->buf_in, r, 0);
-        logf (LOG_DEBUG, "cs_get ok, got %d", r);
+        logf (LOG_DEBUG, "cs_get ok, total size %d", r);
         if (!z_APDU (p->odr_in, &apdu, 0))
         {
-            logf (LOG_DEBUG, "%s", odr_errlist [odr_geterror (p->odr_in)]);
-            if (p->failback)
-                Tcl_Eval (p->interp, p->failback);
+            logf (LOG_DEBUG, "cs_get failed: %s",
+               odr_errmsg (odr_geterror (p->odr_in)));
             do_disconnect (p, NULL, 2, NULL);
-
-           /* relase ir object now if callback deleted it */
-           ir_obj_delete (p);
+            if (p->failback)
+            {
+                p->failInfo = IR_TCL_FAIL_IN_APDU;
+                p->apduOffset = odr_offset (p->odr_in);
+                IrTcl_eval (p->interp, p->failback);
+            }
+            /* release ir object now if failback deleted it */
+            ir_obj_delete (p);
             return;
         }
-        switch(apdu->which)
+       logf(LOG_DEBUG, "Decoded ok");
+        /* handle APDU and invoke callback */
+        rq = p->request_queue;
+        if (!rq)
         {
-        case Z_APDU_initResponse:
-            ir_initResponse (p, apdu->u.initResponse);
-            break;
-        case Z_APDU_searchResponse:
-            ir_searchResponse (p, apdu->u.searchResponse);
-            break;
-        case Z_APDU_presentResponse:
-            ir_presentResponse (p, apdu->u.presentResponse);
-            break;
-        case Z_APDU_scanResponse:
-            ir_scanResponse (p, apdu->u.scanResponse);
-            break;
-        default:
-            logf (LOG_WARN, "Received unknown APDU type (%d)", apdu->which);
-            if (p->failback)
-                Tcl_Eval (p->interp, p->failback);
-            do_disconnect (p, NULL, 2, NULL);
+            logf (LOG_FATAL, "Internal error. No queue entry");
+            exit (1);
+        }
+        object_name = rq->object_name;
+        logf (LOG_DEBUG, "getCommandInfo (%s)", object_name);
+        apdu_call = NULL;
+        if (Tcl_GetCommandInfo (p->interp, object_name, &cmd_info))
+        {
+            switch(apdu->which)
+            {
+            case Z_APDU_initResponse:
+                p->eventType = "init";
+                ir_initResponse (p, apdu->u.initResponse);
+               apdu_call = p->initResponse;
+                break;
+            case Z_APDU_searchResponse:
+                p->eventType = "search";
+                ir_searchResponse (p, apdu->u.searchResponse,
+                                   (IrTcl_SetObj *) cmd_info.clientData);
+                apdu_call = ((IrTcl_SetObj *) 
+                             cmd_info.clientData)->searchResponse;
+                break;
+            case Z_APDU_presentResponse:
+                p->eventType = "present";
+                ir_presentResponse (p, apdu->u.presentResponse,
+                                    (IrTcl_SetObj *) cmd_info.clientData);
+                apdu_call = ((IrTcl_SetObj *) 
+                             cmd_info.clientData)->presentResponse;
+                break;
+            case Z_APDU_scanResponse:
+                p->eventType = "scan";
+                ir_scanResponse (p, apdu->u.scanResponse, 
+                                 (IrTcl_ScanObj *) cmd_info.clientData);
+                apdu_call = ((IrTcl_ScanObj *) 
+                             cmd_info.clientData)->scanResponse;
+                break;
+            default:
+                logf (LOG_WARN, "Received unknown APDU type (%d)",
+                      apdu->which);
+                do_disconnect (p, NULL, 2, NULL);
+                if (p->failback)
+                {
+                    p->failInfo = IR_TCL_FAIL_UNKNOWN_APDU;
+                    IrTcl_eval (p->interp, p->failback);
+                }
+                return;
+            }
         }
+        p->request_queue = rq->next;
+        p->state = IR_TCL_R_Idle;
+       
+        if (apdu_call)
+            IrTcl_eval (p->interp, apdu_call);
+        else if (rq->callback)
+            IrTcl_eval (p->interp, rq->callback);
+        free (rq->buf_out);
+        free (rq->callback);
+        free (rq->object_name);
+        free (rq);
         odr_reset (p->odr_in);
-        if (p->callback)
-           Tcl_Eval (p->interp, p->callback);
-       if (p->ref_count == 1)
-       {
-           ir_obj_delete (p);
-           return;
-       }
-       --(p->ref_count);
-    } while (p->cs_link && cs_more (p->cs_link));    
+        if (p->ref_count == 1)
+        {
+            ir_obj_delete (p);
+            return;
+        }
+        --(p->ref_count);
+    } while (p->cs_link && cs_more (p->cs_link));
+    if (p->cs_link && p->request_queue && p->state == IR_TCL_R_Idle)
+        ir_tcl_send_q (p, p->request_queue, "x");
 }
 
 /*
  * ir_select_write: handle outgoing packages - not yet written.
  */
-void ir_select_write (ClientData clientData)
+static void ir_select_write (ClientData clientData)
 {
-    IRObj *p = clientData;
+    IrTcl_Obj *p = clientData;
     int r;
+    IrTcl_Request *rq;
 
-    logf (LOG_DEBUG, "In write handler");
-    if (p->connectFlag)
+    logf (LOG_DEBUG, "Write handler fd=%d", cs_fileno(p->cs_link));
+    if (p->state == IR_TCL_R_Connecting)
     {
+       logf(LOG_DEBUG, "Connect handler");
         r = cs_rcvconnect (p->cs_link);
         if (r == 1)
             return;
-        p->connectFlag = 0;
+        p->state = IR_TCL_R_Idle;
         if (r < 0)
         {
             logf (LOG_DEBUG, "cs_rcvconnect error");
+#if IRTCL_GENERIC_FILES
+            ir_select_remove_write (p->csFile, p);
+#else
             ir_select_remove_write (cs_fileno (p->cs_link), p);
+#endif
             if (p->failback)
-                Tcl_Eval (p->interp, p->failback);
+            {
+                p->failInfo = IR_TCL_FAIL_CONNECT;
+                IrTcl_eval (p->interp, p->failback);
+            }
             do_disconnect (p, NULL, 2, NULL);
             return;
         }
+#if IRTCL_GENERIC_FILES
+        ir_select_remove_write (p->csFile, p);
+#else
         ir_select_remove_write (cs_fileno (p->cs_link), p);
+#endif
         if (p->callback)
-           Tcl_Eval (p->interp, p->callback);
+            IrTcl_eval (p->interp, p->callback);
         return;
     }
-    if ((r=cs_put (p->cs_link, p->sbuf, p->slen)) < 0)
-    {   
-        logf (LOG_DEBUG, "select write fail");
+    rq = p->request_queue;
+    if (!rq || !rq->buf_out)
+        return;
+    assert (rq);
+    if ((r=cs_put (p->cs_link, rq->buf_out, rq->len_out)) < 0)
+    {
+        logf (LOG_DEBUG, "cs_put write fail");
         if (p->failback)
-            Tcl_Eval (p->interp, p->failback);
+        {
+            p->failInfo = IR_TCL_FAIL_WRITE;
+            IrTcl_eval (p->interp, p->failback);
+        }
+        free (rq->buf_out);
+        rq->buf_out = NULL;
         do_disconnect (p, NULL, 2, NULL);
     }
     else if (r == 0)            /* remove select bit */
     {
+       logf(LOG_DEBUG, "Write completed");
+        p->state = IR_TCL_R_Waiting;
+#if IRTCL_GENERIC_FILES
+        ir_select_remove_write (p->csFile, p);
+#else
         ir_select_remove_write (cs_fileno (p->cs_link), p);
+#endif
+        free (rq->buf_out);
+        rq->buf_out = NULL;
     }
 }
 
+static void ir_select_notify (ClientData clientData, int r, int w, int e)
+{
+    if (r)
+        ir_select_read (clientData);
+    if (w)
+        ir_select_write (clientData);
+}
+
 /* ------------------------------------------------------- */
 
 /*
- * ir_tcl_init: Registration of TCL commands.
+ * Irtcl_init: Registration of TCL commands.
  */
-int ir_tcl_init (Tcl_Interp *interp)
+int Irtcl_Init (Tcl_Interp *interp)
 {
     Tcl_CreateCommand (interp, "ir", ir_obj_mk, (ClientData) NULL,
                        (Tcl_CmdDeleteProc *) NULL);
     Tcl_CreateCommand (interp, "ir-set", ir_set_obj_mk,
-                      (ClientData) NULL, (Tcl_CmdDeleteProc *) NULL);
+                       (ClientData) NULL, (Tcl_CmdDeleteProc *) NULL);
     Tcl_CreateCommand (interp, "ir-scan", ir_scan_obj_mk,
-                      (ClientData) NULL, (Tcl_CmdDeleteProc *) NULL);
+                       (ClientData) NULL, (Tcl_CmdDeleteProc *) NULL);
     return TCL_OK;
 }
 
-