Added init command for yaz-client which sends extra init request
[yaz-moved-to-github.git] / client / client.c
1 /* 
2  * Copyright (c) 1995-2004, Index Data
3  * See the file LICENSE for details.
4  *
5  * $Id: client.c,v 1.229 2004-02-14 15:44:15 adam Exp $
6  */
7
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <assert.h>
11 #if HAVE_LOCALE_H
12 #include <locale.h>
13 #endif
14
15 #if HAVE_LANGINFO_H
16 #include <langinfo.h>
17 #endif
18
19 #include <time.h>
20 #include <ctype.h>
21
22 #ifdef WIN32
23 #include <io.h>
24 #define S_ISREG(x) (x & _S_IFREG)
25 #define S_ISDIR(x) (x & _S_IFDIR)
26 #endif
27
28 #include <yaz/yaz-util.h>
29
30 #include <yaz/comstack.h>
31
32 #include <yaz/proto.h>
33 #include <yaz/marcdisp.h>
34 #include <yaz/diagbib1.h>
35 #include <yaz/otherinfo.h>
36 #include <yaz/charneg.h>
37
38 #include <yaz/pquery.h>
39 #include <yaz/sortspec.h>
40
41 #include <yaz/ill.h>
42 #include <yaz/srw.h>
43 #include <yaz/yaz-ccl.h>
44 #include <yaz/cql.h>
45
46 #if HAVE_READLINE_READLINE_H
47 #include <readline/readline.h>
48 #include <unistd.h>
49 #endif
50 #if HAVE_READLINE_HISTORY_H
51 #include <readline/history.h>
52 #endif
53
54 #include <sys/stat.h>
55
56 #include "admin.h"
57 #include "tabcomplete.h"
58
59 #define C_PROMPT "Z> "
60
61 static char *codeset = 0;               /* character set for output */
62 static int hex_dump = 0;
63 static char *dump_file_prefix = 0;
64 static ODR out, in, print;              /* encoding and decoding streams */
65 #if HAVE_XML2
66 static ODR srw_sr_odr_out = 0;
67 static Z_SRW_PDU *srw_sr = 0;
68 #endif
69 static FILE *apdu_file = 0;
70 static FILE *ber_file = 0;
71 static COMSTACK conn = 0;               /* our z-association */
72 static Z_IdAuthentication *auth = 0;    /* our current auth definition */
73 char *databaseNames[128];
74 int num_databaseNames = 0;
75 static Z_External *record_last = 0;
76 static int setnumber = -1;              /* current result set number */
77 static int smallSetUpperBound = 0;
78 static int largeSetLowerBound = 1;
79 static int mediumSetPresentNumber = 0;
80 static Z_ElementSetNames *elementSetNames = 0; 
81 static int setno = 1;                   /* current set offset */
82 static enum oid_proto protocol = PROTO_Z3950;      /* current app protocol */
83 static enum oid_value recordsyntax = VAL_USMARC;
84 static char *record_schema = 0;
85 static int sent_close = 0;
86 static NMEM session_mem = NULL;         /* memory handle for init-response */
87 static Z_InitResponse *session = 0;     /* session parameters */
88 static char last_scan_line[512] = "0";
89 static char last_scan_query[512] = "0";
90 static char ccl_fields[512] = "default.bib";
91 /* ### How can I set this path to use wherever YAZ is installed? */
92 static char cql_fields[512] = "/usr/local/share/yaz/etc/pqf.properties";
93 static char *esPackageName = 0;
94 static char *yazProxy = 0;
95 static int kilobytes = 1024;
96 static char *negotiationCharset = 0;
97 static char *outputCharset = 0;
98 static char *marcCharset = 0;
99 static char* yazLang = 0;
100
101 static char last_cmd[32] = "?";
102 static FILE *marc_file = 0;
103 static char *refid = NULL;
104 static char *last_open_command = NULL;
105 static int auto_reconnect = 0;
106 static Odr_bitmask z3950_options;
107 static int z3950_version = 3;
108
109 static char cur_host[200];
110
111 typedef enum {
112     QueryType_Prefix,
113     QueryType_CCL,
114     QueryType_CCL2RPN,
115     QueryType_CQL,
116     QueryType_CQL2RPN
117 } QueryType;
118
119 static QueryType queryType = QueryType_Prefix;
120
121 static CCL_bibset bibset;               /* CCL bibset handle */
122 static cql_transform_t cqltrans;        /* CQL context-set handle */
123
124 #if HAVE_READLINE_COMPLETION_OVER
125
126 #else
127 /* readline doesn't have this var. Define it ourselves. */
128 int rl_attempted_completion_over = 0;
129 #endif
130
131 /* set this one to 1, to avoid decode of unknown MARCs  */
132 #define AVOID_MARC_DECODE 1
133
134 #define maxOtherInfosSupported 10
135 struct {
136     int oidval;
137     char* value;
138 } extraOtherInfos[maxOtherInfosSupported];
139         
140
141 void process_cmd_line(char* line);
142 char ** readline_completer(char *text, int start, int end);
143 char *command_generator(const char *text, int state);
144 char** curret_global_list=NULL;
145 int cmd_register_tab(const char* arg);
146
147 static void close_session (void);
148
149 ODR getODROutputStream()
150 {
151     return out;
152 }
153
154 const char* query_type_as_string(QueryType q) 
155 {
156     switch (q) { 
157     case QueryType_Prefix: return "prefix (RPN sent to server)";
158     case QueryType_CCL: return "CCL (CCL sent to server) ";
159     case QueryType_CCL2RPN: return "CCL -> RPN (RPN sent to server)";
160     case QueryType_CQL: return "CQL (CQL sent to server)";
161     case QueryType_CQL2RPN: return "CQL -> RPN (RPN sent to server)";
162     default: 
163         return "unknown Query type internal yaz-client error";
164     }
165 }
166
167 static void do_hex_dump(const char* buf, int len) 
168 {
169     if (hex_dump)
170     {
171         int i,x;
172         for( i=0; i<len ; i=i+16 ) 
173         {                       
174             printf(" %4.4d ",i);
175             for(x=0 ; i+x<len && x<16; ++x) 
176             {
177                 printf("%2.2X ",(unsigned int)((unsigned char)buf[i+x]));
178             }
179             printf("\n");
180         }
181     }
182     if (dump_file_prefix)
183     {
184         static int no = 0;
185         if (++no < 1000 && strlen(dump_file_prefix) < 500)
186         {
187             char fname[1024];
188             FILE *of;
189             sprintf (fname, "%s.%03d.raw", dump_file_prefix, no);
190             of = fopen(fname, "wb");
191             
192             fwrite (buf, 1, len, of);
193             
194             fclose(of);
195         }
196     }
197 }
198
199 void add_otherInfos(Z_APDU *a) 
200 {
201     Z_OtherInformation **oi;
202     int i;
203                 
204     yaz_oi_APDU(a, &oi);
205     for(i=0; i<maxOtherInfosSupported; ++i) 
206     {
207         if(extraOtherInfos[i].oidval != -1) 
208             yaz_oi_set_string_oidval(oi, out, extraOtherInfos[i].oidval,
209                                      1, extraOtherInfos[i].value);
210     }   
211 }
212
213 int send_apdu(Z_APDU *a)
214 {
215     char *buf;
216     int len;
217     
218     add_otherInfos(a);
219     
220     if (apdu_file)
221     {
222         z_APDU(print, &a, 0, 0);
223         odr_reset(print);
224     }
225     if (!z_APDU(out, &a, 0, 0))
226     {
227         odr_perror(out, "Encoding APDU");
228         close_session();
229         return 0;
230     }
231     buf = odr_getbuf(out, &len, 0);
232     if (ber_file)
233         odr_dumpBER(ber_file, buf, len);
234     /* printf ("sending APDU of size %d\n", len); */
235     do_hex_dump(buf, len);
236     if (cs_put(conn, buf, len) < 0)
237     {
238         fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
239         close_session();
240         return 0;
241     }
242     odr_reset(out); /* release the APDU structure  */
243     return 1;
244 }
245
246 static void print_stringn(const unsigned char *buf, size_t len)
247 {
248     size_t i;
249     for (i = 0; i<len; i++)
250         if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
251             printf ("%c", buf[i]);
252         else
253             printf ("\\X%02X", buf[i]);
254 }
255
256 static void print_refid (Z_ReferenceId *id)
257 {
258     if (id)
259     {
260         printf ("Reference Id: ");
261         print_stringn (id->buf, id->len);
262         printf ("\n");
263     }
264 }
265
266 static Z_ReferenceId *set_refid (ODR out)
267 {
268     Z_ReferenceId *id;
269     if (!refid)
270         return 0;
271     id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
272     id->size = id->len = strlen(refid);
273     id->buf = (unsigned char *) odr_malloc (out, id->len);
274     memcpy (id->buf, refid, id->len);
275     return id;
276 }   
277
278 /* INIT SERVICE ------------------------------- */
279
280 static void send_initRequest(const char* type_and_host)
281 {
282     Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
283     Z_InitRequest *req = apdu->u.initRequest;
284     int i;
285
286     req->options = &z3950_options;
287
288     ODR_MASK_ZERO(req->protocolVersion);
289     for (i = 0; i<z3950_version; i++)
290         ODR_MASK_SET(req->protocolVersion, i);
291
292     *req->maximumRecordSize = 1024*kilobytes;
293     *req->preferredMessageSize = 1024*kilobytes;
294
295     req->idAuthentication = auth;
296
297     req->referenceId = set_refid (out);
298
299     if (yazProxy && type_and_host) 
300         yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
301         1, type_and_host);
302     
303     if (negotiationCharset || yazLang) {
304         Z_OtherInformation **p;
305         Z_OtherInformationUnit *p0;
306         
307         yaz_oi_APDU(apdu, &p);
308         
309         if ((p0=yaz_oi_update(p, out, NULL, 0, 0))) {
310                 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
311                 
312                 p0->which = Z_OtherInfo_externallyDefinedInfo;
313                 p0->information.externallyDefinedInfo =
314                         yaz_set_proposal_charneg(
315                             out,
316                             (const char**)&negotiationCharset, 
317                             negotiationCharset ? 1 : 0,
318                             (const char**)&yazLang, yazLang ? 1 : 0, 1);
319         }
320     }
321     
322     if (send_apdu(apdu))
323         printf("Sent initrequest.\n");
324 }
325
326
327 /* These two are used only from process_initResponse() */
328 static void render_initUserInfo(Z_OtherInformation *ui1);
329 static void render_diag(Z_DiagnosticFormat *diag);
330
331 static void pr_opt(const char *opt, void *clientData)
332 {
333     printf (" %s", opt);
334 }
335
336 static int process_initResponse(Z_InitResponse *res)
337 {
338     int ver = 0;
339     /* save session parameters for later use */
340     session_mem = odr_extract_mem(in);
341     session = res;
342
343     for (ver = 0; ver < 8; ver++)
344         if (!ODR_MASK_GET(res->protocolVersion, ver))
345             break;
346
347     if (!*res->result)
348         printf("Connection rejected by v%d target.\n", ver);
349     else
350         printf("Connection accepted by v%d target.\n", ver);
351     if (res->implementationId)
352         printf("ID     : %s\n", res->implementationId);
353     if (res->implementationName)
354         printf("Name   : %s\n", res->implementationName);
355     if (res->implementationVersion)
356         printf("Version: %s\n", res->implementationVersion);
357     if (res->userInformationField)
358     {
359         Z_External *uif = res->userInformationField;
360         if (uif->which == Z_External_userInfo1) {
361             render_initUserInfo(uif->u.userInfo1);
362         } else {
363             printf("UserInformationfield:\n");
364             if (!z_External(print, (Z_External**)&uif, 0, 0)) {
365                 odr_perror(print, "Printing userinfo\n");
366                 odr_reset(print);
367             }
368             if (uif->which == Z_External_octet) {
369                 printf("Guessing visiblestring:\n");
370                 printf("'%s'\n", uif->u. octet_aligned->buf);
371             } else if (uif->which == Z_External_single) {
372                 /* Peek at any private Init-diagnostic APDUs */
373                 Odr_any *sat = uif->u.single_ASN1_type;
374                 printf("### NAUGHTY: External is '%s'\n", sat->buf);
375             }
376             odr_reset (print);
377         }
378     }
379     printf ("Options:");
380     yaz_init_opt_decode(res->options, pr_opt, 0);
381     printf ("\n");
382
383     if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
384         setnumber = 0;
385     
386     if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
387     
388         Z_CharSetandLanguageNegotiation *p =
389                 yaz_get_charneg_record(res->otherInfo);
390         
391         if (p) {
392             
393             char *charset=NULL, *lang=NULL;
394             int selected;
395             
396             yaz_get_response_charneg(session_mem, p, &charset, &lang,
397                                      &selected);
398
399             if (outputCharset && negotiationCharset) {
400                     odr_set_charset (out, charset, outputCharset);
401                     odr_set_charset (in, outputCharset, charset);
402             }
403             else {
404                     odr_set_charset (out, 0, 0);
405                     odr_set_charset (in, 0, 0);
406             }
407             
408             printf("Accepted character set : %s\n", charset);
409             printf("Accepted code language : %s\n", lang ? lang : "none");
410             printf("Accepted records in ...: %d\n", selected );
411         }
412     }
413     fflush (stdout);
414     return 0;
415 }
416
417
418 static void render_initUserInfo(Z_OtherInformation *ui1) {
419     int i;
420     printf("Init response contains %d otherInfo unit%s:\n",
421            ui1->num_elements, ui1->num_elements == 1 ? "" : "s");
422
423     for (i = 0; i < ui1->num_elements; i++) {
424         Z_OtherInformationUnit *unit = ui1->list[i];
425         printf("  %d: otherInfo unit contains ", i+1);
426         if (unit->which == Z_OtherInfo_externallyDefinedInfo &&
427             unit->information.externallyDefinedInfo->which ==
428             Z_External_diag1) {
429             render_diag(unit->information.externallyDefinedInfo->u.diag1);
430         } else {
431             printf("unsupported otherInfo unit type %d\n", unit->which);
432         }
433     }
434 }
435
436
437 /* ### should this share code with display_diagrecs()? */
438 static void render_diag(Z_DiagnosticFormat *diag) {
439     int i;
440
441     printf("%d diagnostic%s:\n", diag->num, diag->num == 1 ? "" : "s");
442     for (i = 0; i < diag->num; i++) {
443         Z_DiagnosticFormat_s *ds = diag->elements[i];
444         printf("    %d: ", i+1);
445         switch (ds->which) {
446         case Z_DiagnosticFormat_s_defaultDiagRec: {
447             Z_DefaultDiagFormat *dd = ds->u.defaultDiagRec;
448             /* ### should check `dd->diagnosticSetId' */
449             printf("code=%d (%s)", *dd->condition,
450                    diagbib1_str(*dd->condition));
451             /* Both types of addinfo are the same, so use type-pun */
452             if (dd->u.v2Addinfo != 0)
453                 printf(",\n\taddinfo='%s'", dd->u.v2Addinfo);
454             break;
455         }
456         case Z_DiagnosticFormat_s_explicitDiagnostic:
457             printf("Explicit diagnostic (not supported)");
458             break;
459         default:
460             printf("Unrecognised diagnostic type %d", ds->which);
461             break;
462         }
463
464         if (ds->message != 0)
465             printf(", message='%s'", ds->message);
466         printf("\n");
467     }
468 }
469
470
471 static int set_base(const char *arg)
472 {
473     int i;
474     const char *cp;
475
476     for (i = 0; i<num_databaseNames; i++)
477         xfree (databaseNames[i]);
478     num_databaseNames = 0;
479     while (1)
480     {
481         char *cp1;
482         if (!(cp = strchr(arg, ' ')))
483             cp = arg + strlen(arg);
484         if (cp - arg < 1)
485             break;
486         databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
487         memcpy (databaseNames[num_databaseNames], arg, cp - arg);
488         databaseNames[num_databaseNames][cp - arg] = '\0';
489
490         for (cp1 = databaseNames[num_databaseNames]; *cp1 ; cp1++)
491             if (*cp1 == '+')
492                 *cp1 = ' ';
493         num_databaseNames++;
494
495         if (!*cp)
496             break;
497         arg = cp+1;
498     }
499     if (num_databaseNames == 0)
500     {
501         num_databaseNames = 1;
502         databaseNames[0] = xstrdup("");
503     }
504     return 1;
505 }
506
507 static int cmd_base(const char *arg)
508 {
509     if (!*arg)
510     {
511         printf("Usage: base <database> <database> ...\n");
512         return 0;
513     }
514     return set_base(arg);
515 }
516
517 void cmd_open_remember_last_open_command(const char* arg, char* new_open_command)
518 {
519     if(last_open_command != arg) 
520     {
521         if(last_open_command) xfree(last_open_command);
522         last_open_command = xstrdup(new_open_command);
523     }
524 }
525
526 int session_connect(const char *arg)
527 {
528     void *add;
529     char type_and_host[101];
530     const char *basep = 0;
531     if (conn)
532     {
533         cs_close (conn);
534         conn = NULL;
535         if (session_mem)
536         {
537             nmem_destroy (session_mem);
538             session_mem = NULL;
539         }
540     }   
541     cs_get_host_args(arg, &basep);
542
543     strncpy(type_and_host, arg, sizeof(type_and_host)-1);
544     type_and_host[sizeof(type_and_host)-1] = '\0';
545
546     cmd_open_remember_last_open_command(arg,type_and_host);
547
548     if (yazProxy)
549         conn = cs_create_host(yazProxy, 1, &add);
550     else
551         conn = cs_create_host(arg, 1, &add);
552     if (!conn)
553     {
554         printf ("Couldn't create comstack\n");
555         return 0;
556     }
557 #if HAVE_XML2
558 #else
559     if (conn->protocol == PROTO_HTTP)
560     {
561         printf ("SRW/HTTP not enabled in this YAZ\n");
562         cs_close(conn);
563         conn = 0;
564         return 0;
565     }
566 #endif
567     protocol = conn->protocol;
568     if (conn->protocol == PROTO_HTTP)
569         set_base("");
570     else
571         set_base("Default");
572     printf("Connecting...");
573     fflush(stdout);
574     if (cs_connect(conn, add) < 0)
575     {
576         printf ("error = %s\n", cs_strerror(conn));
577         if (conn->cerrno == CSYSERR)
578         {
579             char msg[256];
580             yaz_strerror(msg, sizeof(msg));
581             printf ("%s\n", msg);
582         }
583         cs_close(conn);
584         conn = 0;
585         return 0;
586     }
587     printf("OK.\n");
588     if (basep && *basep)
589         set_base (basep);
590     if (protocol == PROTO_Z3950)
591     {
592         send_initRequest(type_and_host);
593         return 2;
594     }
595     return 0;
596 }
597
598 int cmd_open(const char *arg)
599 {
600     if (arg)
601     {
602         strncpy (cur_host, arg, sizeof(cur_host)-1);
603         cur_host[sizeof(cur_host)-1] = 0;
604     }
605     return session_connect(cur_host);
606 }
607
608 void try_reconnect() 
609 {
610     char* open_command;
611         
612     if(!( auto_reconnect && last_open_command) ) return ;
613
614     open_command = (char *) xmalloc (strlen(last_open_command)+6);
615     strcpy (open_command, "open ");
616         
617     strcat (open_command, last_open_command);
618
619     process_cmd_line(open_command);
620         
621     xfree(open_command);                                
622 }
623
624 int cmd_authentication(const char *arg)
625 {
626     static Z_IdAuthentication au;
627     static char user[40], group[40], pass[40];
628     static Z_IdPass idPass;
629     int r;
630
631     if (!*arg)
632     {
633         printf("Auth field set to null\n");
634         auth = 0;
635         return 1;
636     }
637     r = sscanf (arg, "%39s %39s %39s", user, group, pass);
638     if (r == 0)
639     {
640         printf("Authentication set to null\n");
641         auth = 0;
642     }
643     if (r == 1)
644     {
645         auth = &au;
646         if (!strcmp(user, "-")) {
647             au.which = Z_IdAuthentication_anonymous;
648             printf("Authentication set to Anonymous\n");
649         } else {
650             au.which = Z_IdAuthentication_open;
651             au.u.open = user;
652             printf("Authentication set to Open (%s)\n", user);
653         }
654     }
655     if (r == 2)
656     {
657         auth = &au;
658         au.which = Z_IdAuthentication_idPass;
659         au.u.idPass = &idPass;
660         idPass.groupId = NULL;
661         idPass.userId = user;
662         idPass.password = group;
663         printf("Authentication set to User (%s), Pass (%s)\n", user, group);
664     }
665     if (r == 3)
666     {
667         auth = &au;
668         au.which = Z_IdAuthentication_idPass;
669         au.u.idPass = &idPass;
670         idPass.groupId = group;
671         idPass.userId = user;
672         idPass.password = pass;
673         printf("Authentication set to User (%s), Group (%s), Pass (%s)\n",
674                user, group, pass);
675     }
676     return 1;
677 }
678
679 /* SEARCH SERVICE ------------------------------ */
680 static void display_record(Z_External *r);
681
682 static void print_record(const unsigned char *buf, size_t len)
683 {
684     size_t i = len;
685     print_stringn (buf, len);
686     /* add newline if not already added ... */
687     if (i <= 0 || buf[i-1] != '\n')
688         printf ("\n");
689 }
690
691 static void display_record(Z_External *r)
692 {
693     oident *ent = oid_getentbyoid(r->direct_reference);
694
695     record_last = r;
696     /*
697      * Tell the user what we got.
698      */
699     if (r->direct_reference)
700     {
701         printf("Record type: ");
702         if (ent)
703             printf("%s\n", ent->desc);
704         else if (!odr_oid(print, &r->direct_reference, 0, 0))
705         {
706             odr_perror(print, "print oid");
707             odr_reset(print);
708         }
709     }
710     /* Check if this is a known, ASN.1 type tucked away in an octet string */
711     if (ent && r->which == Z_External_octet)
712     {
713         Z_ext_typeent *type = z_ext_getentbyref(ent->value);
714         void *rr;
715
716         if (type)
717         {
718             /*
719              * Call the given decoder to process the record.
720              */
721             odr_setbuf(in, (char*)r->u.octet_aligned->buf,
722                 r->u.octet_aligned->len, 0);
723             if (!(*type->fun)(in, (char **)&rr, 0, 0))
724             {
725                 odr_perror(in, "Decoding constructed record.");
726                 fprintf(stdout, "[Near %d]\n", odr_offset(in));
727                 fprintf(stdout, "Packet dump:\n---------\n");
728                 odr_dumpBER(stdout, (char*)r->u.octet_aligned->buf,
729                             r->u.octet_aligned->len);
730                 fprintf(stdout, "---------\n");
731                 
732                 /* note just ignores the error ant print the bytes form the octet_aligned later */
733             } else {
734                 /*
735                  * Note: we throw away the original, BER-encoded record here.
736                  * Do something else with it if you want to keep it.
737                  */
738                 r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
739                 r->which = type->what;
740             }
741         }
742     }
743     if (ent && ent->oclass != CLASS_RECSYN) 
744         return;
745     if (ent && ent->value == VAL_SOIF)
746         print_record((const unsigned char *) r->u.octet_aligned->buf,
747                      r->u.octet_aligned->len);
748     else if (r->which == Z_External_octet)
749     {
750         const char *octet_buf = (char*)r->u.octet_aligned->buf;
751         if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
752             ent->value == VAL_HTML)
753         {
754             print_record((const unsigned char *) octet_buf,
755                          r->u.octet_aligned->len);
756         }
757         else if (ent->value == VAL_POSTSCRIPT)
758         {
759             int size = r->u.octet_aligned->len;
760             if (size > 100)
761                 size = 100;
762             print_record((const unsigned char *) octet_buf, size);
763         }
764         else
765         {
766             if ( 
767 #if AVOID_MARC_DECODE
768                 /* primitive check for a marc OID 5.1-29 except 16 */
769                 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
770                 ent->oidsuffix[1] != 16
771 #else
772                 1
773 #endif
774                 )
775             {
776                 char *result;
777                 int rlen;
778                 yaz_iconv_t cd = 0;
779                 yaz_marc_t mt = yaz_marc_create();
780                     
781                 if (yaz_marc_decode_buf(mt, octet_buf,r->u.octet_aligned->len,
782                                         &result, &rlen)> 0)
783                 {
784                     char *from = 0;
785                     if (marcCharset && !strcmp(marcCharset, "auto"))
786                     {
787                         if (ent->value == VAL_USMARC)
788                         {
789                             if (octet_buf[9] == 'a')
790                                 from = "UTF-8";
791                             else
792                                 from = "MARC-8";
793                         }
794                         else
795                             from = "ISO-8859-1";
796                     }
797                     else if (marcCharset)
798                         from = marcCharset;
799                     if (outputCharset && from)
800                     {   
801                         cd = yaz_iconv_open(outputCharset, from);
802                         printf ("convert from %s to %s", from, 
803                                 outputCharset);
804                         if (!cd)
805                             printf (" unsupported\n");
806                         else
807                             printf ("\n");
808                     }
809                     if (!cd)
810                         fwrite (result, 1, rlen, stdout);
811                     else
812                     {
813                         char outbuf[6];
814                         size_t inbytesleft = rlen;
815                         const char *inp = result;
816                         
817                         while (inbytesleft)
818                         {
819                             size_t outbytesleft = sizeof(outbuf);
820                             char *outp = outbuf;
821                             size_t r;
822
823                             r = yaz_iconv (cd, (char**) &inp,
824                                            &inbytesleft, 
825                                            &outp, &outbytesleft);
826                             if (r == (size_t) (-1))
827                             {
828                                 int e = yaz_iconv_error(cd);
829                                 if (e != YAZ_ICONV_E2BIG)
830                                     break;
831                             }
832                             fwrite (outbuf, outp - outbuf, 1, stdout);
833                         }
834                     }
835                 }
836                 else
837                 {
838                     printf ("bad MARC. Dumping as it is:\n");
839                     print_record((const unsigned char*) octet_buf,
840                                   r->u.octet_aligned->len);
841                 }       
842                 yaz_marc_destroy(mt);
843                 if (cd)
844                     yaz_iconv_close(cd);
845             }
846             else
847             {
848                 print_record((const unsigned char*) octet_buf,
849                              r->u.octet_aligned->len);
850             }
851         }
852         if (marc_file)
853             fwrite (octet_buf, 1, r->u.octet_aligned->len, marc_file);
854     }
855     else if (ent && ent->value == VAL_SUTRS)
856     {
857         if (r->which != Z_External_sutrs)
858         {
859             printf("Expecting single SUTRS type for SUTRS.\n");
860             return;
861         }
862         print_record(r->u.sutrs->buf, r->u.sutrs->len);
863     }
864     else if (ent && ent->value == VAL_GRS1)
865     {
866         WRBUF w;
867         if (r->which != Z_External_grs1)
868         {
869             printf("Expecting single GRS type for GRS.\n");
870             return;
871         }
872         w = wrbuf_alloc();
873         yaz_display_grs1(w, r->u.grs1, 0);
874         puts (wrbuf_buf(w));
875         wrbuf_free(w, 1);
876     }
877     else if ( /* OPAC display not complete yet .. */
878              ent && ent->value == VAL_OPAC)
879     {
880         int i;
881         if (r->u.opac->bibliographicRecord)
882             display_record(r->u.opac->bibliographicRecord);
883         for (i = 0; i<r->u.opac->num_holdingsData; i++)
884         {
885             Z_HoldingsRecord *h = r->u.opac->holdingsData[i];
886             if (h->which == Z_HoldingsRecord_marcHoldingsRecord)
887             {
888                 printf ("MARC holdings %d\n", i);
889                 display_record(h->u.marcHoldingsRecord);
890             }
891             else if (h->which == Z_HoldingsRecord_holdingsAndCirc)
892             {
893                 int j;
894
895                 Z_HoldingsAndCircData *data = h->u.holdingsAndCirc;
896
897                 printf ("Data holdings %d\n", i);
898                 if (data->typeOfRecord)
899                     printf ("typeOfRecord: %s\n", data->typeOfRecord);
900                 if (data->encodingLevel)
901                     printf ("encodingLevel: %s\n", data->encodingLevel);
902                 if (data->receiptAcqStatus)
903                     printf ("receiptAcqStatus: %s\n", data->receiptAcqStatus);
904                 if (data->generalRetention)
905                     printf ("generalRetention: %s\n", data->generalRetention);
906                 if (data->completeness)
907                     printf ("completeness: %s\n", data->completeness);
908                 if (data->dateOfReport)
909                     printf ("dateOfReport: %s\n", data->dateOfReport);
910                 if (data->nucCode)
911                     printf ("nucCode: %s\n", data->nucCode);
912                 if (data->localLocation)
913                     printf ("localLocation: %s\n", data->localLocation);
914                 if (data->shelvingLocation)
915                     printf ("shelvingLocation: %s\n", data->shelvingLocation);
916                 if (data->callNumber)
917                     printf ("callNumber: %s\n", data->callNumber);
918                 if (data->copyNumber)
919                     printf ("copyNumber: %s\n", data->copyNumber);
920                 if (data->publicNote)
921                     printf ("publicNote: %s\n", data->publicNote);
922                 if (data->reproductionNote)
923                     printf ("reproductionNote: %s\n", data->reproductionNote);
924                 if (data->termsUseRepro)
925                     printf ("termsUseRepro: %s\n", data->termsUseRepro);
926                 if (data->enumAndChron)
927                     printf ("enumAndChron: %s\n", data->enumAndChron);
928                 for (j = 0; j<data->num_volumes; j++)
929                 {
930                     printf ("volume %d\n", j);
931                     if (data->volumes[j]->enumeration)
932                         printf (" enumeration: %s\n",
933                                 data->volumes[j]->enumeration);
934                     if (data->volumes[j]->chronology)
935                         printf (" chronology: %s\n",
936                                 data->volumes[j]->chronology);
937                     if (data->volumes[j]->enumAndChron)
938                         printf (" enumAndChron: %s\n",
939                                 data->volumes[j]->enumAndChron);
940                 }
941                 for (j = 0; j<data->num_circulationData; j++)
942                 {
943                     printf ("circulation %d\n", j);
944                     if (data->circulationData[j]->availableNow)
945                         printf (" availableNow: %d\n",
946                                 *data->circulationData[j]->availableNow);
947                     if (data->circulationData[j]->availablityDate)
948                         printf (" availabiltyDate: %s\n",
949                                 data->circulationData[j]->availablityDate);
950                     if (data->circulationData[j]->availableThru)
951                         printf (" availableThru: %s\n",
952                                 data->circulationData[j]->availableThru);
953                     if (data->circulationData[j]->restrictions)
954                         printf (" restrictions: %s\n",
955                                 data->circulationData[j]->restrictions);
956                     if (data->circulationData[j]->itemId)
957                         printf (" itemId: %s\n",
958                                 data->circulationData[j]->itemId);
959                     if (data->circulationData[j]->renewable)
960                         printf (" renewable: %d\n",
961                                 *data->circulationData[j]->renewable);
962                     if (data->circulationData[j]->onHold)
963                         printf (" onHold: %d\n",
964                                 *data->circulationData[j]->onHold);
965                     if (data->circulationData[j]->enumAndChron)
966                         printf (" enumAndChron: %s\n",
967                                 data->circulationData[j]->enumAndChron);
968                     if (data->circulationData[j]->midspine)
969                         printf (" midspine: %s\n",
970                                 data->circulationData[j]->midspine);
971                     if (data->circulationData[j]->temporaryLocation)
972                         printf (" temporaryLocation: %s\n",
973                                 data->circulationData[j]->temporaryLocation);
974                 }
975             }
976         }
977     }
978     else 
979     {
980         printf("Unknown record representation.\n");
981         if (!z_External(print, &r, 0, 0))
982         {
983             odr_perror(print, "Printing external");
984             odr_reset(print);
985         }
986     }
987 }
988
989 static void display_diagrecs(Z_DiagRec **pp, int num)
990 {
991     int i;
992     oident *ent;
993     Z_DefaultDiagFormat *r;
994
995     printf("Diagnostic message(s) from database:\n");
996     for (i = 0; i<num; i++)
997     {
998         Z_DiagRec *p = pp[i];
999         if (p->which != Z_DiagRec_defaultFormat)
1000         {
1001             printf("Diagnostic record not in default format.\n");
1002             return;
1003         }
1004         else
1005             r = p->u.defaultFormat;
1006         if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
1007             ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
1008             printf("Missing or unknown diagset\n");
1009         printf("    [%d] %s", *r->condition, diagbib1_str(*r->condition));
1010         switch (r->which)
1011         {
1012         case Z_DefaultDiagFormat_v2Addinfo:
1013             printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
1014             break;
1015         case Z_DefaultDiagFormat_v3Addinfo:
1016             printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
1017             break;
1018         }
1019     }
1020 }
1021
1022
1023 static void display_nameplusrecord(Z_NamePlusRecord *p)
1024 {
1025     if (p->databaseName)
1026         printf("[%s]", p->databaseName);
1027     if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
1028         display_diagrecs(&p->u.surrogateDiagnostic, 1);
1029     else if (p->which == Z_NamePlusRecord_databaseRecord)
1030         display_record(p->u.databaseRecord);
1031 }
1032
1033 static void display_records(Z_Records *p)
1034 {
1035     int i;
1036
1037     if (p->which == Z_Records_NSD)
1038     {
1039         Z_DiagRec dr, *dr_p = &dr;
1040         dr.which = Z_DiagRec_defaultFormat;
1041         dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
1042         display_diagrecs (&dr_p, 1);
1043     }
1044     else if (p->which == Z_Records_multipleNSD)
1045         display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
1046                           p->u.multipleNonSurDiagnostics->num_diagRecs);
1047     else 
1048     {
1049         printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
1050         for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
1051             display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
1052     }
1053 }
1054
1055 static int send_deleteResultSetRequest(const char *arg)
1056 {
1057     char names[8][32];
1058     int i;
1059
1060     Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
1061     Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
1062
1063     req->referenceId = set_refid (out);
1064
1065     req->num_resultSetList =
1066         sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
1067                 names[0], names[1], names[2], names[3],
1068                 names[4], names[5], names[6], names[7]);
1069
1070     req->deleteFunction = (int *)
1071         odr_malloc (out, sizeof(*req->deleteFunction));
1072     if (req->num_resultSetList > 0)
1073     {
1074         *req->deleteFunction = Z_DeleteRequest_list;
1075         req->resultSetList = (char **)
1076             odr_malloc (out, sizeof(*req->resultSetList)*
1077                         req->num_resultSetList);
1078         for (i = 0; i<req->num_resultSetList; i++)
1079             req->resultSetList[i] = names[i];
1080     }
1081     else
1082     {
1083         *req->deleteFunction = Z_DeleteRequest_all;
1084         req->resultSetList = 0;
1085     }
1086     
1087     send_apdu(apdu);
1088     printf("Sent deleteResultSetRequest.\n");
1089     return 2;
1090 }
1091
1092 #if HAVE_XML2
1093 static int send_srw(Z_SRW_PDU *sr)
1094 {
1095     const char *charset = negotiationCharset;
1096     const char *host_port = cur_host;
1097     char *path = 0;
1098     char ctype[50];
1099     Z_SOAP_Handler h[2] = {
1100         {"http://www.loc.gov/zing/srw/", 0, (Z_SOAP_fun) yaz_srw_codec},
1101         {0, 0, 0}
1102     };
1103     ODR o = odr_createmem(ODR_ENCODE);
1104     int ret;
1105     Z_SOAP *p = odr_malloc(o, sizeof(*p));
1106     Z_GDU *gdu;
1107
1108     path = odr_malloc(out, strlen(databaseNames[0])+2);
1109     *path = '/';
1110     strcpy(path+1, databaseNames[0]);
1111
1112     gdu = z_get_HTTP_Request(out);
1113     gdu->u.HTTP_Request->path = odr_strdup(out, path);
1114
1115     if (host_port)
1116     {
1117         const char *cp0 = strstr(host_port, "://");
1118         const char *cp1 = 0;
1119         if (cp0)
1120             cp0 = cp0+3;
1121         else
1122             cp0 = host_port;
1123
1124         cp1 = strchr(cp0, '/');
1125         if (!cp1)
1126             cp1 = cp0+strlen(cp0);
1127
1128         if (cp0 && cp1)
1129         {
1130             char *h = odr_malloc(out, cp1 - cp0 + 1);
1131             memcpy (h, cp0, cp1 - cp0);
1132             h[cp1-cp0] = '\0';
1133             z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1134                               "Host", h);
1135         }
1136     }
1137
1138     strcpy(ctype, "text/xml");
1139     if (charset && strlen(charset) < 20)
1140     {
1141         strcat(ctype, "; charset=");
1142         strcat(ctype, charset);
1143     }
1144     z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1145                       "Content-Type", ctype);
1146     z_HTTP_header_add(out, &gdu->u.HTTP_Request->headers,
1147                       "SOAPAction", "\"\"");
1148     p->which = Z_SOAP_generic;
1149     p->u.generic = odr_malloc(o, sizeof(*p->u.generic));
1150     p->u.generic->no = 0;
1151     p->u.generic->ns = 0;
1152     p->u.generic->p = sr;
1153     p->ns = "http://schemas.xmlsoap.org/soap/envelope/";
1154
1155     ret = z_soap_codec_enc(o, &p,
1156                            &gdu->u.HTTP_Request->content_buf,
1157                            &gdu->u.HTTP_Request->content_len, h,
1158                            charset);
1159
1160     if (z_GDU(out, &gdu, 0, 0))
1161     {
1162         /* encode OK */
1163         char *buf_out;
1164         int len_out;
1165         int r;
1166         if (apdu_file)
1167         {
1168             if (!z_GDU(print, &gdu, 0, 0))
1169                 printf ("Failed to print outgoing APDU\n");
1170             odr_reset(print);
1171         }
1172         buf_out = odr_getbuf(out, &len_out, 0);
1173         
1174         /* we don't odr_reset(out), since we may need the buffer again */
1175
1176         do_hex_dump(buf_out, len_out);
1177
1178         r = cs_put(conn, buf_out, len_out);
1179
1180         odr_destroy(o);
1181         
1182         if (r >= 0)
1183             return 2;
1184     }
1185     return 0;
1186 }
1187 #endif
1188
1189 #if HAVE_XML2
1190 static int send_SRW_searchRequest(const char *arg)
1191 {
1192     Z_SRW_PDU *sr = 0;
1193     
1194     if (!srw_sr)
1195     {
1196         assert(srw_sr_odr_out == 0);
1197         srw_sr_odr_out = odr_createmem(ODR_ENCODE);
1198     }
1199     odr_reset(srw_sr_odr_out);
1200
1201     setno = 1;
1202
1203     /* save this for later .. when fetching individual records */
1204     srw_sr = sr = yaz_srw_get(srw_sr_odr_out, Z_SRW_searchRetrieve_request);
1205     sr->u.request->query_type = Z_SRW_query_type_cql;
1206     sr->u.request->query.cql = odr_strdup(srw_sr_odr_out, arg);
1207
1208     sr = yaz_srw_get(out, Z_SRW_searchRetrieve_request);
1209     sr->u.request->query_type = Z_SRW_query_type_cql;
1210     sr->u.request->query.cql = odr_strdup(out, arg);
1211     if (record_schema)
1212         sr->u.request->recordSchema = record_schema;
1213     return send_srw(sr);
1214 }
1215 #endif
1216
1217 static int send_searchRequest(const char *arg)
1218 {
1219     Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
1220     Z_SearchRequest *req = apdu->u.searchRequest;
1221     Z_Query query;
1222     int oid[OID_SIZE];
1223     struct ccl_rpn_node *rpn = NULL;
1224     int error, pos;
1225     char setstring[100];
1226     Z_RPNQuery *RPNquery;
1227     Odr_oct ccl_query;
1228     YAZ_PQF_Parser pqf_parser;
1229     Z_External *ext;
1230     QueryType myQueryType = queryType;
1231     char pqfbuf[512];
1232
1233     if (myQueryType == QueryType_CCL2RPN)
1234     {
1235         rpn = ccl_find_str(bibset, arg, &error, &pos);
1236         if (error)
1237         {
1238             printf("CCL ERROR: %s\n", ccl_err_msg(error));
1239             return 0;
1240         }
1241     } else if (myQueryType == QueryType_CQL2RPN) {
1242         /* ### All this code should be wrapped in a utility function */
1243         CQL_parser parser;
1244         struct cql_node *node;
1245         const char *addinfo;
1246         if (cqltrans == 0) {
1247             printf("Can't use CQL: no translation file.  Try set_cqlfile\n");
1248             return 0;
1249         }
1250         parser = cql_parser_create();
1251         if ((error = cql_parser_string(parser, arg)) != 0) {
1252             printf("Can't parse CQL: must be a syntax error\n");
1253             return 0;
1254         }
1255         node = cql_parser_result(parser);
1256         if ((error = cql_transform_buf(cqltrans, node, pqfbuf,
1257                                        sizeof pqfbuf)) != 0) {
1258             error = cql_transform_error(cqltrans, &addinfo);
1259             printf ("Can't convert CQL to PQF: %s (addinfo=%s)\n",
1260                     cql_strerror(error), addinfo);
1261             return 0;
1262         }
1263         arg = pqfbuf;
1264         myQueryType = QueryType_Prefix;
1265     }
1266
1267     req->referenceId = set_refid (out);
1268     if (!strcmp(arg, "@big")) /* strictly for troublemaking */
1269     {
1270         static unsigned char big[2100];
1271         static Odr_oct bigo;
1272
1273         /* send a very big referenceid to test transport stack etc. */
1274         memset(big, 'A', 2100);
1275         bigo.len = bigo.size = 2100;
1276         bigo.buf = big;
1277         req->referenceId = &bigo;
1278     }
1279     
1280     if (setnumber >= 0)
1281     {
1282         sprintf(setstring, "%d", ++setnumber);
1283         req->resultSetName = setstring;
1284     }
1285     *req->smallSetUpperBound = smallSetUpperBound;
1286     *req->largeSetLowerBound = largeSetLowerBound;
1287     *req->mediumSetPresentNumber = mediumSetPresentNumber;
1288     if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
1289         mediumSetPresentNumber > 0))
1290     {
1291         oident prefsyn;
1292
1293         prefsyn.proto = protocol;
1294         prefsyn.oclass = CLASS_RECSYN;
1295         prefsyn.value = recordsyntax;
1296         req->preferredRecordSyntax =
1297             odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
1298         req->smallSetElementSetNames =
1299             req->mediumSetElementSetNames = elementSetNames;
1300     }
1301     req->num_databaseNames = num_databaseNames;
1302     req->databaseNames = databaseNames;
1303
1304     req->query = &query;
1305
1306     switch (myQueryType)
1307     {
1308     case QueryType_Prefix:
1309         query.which = Z_Query_type_1;
1310         pqf_parser = yaz_pqf_create ();
1311         RPNquery = yaz_pqf_parse (pqf_parser, out, arg);
1312         if (!RPNquery)
1313         {
1314             const char *pqf_msg;
1315             size_t off;
1316             int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
1317             printf("%*s^\n", off+4, "");
1318             printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
1319             
1320             yaz_pqf_destroy (pqf_parser);
1321             return 0;
1322         }
1323         yaz_pqf_destroy (pqf_parser);
1324         query.u.type_1 = RPNquery;
1325         break;
1326     case QueryType_CCL:
1327         query.which = Z_Query_type_2;
1328         query.u.type_2 = &ccl_query;
1329         ccl_query.buf = (unsigned char*) arg;
1330         ccl_query.len = strlen(arg);
1331         break;
1332     case QueryType_CCL2RPN:
1333         query.which = Z_Query_type_1;
1334         RPNquery = ccl_rpn_query(out, rpn);
1335         if (!RPNquery)
1336         {
1337             printf ("Couldn't convert from CCL to RPN\n");
1338             return 0;
1339         }
1340         query.u.type_1 = RPNquery;
1341         ccl_rpn_delete (rpn);
1342         break;
1343     case QueryType_CQL:
1344         query.which = Z_Query_type_104;
1345         ext = (Z_External *) odr_malloc(out, sizeof(*ext));
1346         ext->direct_reference = odr_getoidbystr(out, "1.2.840.10003.16.2");
1347         ext->indirect_reference = 0;
1348         ext->descriptor = 0;
1349         ext->which = Z_External_CQL;
1350         ext->u.cql = odr_strdup(out, arg);
1351         query.u.type_104 =  ext;
1352         break;
1353     default:
1354         printf ("Unsupported query type\n");
1355         return 0;
1356     }
1357     if (send_apdu(apdu))
1358         printf("Sent searchRequest.\n");
1359     setno = 1;
1360     return 2;
1361 }
1362
1363 /* display Query Expression as part of searchResult-1 */
1364 static void display_queryExpression (Z_QueryExpression *qe)
1365 {
1366     if (!qe)
1367         return;
1368     if (qe->which == Z_QueryExpression_term)
1369     {
1370         if (qe->u.term->queryTerm)
1371         {
1372             Z_Term *term = qe->u.term->queryTerm;
1373             switch (term->which)
1374             {
1375             case Z_Term_general:
1376                 printf (" %.*s", term->u.general->len, term->u.general->buf);
1377                 break;
1378             case Z_Term_characterString:
1379                 printf (" %s", term->u.characterString);
1380                 break;
1381             case Z_Term_numeric:
1382                 printf (" %d", *term->u.numeric);
1383                 break;
1384             case Z_Term_null:
1385                 printf (" null");
1386                 break;
1387             }
1388         }
1389     }
1390 }
1391
1392 /* see if we can find USR:SearchResult-1 */
1393 static void display_searchResult (Z_OtherInformation *o)
1394 {
1395     int i;
1396     if (!o)
1397         return ;
1398     for (i = 0; i < o->num_elements; i++)
1399     {
1400         if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
1401         {
1402             Z_External *ext = o->list[i]->information.externallyDefinedInfo;
1403             
1404             if (ext->which == Z_External_searchResult1)
1405             {
1406                 int j;
1407                 Z_SearchInfoReport *sr = ext->u.searchResult1;
1408                 printf ("SearchResult-1:");
1409                 for (j = 0; j < sr->num; j++)
1410                 {
1411                     if (!sr->elements[j]->subqueryExpression)
1412                         printf (" %d", j);
1413                     display_queryExpression (
1414                         sr->elements[j]->subqueryExpression);
1415                     display_queryExpression (
1416                         sr->elements[j]->subqueryInterpretation);
1417                     display_queryExpression (
1418                         sr->elements[j]->subqueryRecommendation);
1419                     if (sr->elements[j]->subqueryCount)
1420                         printf ("(%d)", *sr->elements[j]->subqueryCount);
1421                 }
1422                 printf ("\n");
1423             }
1424         }
1425     }
1426 }
1427
1428 static int process_searchResponse(Z_SearchResponse *res)
1429 {
1430     printf ("Received SearchResponse.\n");
1431     print_refid (res->referenceId);
1432     if (*res->searchStatus)
1433         printf("Search was a success.\n");
1434     else
1435         printf("Search was a bloomin' failure.\n");
1436     printf("Number of hits: %d", *res->resultCount);
1437     if (setnumber >= 0)
1438         printf (", setno %d", setnumber);
1439     printf ("\n");
1440     display_searchResult (res->additionalSearchInfo);
1441     printf("records returned: %d\n",
1442            *res->numberOfRecordsReturned);
1443     setno += *res->numberOfRecordsReturned;
1444     if (res->records)
1445         display_records(res->records);
1446     return 0;
1447 }
1448
1449 static void print_level(int iLevel)
1450 {
1451     int i;
1452     for (i = 0; i < iLevel * 4; i++)
1453         printf(" ");
1454 }
1455
1456 static void print_int(int iLevel, const char *pTag, int *pInt)
1457 {
1458     if (pInt != NULL)
1459     {
1460         print_level(iLevel);
1461         printf("%s: %d\n", pTag, *pInt);
1462     }
1463 }
1464
1465 static void print_string(int iLevel, const char *pTag, const char *pString)
1466 {
1467     if (pString != NULL)
1468     {
1469         print_level(iLevel);
1470         printf("%s: %s\n", pTag, pString);
1471     }
1472 }
1473
1474 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
1475 {
1476     if (pOid != NULL)
1477     {
1478         int *pInt = pOid;
1479
1480         print_level(iLevel);
1481         printf("%s:", pTag);
1482         for (; *pInt != -1; pInt++)
1483             printf(" %d", *pInt);
1484         printf("\n");
1485     }
1486 }
1487
1488 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1489 {
1490     if (referenceId != NULL)
1491     {
1492         int i;
1493
1494         print_level(iLevel);
1495         printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1496         for (i = 0; i < referenceId->len; i++)
1497             printf("%c", referenceId->buf[i]);
1498         printf("\n");
1499     }
1500 }
1501
1502 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1503 {
1504     if (pStringNumeric != NULL)
1505     {
1506         switch (pStringNumeric->which)
1507         {
1508         case Z_StringOrNumeric_string:
1509             print_string(iLevel, pTag, pStringNumeric->u.string);
1510             break;
1511             
1512         case Z_StringOrNumeric_numeric:
1513             print_int(iLevel, pTag, pStringNumeric->u.numeric);
1514             break;
1515             
1516         default:
1517             print_level(iLevel);
1518             printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1519             break;
1520         }
1521     }
1522 }
1523
1524 static void print_universe_report_duplicate(
1525     int iLevel,
1526     Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1527 {
1528     if (pUniverseReportDuplicate != NULL)
1529     {
1530         print_level(iLevel);
1531         printf("Universe Report Duplicate: \n");
1532         iLevel++;
1533         print_string_or_numeric(iLevel, "Hit No",
1534                                 pUniverseReportDuplicate->hitno);
1535     }
1536 }
1537
1538 static void print_universe_report_hits(
1539     int iLevel,
1540     Z_UniverseReportHits *pUniverseReportHits)
1541 {
1542     if (pUniverseReportHits != NULL)
1543     {
1544         print_level(iLevel);
1545         printf("Universe Report Hits: \n");
1546         iLevel++;
1547         print_string_or_numeric(iLevel, "Database",
1548                                 pUniverseReportHits->database);
1549         print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1550     }
1551 }
1552
1553 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1554 {
1555     if (pUniverseReport != NULL)
1556     {
1557         print_level(iLevel);
1558         printf("Universe Report: \n");
1559         iLevel++;
1560         print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1561         switch (pUniverseReport->which)
1562         {
1563         case Z_UniverseReport_databaseHits:
1564             print_universe_report_hits(iLevel,
1565                                        pUniverseReport->u.databaseHits);
1566             break;
1567             
1568         case Z_UniverseReport_duplicate:
1569             print_universe_report_duplicate(iLevel,
1570                                             pUniverseReport->u.duplicate);
1571             break;
1572             
1573         default:
1574             print_level(iLevel);
1575             printf("Type: %d\n", pUniverseReport->which);
1576             break;
1577         }
1578     }
1579 }
1580
1581 static void print_external(int iLevel, Z_External *pExternal)
1582 {
1583     if (pExternal != NULL)
1584     {
1585         print_level(iLevel);
1586         printf("External: \n");
1587         iLevel++;
1588         print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1589         print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1590         print_string(iLevel, "Descriptor", pExternal->descriptor);
1591         switch (pExternal->which)
1592         {
1593         case Z_External_universeReport:
1594             print_universe_report(iLevel, pExternal->u.universeReport);
1595             break;
1596             
1597         default:
1598             print_level(iLevel);
1599             printf("Type: %d\n", pExternal->which);
1600             break;
1601         }
1602     }
1603 }
1604
1605 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1606 {
1607     printf ("Received ResourceControlRequest.\n");
1608     print_referenceId(1, req->referenceId);
1609     print_int(1, "Suspended Flag", req->suspendedFlag);
1610     print_int(1, "Partial Results Available", req->partialResultsAvailable);
1611     print_int(1, "Response Required", req->responseRequired);
1612     print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1613     print_external(1, req->resourceReport);
1614     return 0;
1615 }
1616
1617 void process_ESResponse(Z_ExtendedServicesResponse *res)
1618 {
1619     printf("Status: ");
1620     switch (*res->operationStatus)
1621     {
1622     case Z_ExtendedServicesResponse_done:
1623         printf ("done\n");
1624         break;
1625     case Z_ExtendedServicesResponse_accepted:
1626         printf ("accepted\n");
1627         break;
1628     case Z_ExtendedServicesResponse_failure:
1629         printf ("failure\n");
1630         display_diagrecs(res->diagnostics, res->num_diagnostics);
1631         break;
1632     default:
1633         printf ("unknown\n");
1634     }
1635     if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1636         (res->num_diagnostics != 0) ) {
1637         display_diagrecs(res->diagnostics, res->num_diagnostics);
1638     }
1639     print_refid (res->referenceId);
1640     if (res->taskPackage && 
1641         res->taskPackage->which == Z_External_extendedService)
1642     {
1643         Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1644         Odr_oct *id = taskPackage->targetReference;
1645         Z_External *ext = taskPackage->taskSpecificParameters;
1646         
1647         if (id)
1648         {
1649             printf ("Target Reference: ");
1650             print_stringn (id->buf, id->len);
1651             printf ("\n");
1652         }
1653         if (ext->which == Z_External_update)
1654         {
1655             Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1656             if (utp && utp->targetPart)
1657             {
1658                 Z_IUTargetPart *targetPart = utp->targetPart;
1659                 int i;
1660
1661                 for (i = 0; i<targetPart->num_taskPackageRecords;  i++)
1662                 {
1663
1664                     Z_IUTaskPackageRecordStructure *tpr =
1665                         targetPart->taskPackageRecords[i];
1666                     printf ("task package record %d\n", i+1);
1667                     if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1668                     {
1669                         display_record (tpr->u.record);
1670                     }
1671                     else
1672                     {
1673                         printf ("other type\n");
1674                     }
1675                 }
1676             }
1677         }
1678     }
1679 }
1680
1681 const char *get_ill_element (void *clientData, const char *element)
1682 {
1683     return 0;
1684 }
1685
1686 static Z_External *create_external_itemRequest()
1687 {
1688     struct ill_get_ctl ctl;
1689     ILL_ItemRequest *req;
1690     Z_External *r = 0;
1691     int item_request_size = 0;
1692     char *item_request_buf = 0;
1693
1694     ctl.odr = out;
1695     ctl.clientData = 0;
1696     ctl.f = get_ill_element;
1697     
1698     req = ill_get_ItemRequest(&ctl, "ill", 0);
1699     if (!req)
1700         printf ("ill_get_ItemRequest failed\n");
1701         
1702     if (!ill_ItemRequest (out, &req, 0, 0))
1703     {
1704         if (apdu_file)
1705         {
1706             ill_ItemRequest(print, &req, 0, 0);
1707             odr_reset(print);
1708         }
1709         item_request_buf = odr_getbuf (out, &item_request_size, 0);
1710         if (item_request_buf)
1711             odr_setbuf (out, item_request_buf, item_request_size, 1);
1712         printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1713         return 0;
1714     }
1715     else
1716     {
1717         oident oid;
1718         
1719         item_request_buf = odr_getbuf (out, &item_request_size, 0);
1720         oid.proto = PROTO_GENERAL;
1721         oid.oclass = CLASS_GENERAL;
1722         oid.value = VAL_ISO_ILL_1;
1723         
1724         r = (Z_External *) odr_malloc (out, sizeof(*r));
1725         r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid)); 
1726         r->indirect_reference = 0;
1727         r->descriptor = 0;
1728         r->which = Z_External_single;
1729         
1730         r->u.single_ASN1_type = (Odr_oct *)
1731             odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1732         r->u.single_ASN1_type->buf = (unsigned char *)
1733         odr_malloc (out, item_request_size);
1734         r->u.single_ASN1_type->len = item_request_size;
1735         r->u.single_ASN1_type->size = item_request_size;
1736         memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1737                 item_request_size);
1738         
1739         do_hex_dump(item_request_buf,item_request_size);
1740     }
1741     return r;
1742 }
1743
1744 static Z_External *create_external_ILL_APDU(int which)
1745 {
1746     struct ill_get_ctl ctl;
1747     ILL_APDU *ill_apdu;
1748     Z_External *r = 0;
1749     int ill_request_size = 0;
1750     char *ill_request_buf = 0;
1751         
1752     ctl.odr = out;
1753     ctl.clientData = 0;
1754     ctl.f = get_ill_element;
1755
1756     ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1757
1758     if (!ill_APDU (out, &ill_apdu, 0, 0))
1759     {
1760         if (apdu_file)
1761         {
1762             printf ("-------------------\n");
1763             ill_APDU(print, &ill_apdu, 0, 0);
1764             odr_reset(print);
1765             printf ("-------------------\n");
1766         }
1767         ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1768         if (ill_request_buf)
1769             odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1770         printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1771         return 0;
1772     }
1773     else
1774     {
1775         oident oid;
1776         ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1777         
1778         oid.proto = PROTO_GENERAL;
1779         oid.oclass = CLASS_GENERAL;
1780         oid.value = VAL_ISO_ILL_1;
1781         
1782         r = (Z_External *) odr_malloc (out, sizeof(*r));
1783         r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid)); 
1784         r->indirect_reference = 0;
1785         r->descriptor = 0;
1786         r->which = Z_External_single;
1787         
1788         r->u.single_ASN1_type = (Odr_oct *)
1789             odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1790         r->u.single_ASN1_type->buf = (unsigned char *)
1791         odr_malloc (out, ill_request_size);
1792         r->u.single_ASN1_type->len = ill_request_size;
1793         r->u.single_ASN1_type->size = ill_request_size;
1794         memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1795 /*         printf ("len = %d\n", ill_request_size); */
1796 /*              do_hex_dump(ill_request_buf,ill_request_size); */
1797 /*              printf("--- end of extenal\n"); */
1798
1799     }
1800     return r;
1801 }
1802
1803
1804 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1805 {
1806     Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1807     oident ItemOrderRequest;
1808   
1809     ItemOrderRequest.proto = PROTO_Z3950;
1810     ItemOrderRequest.oclass = CLASS_EXTSERV;
1811     ItemOrderRequest.value = VAL_ITEMORDER;
1812  
1813     r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest)); 
1814     r->indirect_reference = 0;
1815     r->descriptor = 0;
1816
1817     r->which = Z_External_itemOrder;
1818
1819     r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1820     memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1821     r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1822
1823     r->u.itemOrder->u.esRequest = (Z_IORequest *) 
1824         odr_malloc(out,sizeof(Z_IORequest));
1825     memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1826
1827     r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1828         odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1829     memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1830     r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1831         odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1832     memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1833
1834     r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1835     r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1836     r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1837
1838     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1839         (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1840     memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1841     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1842
1843     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1844         (int *) odr_malloc(out, sizeof(int));
1845     *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1846
1847     if (!strcmp (type, "item") || !strcmp(type, "2"))
1848     {
1849         printf ("using item-request\n");
1850         r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 
1851             create_external_itemRequest();
1852     }
1853     else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1854     {
1855         printf ("using ILL-request\n");
1856         r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 
1857             create_external_ILL_APDU(ILL_APDU_ILL_Request);
1858     }
1859     else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1860     {
1861     const char *xml_buf =
1862         "<itemorder>\n"
1863         "  <type>request</type>\n"
1864         "  <libraryNo>000200</libraryNo>\n"
1865         "  <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1866         "</itemorder>";
1867         r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1868             z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1869     }
1870     else
1871         r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1872
1873     return r;
1874 }
1875
1876 static int send_itemorder(const char *type, int itemno)
1877 {
1878     Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1879     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1880     oident ItemOrderRequest;
1881
1882     ItemOrderRequest.proto = PROTO_Z3950;
1883     ItemOrderRequest.oclass = CLASS_EXTSERV;
1884     ItemOrderRequest.value = VAL_ITEMORDER;
1885     req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1886     req->packageName = esPackageName;
1887
1888     req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1889
1890     send_apdu(apdu);
1891     return 0;
1892 }
1893
1894 static int only_z3950()
1895 {
1896     if (protocol == PROTO_HTTP)
1897     {
1898         printf ("Not supported by SRW\n");
1899         return 1;
1900     }
1901     return 0;
1902 }
1903
1904 static int cmd_update_common(const char *arg, int version);
1905
1906 static int cmd_update(const char *arg)
1907 {
1908     return cmd_update_common(arg, 1);
1909 }
1910
1911 static int cmd_update0(const char *arg)
1912 {
1913     return cmd_update_common(arg, 0);
1914 }
1915
1916 static int cmd_update_common(const char *arg, int version)
1917 {
1918     Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1919     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1920     Z_External *r;
1921     int oid[OID_SIZE];
1922     oident update_oid;
1923     char action[20], recid[20], fname[80];
1924     int action_no;
1925     Z_External *record_this = 0;
1926
1927     if (only_z3950())
1928         return 0;
1929     *action = 0;
1930     *recid = 0;
1931     *fname = 0;
1932     sscanf (arg, "%19s %19s %79s", action, recid, fname);
1933
1934     if (!strcmp (action, "insert"))
1935         action_no = Z_IUOriginPartToKeep_recordInsert;
1936     else if (!strcmp (action, "replace"))
1937         action_no = Z_IUOriginPartToKeep_recordReplace;
1938     else if (!strcmp (action, "delete"))
1939         action_no = Z_IUOriginPartToKeep_recordDelete;
1940     else if (!strcmp (action, "update"))
1941         action_no = Z_IUOriginPartToKeep_specialUpdate;
1942     else 
1943     {
1944         printf ("Bad action: %s\n", action);
1945         printf ("Possible values: insert, replace, delete, update\n");
1946         return 0;
1947     }
1948
1949     if (*fname)
1950     {
1951         FILE *inf;
1952         struct stat status;
1953         stat (fname, &status);
1954         if (S_ISREG(status.st_mode) && (inf = fopen(fname, "r")))
1955         {
1956             size_t len = status.st_size;
1957             char *buf = (char *) xmalloc (len);
1958
1959             fread (buf, 1, len, inf);
1960
1961             fclose (inf);
1962             
1963             record_this = z_ext_record (out, VAL_TEXT_XML, buf, len);
1964             
1965             xfree (buf);
1966         }
1967         else
1968         {
1969             printf ("File %s doesn't exist\n", fname);
1970             return 0;
1971         }
1972     }
1973     else
1974     {
1975         if (!record_last)
1976         {
1977             printf ("No last record (update ignored)\n");
1978             return 0;
1979         }
1980         record_this = record_last;
1981     }
1982
1983     update_oid.proto = PROTO_Z3950;
1984     update_oid.oclass = CLASS_EXTSERV;
1985     if (version == 0)
1986         update_oid.value = VAL_DBUPDATE0;
1987     else
1988         update_oid.value = VAL_DBUPDATE;
1989     oid_ent_to_oid (&update_oid, oid);
1990     req->packageType = odr_oiddup(out,oid);
1991     req->packageName = esPackageName;
1992     
1993     req->referenceId = set_refid (out);
1994
1995     r = req->taskSpecificParameters = (Z_External *)
1996         odr_malloc (out, sizeof(*r));
1997     r->direct_reference = odr_oiddup(out,oid);
1998     r->indirect_reference = 0;
1999     r->descriptor = 0;
2000     if (version == 0)
2001     {
2002         Z_IU0OriginPartToKeep *toKeep;
2003         Z_IU0SuppliedRecords *notToKeep;
2004
2005         r->which = Z_External_update0;
2006         r->u.update0 = (Z_IU0Update *) odr_malloc(out, sizeof(*r->u.update0));
2007         r->u.update0->which = Z_IUUpdate_esRequest;
2008         r->u.update0->u.esRequest = (Z_IU0UpdateEsRequest *)
2009             odr_malloc(out, sizeof(*r->u.update0->u.esRequest));
2010         toKeep = r->u.update0->u.esRequest->toKeep = (Z_IU0OriginPartToKeep *)
2011             odr_malloc(out, sizeof(*r->u.update0->u.esRequest->toKeep));
2012         
2013         toKeep->databaseName = databaseNames[0];
2014         toKeep->schema = 0;
2015         toKeep->elementSetName = 0;
2016
2017         toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2018         *toKeep->action = action_no;
2019         
2020         notToKeep = r->u.update0->u.esRequest->notToKeep = (Z_IU0SuppliedRecords *)
2021             odr_malloc(out, sizeof(*r->u.update0->u.esRequest->notToKeep));
2022         notToKeep->num = 1;
2023         notToKeep->elements = (Z_IU0SuppliedRecords_elem **)
2024             odr_malloc(out, sizeof(*notToKeep->elements));
2025         notToKeep->elements[0] = (Z_IU0SuppliedRecords_elem *)
2026             odr_malloc(out, sizeof(**notToKeep->elements));
2027         notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2028         if (*recid)
2029         {
2030             notToKeep->elements[0]->u.opaque = (Odr_oct *)
2031                 odr_malloc (out, sizeof(Odr_oct));
2032             notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2033             notToKeep->elements[0]->u.opaque->size = strlen(recid);
2034             notToKeep->elements[0]->u.opaque->len = strlen(recid);
2035         }
2036         else
2037             notToKeep->elements[0]->u.opaque = 0;
2038         notToKeep->elements[0]->supplementalId = 0;
2039         notToKeep->elements[0]->correlationInfo = 0;
2040         notToKeep->elements[0]->record = record_this;
2041     }
2042     else
2043     {
2044         Z_IUOriginPartToKeep *toKeep;
2045         Z_IUSuppliedRecords *notToKeep;
2046
2047         r->which = Z_External_update;
2048         r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
2049         r->u.update->which = Z_IUUpdate_esRequest;
2050         r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
2051             odr_malloc(out, sizeof(*r->u.update->u.esRequest));
2052         toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
2053             odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
2054         
2055         toKeep->databaseName = databaseNames[0];
2056         toKeep->schema = 0;
2057         toKeep->elementSetName = 0;
2058         toKeep->actionQualifier = 0;
2059         toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
2060         *toKeep->action = action_no;
2061
2062         notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
2063             odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
2064         notToKeep->num = 1;
2065         notToKeep->elements = (Z_IUSuppliedRecords_elem **)
2066             odr_malloc(out, sizeof(*notToKeep->elements));
2067         notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
2068             odr_malloc(out, sizeof(**notToKeep->elements));
2069         notToKeep->elements[0]->which = Z_IUSuppliedRecords_elem_opaque;
2070         if (*recid)
2071         {
2072             notToKeep->elements[0]->u.opaque = (Odr_oct *)
2073                 odr_malloc (out, sizeof(Odr_oct));
2074             notToKeep->elements[0]->u.opaque->buf = (unsigned char *) recid;
2075             notToKeep->elements[0]->u.opaque->size = strlen(recid);
2076             notToKeep->elements[0]->u.opaque->len = strlen(recid);
2077         }
2078         else
2079             notToKeep->elements[0]->u.opaque = 0;
2080         notToKeep->elements[0]->supplementalId = 0;
2081         notToKeep->elements[0]->correlationInfo = 0;
2082         notToKeep->elements[0]->record = record_this;
2083     }
2084     
2085     send_apdu(apdu);
2086
2087     return 2;
2088 }
2089
2090 static int cmd_itemorder(const char *arg)
2091 {
2092     char type[12];
2093     int itemno;
2094    
2095     if (only_z3950())
2096         return 0;
2097     if (sscanf (arg, "%10s %d", type, &itemno) != 2)
2098         return 0;
2099
2100     printf("Item order request\n");
2101     fflush(stdout);
2102     send_itemorder(type, itemno);
2103     return 2;
2104 }
2105
2106 static void show_opt(const char *arg, void *clientData)
2107 {
2108     printf ("%s ", arg);
2109 }
2110
2111 static int cmd_zversion(const char *arg)
2112 {
2113     if (*arg && arg)
2114         z3950_version = atoi(arg);
2115     else
2116         printf ("version is %d\n", z3950_version);
2117     return 0;
2118 }
2119
2120 static int cmd_options(const char *arg)
2121 {
2122     if (*arg)
2123     {
2124         int r;
2125         int pos;
2126         r = yaz_init_opt_encode(&z3950_options, arg, &pos);
2127     }
2128     else
2129     {
2130         yaz_init_opt_decode(&z3950_options, show_opt, 0);
2131         printf ("\n");
2132     }
2133     return 0;
2134 }
2135
2136 static int cmd_explain(const char *arg)
2137 {
2138     if (protocol != PROTO_HTTP)
2139         return 0;
2140 #if HAVE_XML2
2141     if (!conn)
2142         cmd_open(0);
2143     if (conn)
2144     {
2145         Z_SRW_PDU *sr = 0;
2146         
2147         setno = 1;
2148         
2149         /* save this for later .. when fetching individual records */
2150         sr = yaz_srw_get(out, Z_SRW_explain_request);
2151         send_srw(sr);
2152         return 2;
2153     }
2154 #endif
2155     return 0;
2156 }
2157
2158 static int cmd_init(const char *arg)
2159 {
2160     if (!conn || protocol != PROTO_Z3950)
2161        return 0;
2162     send_initRequest(0);
2163     return 2;
2164 }
2165
2166 static int cmd_find(const char *arg)
2167 {
2168     if (!*arg)
2169     {
2170         printf("Find what?\n");
2171         return 0;
2172     }
2173     if (protocol == PROTO_HTTP)
2174     {
2175 #if HAVE_XML2
2176         if (!conn)
2177             cmd_open(0);
2178         if (!conn)
2179             return 0;
2180         if (!send_SRW_searchRequest(arg))
2181             return 0;
2182 #else
2183         return 0;
2184 #endif
2185     }
2186     else
2187     {
2188         if (!conn)
2189         {
2190             try_reconnect(); 
2191             
2192             if (!conn) {                                        
2193                 printf("Not connected yet\n");
2194                 return 0;
2195             }
2196         }
2197         if (!send_searchRequest(arg))
2198             return 0;
2199     }
2200     return 2;
2201 }
2202
2203 static int cmd_delete(const char *arg)
2204 {
2205     if (!conn)
2206     {
2207         printf("Not connected yet\n");
2208         return 0;
2209     }
2210     if (only_z3950())
2211         return 0;
2212     if (!send_deleteResultSetRequest(arg))
2213         return 0;
2214     return 2;
2215 }
2216
2217 static int cmd_ssub(const char *arg)
2218 {
2219     if (!(smallSetUpperBound = atoi(arg)))
2220         return 0;
2221     return 1;
2222 }
2223
2224 static int cmd_lslb(const char *arg)
2225 {
2226     if (only_z3950())
2227         return 0;
2228     if (!(largeSetLowerBound = atoi(arg)))
2229         return 0;
2230     return 1;
2231 }
2232
2233 static int cmd_mspn(const char *arg)
2234 {
2235     if (only_z3950())
2236         return 0;
2237     if (!(mediumSetPresentNumber = atoi(arg)))
2238         return 0;
2239     return 1;
2240 }
2241
2242 static int cmd_status(const char *arg)
2243 {
2244     printf("smallSetUpperBound: %d\n", smallSetUpperBound);
2245     printf("largeSetLowerBound: %d\n", largeSetLowerBound);
2246     printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
2247     return 1;
2248 }
2249
2250 static int cmd_setnames(const char *arg)
2251 {
2252     if (*arg == '1')         /* enable ? */
2253         setnumber = 0;
2254     else if (*arg == '0')    /* disable ? */
2255         setnumber = -1;
2256     else if (setnumber < 0)  /* no args, toggle .. */
2257         setnumber = 0;
2258     else
2259         setnumber = -1;
2260    
2261     if (setnumber >= 0)
2262         printf("Set numbering enabled.\n");
2263     else
2264         printf("Set numbering disabled.\n");
2265     return 1;
2266 }
2267
2268 /* PRESENT SERVICE ----------------------------- */
2269
2270 static void parse_show_args(const char *arg_c, char *setstring,
2271                             int *start, int *number)
2272 {
2273     char arg[40];
2274     char *p;
2275
2276     strncpy(arg, arg_c, sizeof(arg)-1);
2277     arg[sizeof(arg)-1] = '\0';
2278
2279     if ((p = strchr(arg, '+')))
2280     {
2281         *number = atoi(p + 1);
2282         *p = '\0';
2283     }
2284     if (*arg)
2285         *start = atoi(arg);
2286     if (p && (p=strchr(p+1, '+')))
2287         strcpy (setstring, p+1);
2288     else if (setnumber >= 0)
2289         sprintf(setstring, "%d", setnumber);
2290     else
2291         *setstring = '\0';
2292 }
2293
2294 static int send_presentRequest(const char *arg)
2295 {
2296     Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
2297     Z_PresentRequest *req = apdu->u.presentRequest;
2298     Z_RecordComposition compo;
2299     oident prefsyn;
2300     int nos = 1;
2301     int oid[OID_SIZE];
2302     char setstring[100];
2303
2304     req->referenceId = set_refid (out);
2305
2306     parse_show_args(arg, setstring, &setno, &nos);
2307     if (*setstring)
2308         req->resultSetId = setstring;
2309
2310     req->resultSetStartPoint = &setno;
2311     req->numberOfRecordsRequested = &nos;
2312     prefsyn.proto = protocol;
2313     prefsyn.oclass = CLASS_RECSYN;
2314     prefsyn.value = recordsyntax;
2315     req->preferredRecordSyntax =
2316         odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
2317
2318     if (record_schema)
2319     {
2320         oident prefschema;
2321
2322         prefschema.proto = protocol;
2323         prefschema.oclass = CLASS_SCHEMA;
2324         prefschema.value = oid_getvalbyname(record_schema);
2325
2326         req->recordComposition = &compo;
2327         compo.which = Z_RecordComp_complex;
2328         compo.u.complex = (Z_CompSpec *)
2329             odr_malloc(out, sizeof(*compo.u.complex));
2330         compo.u.complex->selectAlternativeSyntax = (bool_t *) 
2331             odr_malloc(out, sizeof(bool_t));
2332         *compo.u.complex->selectAlternativeSyntax = 0;
2333
2334         compo.u.complex->generic = (Z_Specification *)
2335             odr_malloc(out, sizeof(*compo.u.complex->generic));
2336         compo.u.complex->generic->which = Z_Schema_oid;
2337         compo.u.complex->generic->schema.oid = (Odr_oid *)
2338             odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2339         if (!compo.u.complex->generic->schema.oid)
2340         {
2341             /* OID wasn't a schema! Try record syntax instead. */
2342             prefschema.oclass = CLASS_RECSYN;
2343             compo.u.complex->generic->schema.oid = (Odr_oid *)
2344                 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
2345         }
2346         if (!elementSetNames)
2347             compo.u.complex->generic->elementSpec = 0;
2348         else
2349         {
2350             compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
2351                 odr_malloc(out, sizeof(Z_ElementSpec));
2352             compo.u.complex->generic->elementSpec->which =
2353                 Z_ElementSpec_elementSetName;
2354             compo.u.complex->generic->elementSpec->u.elementSetName =
2355                 elementSetNames->u.generic;
2356         }
2357         compo.u.complex->num_dbSpecific = 0;
2358         compo.u.complex->dbSpecific = 0;
2359         compo.u.complex->num_recordSyntax = 0;
2360         compo.u.complex->recordSyntax = 0;
2361     }
2362     else if (elementSetNames)
2363     {
2364         req->recordComposition = &compo;
2365         compo.which = Z_RecordComp_simple;
2366         compo.u.simple = elementSetNames;
2367     }
2368     send_apdu(apdu);
2369     printf("Sent presentRequest (%d+%d).\n", setno, nos);
2370     return 2;
2371 }
2372
2373 #if HAVE_XML2
2374 static int send_SRW_presentRequest(const char *arg)
2375 {
2376     char setstring[100];
2377     int nos = 1;
2378     Z_SRW_PDU *sr = srw_sr;
2379
2380     if (!sr)
2381         return 0;
2382     parse_show_args(arg, setstring, &setno, &nos);
2383     sr->u.request->startRecord = odr_intdup(out, setno);
2384     sr->u.request->maximumRecords = odr_intdup(out, nos);
2385     if (record_schema)
2386         sr->u.request->recordSchema = record_schema;
2387     return send_srw(sr);
2388 }
2389 #endif
2390
2391 static void close_session (void)
2392 {
2393     if (conn)
2394         cs_close (conn);
2395     conn = 0;
2396     if (session_mem)
2397     {
2398         nmem_destroy (session_mem);
2399         session_mem = NULL;
2400     }
2401     sent_close = 0;
2402     odr_reset(out);
2403     odr_reset(in);
2404     odr_reset(print);
2405 }
2406
2407 void process_close(Z_Close *req)
2408 {
2409     Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
2410     Z_Close *res = apdu->u.close;
2411
2412     static char *reasons[] =
2413     {
2414         "finished",
2415         "shutdown",
2416         "system problem",
2417         "cost limit reached",
2418         "resources",
2419         "security violation",
2420         "protocolError",
2421         "lack of activity",
2422         "peer abort",
2423         "unspecified"
2424     };
2425
2426     printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
2427         req->diagnosticInformation ? req->diagnosticInformation : "NULL");
2428     if (sent_close)
2429         close_session ();
2430     else
2431     {
2432         *res->closeReason = Z_Close_finished;
2433         send_apdu(apdu);
2434         printf("Sent response.\n");
2435         sent_close = 1;
2436     }
2437 }
2438
2439 static int cmd_show(const char *arg)
2440 {
2441     if (protocol == PROTO_HTTP)
2442     {
2443 #if HAVE_XML2
2444         if (!conn)
2445             cmd_open(0);
2446         if (!conn)
2447             return 0;
2448         if (!send_SRW_presentRequest(arg))
2449             return 0;
2450 #else
2451         return 0;
2452 #endif
2453     }
2454     else
2455     {
2456         if (!conn)
2457         {
2458             printf("Not connected yet\n");
2459             return 0;
2460         }
2461         if (!send_presentRequest(arg))
2462             return 0;
2463     }
2464     return 2;
2465 }
2466
2467 int cmd_quit(const char *arg)
2468 {
2469     printf("See you later, alligator.\n");
2470     xmalloc_trav ("");
2471     exit(0);
2472     return 0;
2473 }
2474
2475 int cmd_cancel(const char *arg)
2476 {
2477     Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
2478     Z_TriggerResourceControlRequest *req =
2479         apdu->u.triggerResourceControlRequest;
2480     bool_t rfalse = 0;
2481     
2482     if (!conn)
2483     {
2484         printf("Session not initialized yet\n");
2485         return 0;
2486     }
2487     if (only_z3950())
2488         return 0;
2489     if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
2490     {
2491         printf("Target doesn't support cancel (trigger resource ctrl)\n");
2492         return 0;
2493     }
2494     *req->requestedAction = Z_TriggerResourceCtrl_cancel;
2495     req->resultSetWanted = &rfalse;
2496
2497     send_apdu(apdu);
2498     printf("Sent cancel request\n");
2499     return 2;
2500 }
2501
2502 int send_scanrequest(const char *query, int pp, int num, const char *term)
2503 {
2504     Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
2505     Z_ScanRequest *req = apdu->u.scanRequest;
2506     int oid[OID_SIZE];
2507     
2508     if (only_z3950())
2509         return 0;
2510     if (queryType == QueryType_CCL2RPN)
2511     {
2512         oident bib1;
2513         int error, pos;
2514         struct ccl_rpn_node *rpn;
2515
2516         rpn = ccl_find_str (bibset,  query, &error, &pos);
2517         if (error)
2518         {
2519             printf("CCL ERROR: %s\n", ccl_err_msg(error));
2520             return -1;
2521         }
2522         bib1.proto = PROTO_Z3950;
2523         bib1.oclass = CLASS_ATTSET;
2524         bib1.value = VAL_BIB1;
2525         req->attributeSet = oid_ent_to_oid (&bib1, oid);
2526         if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
2527         {
2528             printf("Couldn't convert CCL to Scan term\n");
2529             return -1;
2530         }
2531         ccl_rpn_delete (rpn);
2532     }
2533     else
2534     {
2535         YAZ_PQF_Parser pqf_parser = yaz_pqf_create ();
2536
2537         if (!(req->termListAndStartPoint =
2538               yaz_pqf_scan(pqf_parser, out, &req->attributeSet, query)))
2539         {
2540             const char *pqf_msg;
2541             size_t off;
2542             int code = yaz_pqf_error (pqf_parser, &pqf_msg, &off);
2543             printf("%*s^\n", off+7, "");
2544             printf("Prefix query error: %s (code %d)\n", pqf_msg, code);
2545             yaz_pqf_destroy (pqf_parser);
2546             return -1;
2547         }
2548         yaz_pqf_destroy (pqf_parser);
2549     }
2550     if (term && *term)
2551     {
2552         if (req->termListAndStartPoint->term &&
2553             req->termListAndStartPoint->term->which == Z_Term_general &&
2554             req->termListAndStartPoint->term->u.general)
2555         {
2556             req->termListAndStartPoint->term->u.general->buf =
2557                 (unsigned char *) odr_strdup(out, term);
2558             req->termListAndStartPoint->term->u.general->len =
2559                 req->termListAndStartPoint->term->u.general->size =
2560                 strlen(term);
2561         }
2562     }
2563     req->referenceId = set_refid (out);
2564     req->num_databaseNames = num_databaseNames;
2565     req->databaseNames = databaseNames;
2566     req->numberOfTermsRequested = &num;
2567     req->preferredPositionInResponse = &pp;
2568     send_apdu(apdu);
2569     return 2;
2570 }
2571
2572 int send_sortrequest(const char *arg, int newset)
2573 {
2574     Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
2575     Z_SortRequest *req = apdu->u.sortRequest;
2576     Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
2577         odr_malloc (out, sizeof(*sksl));
2578     char setstring[32];
2579
2580     if (only_z3950())
2581         return 0;
2582     if (setnumber >= 0)
2583         sprintf (setstring, "%d", setnumber);
2584     else
2585         sprintf (setstring, "default");
2586
2587     req->referenceId = set_refid (out);
2588
2589     req->num_inputResultSetNames = 1;
2590     req->inputResultSetNames = (Z_InternationalString **)
2591         odr_malloc (out, sizeof(*req->inputResultSetNames));
2592     req->inputResultSetNames[0] = odr_strdup (out, setstring);
2593
2594     if (newset && setnumber >= 0)
2595         sprintf (setstring, "%d", ++setnumber);
2596
2597     req->sortedResultSetName = odr_strdup (out, setstring);
2598
2599     req->sortSequence = yaz_sort_spec (out, arg);
2600     if (!req->sortSequence)
2601     {
2602         printf ("Missing sort specifications\n");
2603         return -1;
2604     }
2605     send_apdu(apdu);
2606     return 2;
2607 }
2608
2609 void display_term(Z_TermInfo *t)
2610 {
2611     if (t->displayTerm)
2612         printf("%s", t->displayTerm);
2613     else if (t->term->which == Z_Term_general)
2614     {
2615         printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
2616         sprintf(last_scan_line, "%.*s", t->term->u.general->len,
2617             t->term->u.general->buf);
2618     }
2619     else
2620         printf("Term (not general)");
2621     if (t->globalOccurrences)
2622         printf (" (%d)\n", *t->globalOccurrences);
2623     else
2624         printf ("\n");
2625 }
2626
2627 void process_scanResponse(Z_ScanResponse *res)
2628 {
2629     int i;
2630     Z_Entry **entries = NULL;
2631     int num_entries = 0;
2632    
2633     printf("Received ScanResponse\n"); 
2634     print_refid (res->referenceId);
2635     printf("%d entries", *res->numberOfEntriesReturned);
2636     if (res->positionOfTerm)
2637         printf (", position=%d", *res->positionOfTerm); 
2638     printf ("\n");
2639     if (*res->scanStatus != Z_Scan_success)
2640         printf("Scan returned code %d\n", *res->scanStatus);
2641     if (!res->entries)
2642         return;
2643     if ((entries = res->entries->entries))
2644         num_entries = res->entries->num_entries;
2645     for (i = 0; i < num_entries; i++)
2646     {
2647         int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
2648         if (entries[i]->which == Z_Entry_termInfo)
2649         {
2650             printf("%c ", i + 1 == pos_term ? '*' : ' ');
2651             display_term(entries[i]->u.termInfo);
2652         }
2653         else
2654             display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
2655     }
2656     if (res->entries->nonsurrogateDiagnostics)
2657         display_diagrecs (res->entries->nonsurrogateDiagnostics,
2658                           res->entries->num_nonsurrogateDiagnostics);
2659 }
2660
2661 void process_sortResponse(Z_SortResponse *res)
2662 {
2663     printf("Received SortResponse: status=");
2664     switch (*res->sortStatus)
2665     {
2666     case Z_SortStatus_success:
2667         printf ("success"); break;
2668     case Z_SortStatus_partial_1:
2669         printf ("partial"); break;
2670     case Z_SortStatus_failure:
2671         printf ("failure"); break;
2672     default:
2673         printf ("unknown (%d)", *res->sortStatus);
2674     }
2675     printf ("\n");
2676     print_refid (res->referenceId);
2677     if (res->diagnostics)
2678         display_diagrecs(res->diagnostics,
2679                          res->num_diagnostics);
2680 }
2681
2682 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
2683 {
2684     printf("Got deleteResultSetResponse status=%d\n",
2685            *res->deleteOperationStatus);
2686     if (res->deleteListStatuses)
2687     {
2688         int i;
2689         for (i = 0; i < res->deleteListStatuses->num; i++)
2690         {
2691             printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
2692                     *res->deleteListStatuses->elements[i]->status);
2693         }
2694     }
2695 }
2696
2697 int cmd_sort_generic(const char *arg, int newset)
2698 {
2699     if (!conn)
2700     {
2701         printf("Session not initialized yet\n");
2702         return 0;
2703     }
2704     if (only_z3950())
2705         return 0;
2706     if (!ODR_MASK_GET(session->options, Z_Options_sort))
2707     {
2708         printf("Target doesn't support sort\n");
2709         return 0;
2710     }
2711     if (*arg)
2712     {
2713         if (send_sortrequest(arg, newset) < 0)
2714             return 0;
2715         return 2;
2716     }
2717     return 0;
2718 }
2719
2720 int cmd_sort(const char *arg)
2721 {
2722     return cmd_sort_generic (arg, 0);
2723 }
2724
2725 int cmd_sort_newset (const char *arg)
2726 {
2727     return cmd_sort_generic (arg, 1);
2728 }
2729
2730 int cmd_scan(const char *arg)
2731 {
2732     if (only_z3950())
2733         return 0;
2734     if (!conn)
2735     {
2736         try_reconnect();
2737         
2738         if (!conn) {                                                            
2739             printf("Session not initialized yet\n");
2740             return 0;
2741         }
2742     }
2743     if (!ODR_MASK_GET(session->options, Z_Options_scan))
2744     {
2745         printf("Target doesn't support scan\n");
2746         return 0;
2747     }
2748     if (*arg)
2749     {
2750         strcpy (last_scan_query, arg);
2751         if (send_scanrequest(arg, 1, 20, 0) < 0)
2752             return 0;
2753     }
2754     else
2755     {
2756         if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
2757             return 0;
2758     }
2759     return 2;
2760 }
2761
2762 int cmd_schema(const char *arg)
2763 {
2764     xfree(record_schema);
2765     record_schema = 0;
2766     if (arg && *arg)
2767         record_schema = xstrdup(arg);
2768     return 1;
2769 }
2770
2771 int cmd_format(const char *arg)
2772 {
2773     oid_value nsyntax;
2774     if (!arg || !*arg)
2775     {
2776         printf("Usage: format <recordsyntax>\n");
2777         return 0;
2778     }
2779     nsyntax = oid_getvalbyname (arg);
2780     if (strcmp(arg, "none") && nsyntax == VAL_NONE)
2781     {
2782         printf ("unknown record syntax\n");
2783         return 0;
2784     }
2785     recordsyntax = nsyntax;
2786     return 1;
2787 }
2788
2789 int cmd_elements(const char *arg)
2790 {
2791     static Z_ElementSetNames esn;
2792     static char what[100];
2793
2794     if (!arg || !*arg)
2795     {
2796         elementSetNames = 0;
2797         return 1;
2798     }
2799     strcpy(what, arg);
2800     esn.which = Z_ElementSetNames_generic;
2801     esn.u.generic = what;
2802     elementSetNames = &esn;
2803     return 1;
2804 }
2805
2806 int cmd_attributeset(const char *arg)
2807 {
2808     char what[100];
2809
2810     if (!arg || !*arg)
2811     {
2812         printf("Usage: attributeset <setname>\n");
2813         return 0;
2814     }
2815     sscanf(arg, "%s", what);
2816     if (p_query_attset (what))
2817     {
2818         printf("Unknown attribute set name\n");
2819         return 0;
2820     }
2821     return 1;
2822 }
2823
2824 int cmd_querytype (const char *arg)
2825 {
2826     if (!strcmp (arg, "ccl"))
2827         queryType = QueryType_CCL;
2828     else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2829         queryType = QueryType_Prefix;
2830     else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2831         queryType = QueryType_CCL2RPN;
2832     else if (!strcmp(arg, "cql"))
2833         queryType = QueryType_CQL;        
2834     else if (!strcmp (arg, "cql2rpn") || !strcmp (arg, "cqlrpn"))
2835         queryType = QueryType_CQL2RPN;
2836     else
2837     {
2838         printf ("Querytype must be one of:\n");
2839         printf (" prefix         - Prefix query\n");
2840         printf (" ccl            - CCL query\n");
2841         printf (" ccl2rpn        - CCL query converted to RPN\n");
2842         printf (" cql            - CQL\n");
2843         printf (" cql2rpn        - CQL query converted to RPN\n");
2844         return 0;
2845     }
2846     return 1;
2847 }
2848
2849 int cmd_refid (const char *arg)
2850 {
2851     xfree (refid);
2852     refid = NULL;
2853     if (*arg)
2854     {
2855         refid = (char *) xmalloc (strlen(arg)+1);
2856         strcpy (refid, arg);
2857     }
2858     return 1;
2859 }
2860
2861 int cmd_close(const char *arg)
2862 {
2863     Z_APDU *apdu;
2864     Z_Close *req;
2865     if (!conn)
2866         return 0;
2867     if (only_z3950())
2868         return 0;
2869
2870     apdu = zget_APDU(out, Z_APDU_close);
2871     req = apdu->u.close;
2872     *req->closeReason = Z_Close_finished;
2873     send_apdu(apdu);
2874     printf("Sent close request.\n");
2875     sent_close = 1;
2876     return 2;
2877 }
2878
2879 int cmd_packagename(const char* arg)
2880 {
2881     xfree (esPackageName);
2882     esPackageName = NULL;
2883     if (*arg)
2884         esPackageName = xstrdup(arg);
2885     return 1;
2886 }
2887
2888 int cmd_proxy(const char* arg)
2889 {
2890     xfree (yazProxy);
2891     yazProxy = NULL;
2892     if (*arg)
2893         yazProxy = xstrdup (arg);
2894     return 1;
2895 }
2896
2897 int cmd_marccharset(const char *arg)
2898 {
2899     char l1[30];
2900
2901     *l1 = 0;
2902     if (sscanf(arg, "%29s", l1) < 1)
2903         return 1;
2904     xfree (marcCharset);
2905     marcCharset = 0;
2906     if (strcmp(l1, "-"))
2907         marcCharset = xstrdup(l1);
2908     return 1;
2909 }
2910
2911 int cmd_charset(const char* arg)
2912 {
2913     char l1[30], l2[30];
2914
2915     *l1 = *l2 = 0;
2916     if (sscanf(arg, "%29s %29s", l1, l2) < 1)
2917     {
2918         printf("Current negotiation character set is `%s'\n", 
2919                negotiationCharset ? negotiationCharset: "none");
2920         printf("Current output character set is `%s'\n", 
2921                outputCharset ? outputCharset: "none");
2922         return 1;
2923     }
2924     xfree (negotiationCharset);
2925     negotiationCharset = NULL;
2926     if (*l1 && strcmp(l1, "-"))
2927     {
2928         negotiationCharset = xstrdup(l1);
2929         printf ("Character set negotiation : %s\n", negotiationCharset);
2930     }
2931     else
2932         printf ("Character set negotiation disabled\n");
2933     if (*l2)
2934     {
2935         xfree (outputCharset);
2936         outputCharset = 0;
2937         if (!strcmp(l2, "auto") && codeset)
2938         {
2939             if (codeset)
2940             {
2941                 printf ("output charset: %s\n", codeset);
2942                 outputCharset = xstrdup(codeset);
2943
2944
2945             }
2946             else
2947                 printf ("No codeset found on this system\n");
2948         }
2949         else if (strcmp(l2, "-"))
2950             outputCharset = xstrdup(l2);
2951         else
2952             printf ("Output charset conversion disabled\n");
2953     } 
2954
2955     return 1;
2956 }
2957
2958 int cmd_lang(const char* arg)
2959 {
2960     if (*arg == '\0') {
2961         printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2962         return 1;
2963     }
2964     xfree (yazLang);
2965     yazLang = NULL;
2966     if (*arg)
2967     {
2968         yazLang = (char *) xmalloc (strlen(arg)+1);
2969         strcpy (yazLang, arg);
2970     } 
2971     return 1;
2972 }
2973
2974 int cmd_source(const char* arg) 
2975 {
2976     /* first should open the file and read one line at a time.. */
2977     FILE* includeFile;
2978     char line[1024], *cp;
2979
2980     if(strlen(arg)<1) {
2981         fprintf(stderr,"Error in source command use a filename\n");
2982         return -1;
2983     }
2984     
2985     includeFile = fopen (arg, "r");
2986     
2987     if(!includeFile) {
2988         fprintf(stderr,"Unable to open file %s for reading\n",arg);
2989         return -1;
2990     }
2991     
2992     while(!feof(includeFile)) {
2993         memset(line,0,sizeof(line));
2994         fgets(line,sizeof(line),includeFile);
2995         
2996         if(strlen(line) < 2) continue;
2997         if(line[0] == '#') continue;
2998         
2999         if ((cp = strrchr (line, '\n')))
3000             *cp = '\0';
3001         
3002         process_cmd_line(line);
3003     }
3004     
3005     if(fclose(includeFile)<0) {
3006         perror("unable to close include file");
3007         exit(1);
3008     }
3009     return 1;
3010 }
3011
3012 int cmd_subshell(const char* args)
3013 {
3014     if(strlen(args)) 
3015         system(args);
3016     else 
3017         system(getenv("SHELL"));
3018     
3019     printf("\n");
3020     return 1;
3021 }
3022
3023 int cmd_set_berfile(const char *arg)
3024 {
3025     if (ber_file && ber_file != stdout && ber_file != stderr)
3026         fclose(ber_file);
3027     if (!strcmp(arg, ""))
3028         ber_file = 0;
3029     else if (!strcmp(arg, "-"))
3030         ber_file = stdout;
3031     else
3032         ber_file = fopen(arg, "a");
3033     return 1;
3034 }
3035
3036 int cmd_set_apdufile(const char *arg)
3037 {
3038     if(apdu_file && apdu_file != stderr && apdu_file != stderr)
3039         fclose(apdu_file);
3040     if (!strcmp(arg, ""))
3041         apdu_file = 0;
3042     else if (!strcmp(arg, "-"))
3043         apdu_file = stderr;
3044     else
3045     {
3046         apdu_file = fopen(arg, "a");
3047         if (!apdu_file)
3048             perror("unable to open apdu log file");
3049     }
3050     if (apdu_file)
3051         odr_setprint(print, apdu_file);
3052     return 1;
3053 }
3054
3055 int cmd_set_cclfile(const char* arg)
3056 {  
3057     FILE *inf;
3058
3059     bibset = ccl_qual_mk (); 
3060     inf = fopen (arg, "r");
3061     if (!inf)
3062         perror("unable to open CCL file");
3063     else
3064     {
3065         ccl_qual_file (bibset, inf);
3066         fclose (inf);
3067     }
3068     strcpy(ccl_fields,arg);
3069     return 0;
3070 }
3071
3072 int cmd_set_cqlfile(const char* arg)
3073 {
3074     cql_transform_t newcqltrans;
3075
3076     if ((newcqltrans = cql_transform_open_fname(arg)) == 0) {
3077         perror("unable to open CQL file");
3078         return 0;
3079     }
3080     if (cqltrans != 0)
3081         cql_transform_close(cqltrans);
3082
3083     cqltrans = newcqltrans;
3084     strcpy(cql_fields, arg);
3085     return 0;
3086 }
3087
3088 int cmd_set_auto_reconnect(const char* arg)
3089 {  
3090     if(strlen(arg)==0) {
3091         auto_reconnect = ! auto_reconnect;
3092     } else if(strcmp(arg,"on")==0) {
3093         auto_reconnect = 1;
3094     } else if(strcmp(arg,"off")==0) {
3095         auto_reconnect = 0;             
3096     } else {
3097         printf("Error use on or off\n");
3098         return 1;
3099     }
3100     
3101     if (auto_reconnect)
3102         printf("Set auto reconnect enabled.\n");
3103     else
3104         printf("Set auto reconnect disabled.\n");
3105     
3106     return 0;
3107 }
3108
3109 int cmd_set_marcdump(const char* arg)
3110 {
3111     if(marc_file && marc_file != stderr) { /* don't close stdout*/
3112         fclose(marc_file);
3113     }
3114
3115     if (!strcmp(arg, ""))
3116         marc_file = 0;
3117     else if (!strcmp(arg, "-"))
3118         marc_file = stderr;
3119     else
3120     {
3121         marc_file = fopen(arg, "a");
3122         if (!marc_file)
3123             perror("unable to open marc log file");
3124     }
3125     return 1;
3126 }
3127
3128 /* 
3129    this command takes 3 arge {name class oid} 
3130 */
3131 int cmd_register_oid(const char* args) {
3132     static struct {
3133         char* className;
3134         oid_class oclass;
3135     } oid_classes[] = {
3136         {"appctx",CLASS_APPCTX},
3137         {"absyn",CLASS_ABSYN},
3138         {"attset",CLASS_ATTSET},
3139         {"transyn",CLASS_TRANSYN},
3140         {"diagset",CLASS_DIAGSET},
3141         {"recsyn",CLASS_RECSYN},
3142         {"resform",CLASS_RESFORM},
3143         {"accform",CLASS_ACCFORM},
3144         {"extserv",CLASS_EXTSERV},
3145         {"userinfo",CLASS_USERINFO},
3146         {"elemspec",CLASS_ELEMSPEC},
3147         {"varset",CLASS_VARSET},
3148         {"schema",CLASS_SCHEMA},
3149         {"tagset",CLASS_TAGSET},
3150         {"general",CLASS_GENERAL},
3151         {0,(enum oid_class) 0}
3152     };
3153     char oname_str[101], oclass_str[101], oid_str[101];  
3154     char* name;
3155     int i;
3156     oid_class oidclass = CLASS_GENERAL;
3157     int val = 0, oid[OID_SIZE];
3158     struct oident * new_oident=NULL;
3159     
3160     if (sscanf (args, "%100[^ ] %100[^ ] %100s",
3161                 oname_str,oclass_str, oid_str) < 1) {
3162         printf("Error in regristrate command \n");
3163         return 0;
3164     }
3165     
3166     for (i = 0; oid_classes[i].className; i++) {
3167         if (!strcmp(oid_classes[i].className, oclass_str))
3168         {
3169             oidclass=oid_classes[i].oclass;
3170             break;
3171         }
3172     }
3173     
3174     if(!(oid_classes[i].className)) {
3175         printf("Unknonwn oid class %s\n",oclass_str);
3176         return 0;
3177     }
3178     
3179     i = 0;
3180     name = oid_str;
3181     val = 0;
3182     
3183     while (isdigit (*name))
3184     {
3185         val = val*10 + (*name - '0');
3186         name++;
3187         if (*name == '.')
3188         {
3189             if (i < OID_SIZE-1)
3190                 oid[i++] = val;
3191             val = 0;
3192             name++;
3193         }
3194     }
3195     oid[i] = val;
3196     oid[i+1] = -1;
3197     
3198     new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);  
3199     if(strcmp(new_oident->desc,oname_str)) {
3200         fprintf(stderr,"oid is already named as %s, regristration faild\n",
3201                 new_oident->desc);
3202     }
3203     return 1;  
3204 }
3205
3206 int cmd_push_command(const char* arg) 
3207 {
3208 #if HAVE_READLINE_HISTORY_H
3209     if(strlen(arg)>1) 
3210         add_history(arg);
3211 #else 
3212     fprintf(stderr,"Not compiled with the readline/history module\n");
3213 #endif
3214     return 1;
3215 }
3216
3217 void source_rcfile() 
3218 {
3219     /*  Look for a $HOME/.yazclientrc and source it if it exists */
3220     struct stat statbuf;
3221     char buffer[1000];
3222     char* homedir=getenv("HOME");
3223     
3224     if(!homedir) return;
3225     
3226     sprintf(buffer,"%s/.yazclientrc",homedir);
3227     
3228     if(stat(buffer,&statbuf)==0) {
3229         cmd_source(buffer);
3230     }
3231     
3232     if(stat(".yazclientrc",&statbuf)==0) {
3233         cmd_source(".yazclientrc");
3234     }
3235 }
3236
3237
3238 static void initialize(void)
3239 {
3240     FILE *inf;
3241     int i;
3242     
3243     if (!(out = odr_createmem(ODR_ENCODE)) ||
3244         !(in = odr_createmem(ODR_DECODE)) ||
3245         !(print = odr_createmem(ODR_PRINT)))
3246     {
3247         fprintf(stderr, "failed to allocate ODR streams\n");
3248         exit(1);
3249     }
3250     oid_init();
3251     
3252     setvbuf(stdout, 0, _IONBF, 0);
3253     if (apdu_file)
3254         odr_setprint(print, apdu_file);
3255
3256     bibset = ccl_qual_mk (); 
3257     inf = fopen (ccl_fields, "r");
3258     if (inf)
3259     {
3260         ccl_qual_file (bibset, inf);
3261         fclose (inf);
3262     }
3263
3264     cqltrans = cql_transform_open_fname(cql_fields);
3265     /* If this fails, no problem: we detect cqltrans == 0 later */
3266
3267 #if HAVE_READLINE_READLINE_H
3268     rl_attempted_completion_function = (CPPFunction*)readline_completer;
3269 #endif
3270     
3271     
3272     for(i=0; i<maxOtherInfosSupported; ++i) {
3273         extraOtherInfos[i].oidval = -1;
3274     }
3275     
3276     source_rcfile();
3277 }
3278
3279
3280 #if HAVE_GETTIMEOFDAY
3281 struct timeval tv_start, tv_end;
3282 #endif
3283
3284 #if HAVE_XML2
3285 static void handle_srw_record(Z_SRW_record *rec)
3286 {
3287     if (rec->recordPosition)
3288     {
3289         printf ("pos=%d", *rec->recordPosition);
3290         setno = *rec->recordPosition + 1;
3291     }
3292     if (rec->recordSchema)
3293         printf (" schema=%s", rec->recordSchema);
3294     printf ("\n");
3295     if (rec->recordData_buf && rec->recordData_len)
3296         fwrite(rec->recordData_buf, 1, rec->recordData_len, stdout);
3297     else
3298         printf ("No data!");
3299     printf("\n");
3300 }
3301
3302 static void handle_srw_explain_response(Z_SRW_explainResponse *res)
3303 {
3304     handle_srw_record(&res->record);
3305 }
3306
3307 static void handle_srw_response(Z_SRW_searchRetrieveResponse *res)
3308 {
3309     int i;
3310
3311     printf ("Received SRW SearchRetrieve Response\n");
3312     
3313     for (i = 0; i<res->num_diagnostics; i++)
3314     {
3315         printf ("SRW diagnostic %s\n",
3316                 res->diagnostics[i].code);
3317         if (res->diagnostics[i].message)
3318             printf ("Message: %s\n", res->diagnostics[i].message);
3319         if (res->diagnostics[i].details)
3320             printf ("Details: %s\n", res->diagnostics[i].details);
3321     }
3322     if (res->numberOfRecords)
3323         printf ("Number of hits: %d\n", *res->numberOfRecords);
3324     for (i = 0; i<res->num_records; i++)
3325         handle_srw_record(res->records + i);
3326 }
3327
3328 static void http_response(Z_HTTP_Response *hres)
3329 {
3330     int ret = -1;
3331     const char *content_type = z_HTTP_header_lookup(hres->headers,
3332                                                     "Content-Type");
3333     const char *connection_head = z_HTTP_header_lookup(hres->headers,
3334                                                        "Connection");
3335     if (content_type && !yaz_strcmp_del("text/xml", content_type, "; "))
3336     {
3337         Z_SOAP *soap_package = 0;
3338         ODR o = odr_createmem(ODR_DECODE);
3339         Z_SOAP_Handler soap_handlers[2] = {
3340             {"http://www.loc.gov/zing/srw/", 0,
3341              (Z_SOAP_fun) yaz_srw_codec},
3342             {0, 0, 0}
3343         };
3344         ret = z_soap_codec(o, &soap_package,
3345                            &hres->content_buf, &hres->content_len,
3346                            soap_handlers);
3347         if (!ret && soap_package->which == Z_SOAP_generic &&
3348             soap_package->u.generic->no == 0)
3349         {
3350             Z_SRW_PDU *sr = soap_package->u.generic->p;
3351             if (sr->which == Z_SRW_searchRetrieve_response)
3352                 handle_srw_response(sr->u.response);
3353             else if (sr->which == Z_SRW_explain_response)
3354                 handle_srw_explain_response(sr->u.explain_response);
3355             else
3356                 ret = -1;
3357         }
3358         else if (soap_package && (soap_package->which == Z_SOAP_fault
3359                           || soap_package->which == Z_SOAP_error))
3360         {
3361             printf ("HTTP Error Status=%d\n", hres->code);
3362             printf ("SOAP Fault code %s\n",
3363                     soap_package->u.fault->fault_code);
3364             printf ("SOAP Fault string %s\n", 
3365                     soap_package->u.fault->fault_string);
3366             if (soap_package->u.fault->details)
3367                 printf ("SOAP Details %s\n", 
3368                         soap_package->u.fault->details);
3369         }
3370         else
3371             ret = -1;
3372         odr_destroy(o);
3373     }
3374     if (ret)
3375     {
3376         if (hres->code != 200)
3377         {
3378             printf ("HTTP Error Status=%d\n", hres->code);
3379         }
3380         else
3381         {
3382             printf ("Decoding of SRW package failed\n");
3383         }
3384         close_session();
3385     }
3386     else
3387     {
3388         if (!strcmp(hres->version, "1.0"))
3389         {
3390             /* HTTP 1.0: only if Keep-Alive we stay alive.. */
3391             if (!connection_head || strcmp(connection_head, "Keep-Alive"))
3392                 close_session();
3393         }
3394         else 
3395         {
3396             /* HTTP 1.1: only if no close we stay alive .. */
3397             if (connection_head && !strcmp(connection_head, "close"))
3398                 close_session();
3399         }
3400     }
3401 }
3402 #endif
3403
3404 void wait_and_handle_response() 
3405 {
3406     int reconnect_ok = 1;
3407     int res;
3408     char *netbuffer= 0;
3409     int netbufferlen = 0;
3410     Z_GDU *gdu;
3411     
3412     while(conn)
3413     {
3414         res = cs_get(conn, &netbuffer, &netbufferlen);
3415         if (reconnect_ok && res <= 0 && protocol == PROTO_HTTP)
3416         {
3417             cs_close(conn);
3418             conn = 0;
3419             cmd_open(0);
3420             reconnect_ok = 0;
3421             if (conn)
3422             {
3423                 char *buf_out;
3424                 int len_out;
3425                 
3426                 buf_out = odr_getbuf(out, &len_out, 0);
3427                 
3428                 do_hex_dump(buf_out, len_out);
3429
3430                 cs_put(conn, buf_out, len_out);
3431                 
3432                 odr_reset(out);
3433                 continue;
3434             }
3435         }
3436         else if (res <= 0)
3437         {
3438             printf("Target closed connection\n");
3439             close_session();
3440             break;
3441         }
3442         odr_reset(out);
3443         odr_reset(in); /* release APDU from last round */
3444         record_last = 0;
3445         do_hex_dump(netbuffer, res);
3446         odr_setbuf(in, netbuffer, res, 0);
3447         
3448         if (!z_GDU(in, &gdu, 0, 0))
3449         {
3450             FILE *f = ber_file ? ber_file : stdout;
3451             odr_perror(in, "Decoding incoming APDU");
3452             fprintf(f, "[Near %d]\n", odr_offset(in));
3453             fprintf(f, "Packet dump:\n---------\n");
3454             odr_dumpBER(f, netbuffer, res);
3455             fprintf(f, "---------\n");
3456             if (apdu_file)
3457             {
3458                 z_GDU(print, &gdu, 0, 0);
3459                 odr_reset(print);
3460             }
3461             if (conn && cs_more(conn))
3462                 continue;
3463             break;
3464         }
3465         if (ber_file)
3466             odr_dumpBER(ber_file, netbuffer, res);
3467         if (apdu_file && !z_GDU(print, &gdu, 0, 0))
3468         {
3469             odr_perror(print, "Failed to print incoming APDU");
3470             odr_reset(print);
3471                 continue;
3472         }
3473         if (gdu->which == Z_GDU_Z3950)
3474         {
3475             Z_APDU *apdu = gdu->u.z3950;
3476             switch(apdu->which)
3477             {
3478             case Z_APDU_initResponse:
3479                 process_initResponse(apdu->u.initResponse);
3480                 break;
3481             case Z_APDU_searchResponse:
3482                 process_searchResponse(apdu->u.searchResponse);
3483                 break;
3484             case Z_APDU_scanResponse:
3485                 process_scanResponse(apdu->u.scanResponse);
3486                 break;
3487             case Z_APDU_presentResponse:
3488                 print_refid (apdu->u.presentResponse->referenceId);
3489                 setno +=
3490                     *apdu->u.presentResponse->numberOfRecordsReturned;
3491                 if (apdu->u.presentResponse->records)
3492                     display_records(apdu->u.presentResponse->records);
3493                 else
3494                     printf("No records.\n");
3495                 printf ("nextResultSetPosition = %d\n",
3496                         *apdu->u.presentResponse->nextResultSetPosition);
3497                 break;
3498             case Z_APDU_sortResponse:
3499                 process_sortResponse(apdu->u.sortResponse);
3500                 break;
3501             case Z_APDU_extendedServicesResponse:
3502                 printf("Got extended services response\n");
3503                 process_ESResponse(apdu->u.extendedServicesResponse);
3504                 break;
3505             case Z_APDU_close:
3506                 printf("Target has closed the association.\n");
3507                 process_close(apdu->u.close);
3508                 break;
3509             case Z_APDU_resourceControlRequest:
3510                 process_resourceControlRequest
3511                     (apdu->u.resourceControlRequest);
3512                 break;
3513             case Z_APDU_deleteResultSetResponse:
3514                 process_deleteResultSetResponse(apdu->u.
3515                                                 deleteResultSetResponse);
3516                 break;
3517             default:
3518                 printf("Received unknown APDU type (%d).\n", 
3519                        apdu->which);
3520                 close_session ();
3521             }
3522         }
3523 #if HAVE_XML2
3524         else if (gdu->which == Z_GDU_HTTP_Response)
3525         {
3526             http_response(gdu->u.HTTP_Response);
3527         }
3528 #endif
3529         if (conn && !cs_more(conn))
3530             break;
3531     }
3532     if (conn)
3533     {
3534 #if HAVE_GETTIMEOFDAY
3535         gettimeofday (&tv_end, 0);
3536 #if 0
3537         printf ("S/U S/U=%ld/%ld %ld/%ld",
3538                 (long) tv_start.tv_sec,
3539                 (long) tv_start.tv_usec,
3540                 (long) tv_end.tv_sec,
3541                 (long) tv_end.tv_usec);
3542 #endif
3543         printf ("Elapsed: %.6f\n",
3544                 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
3545                 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
3546 #endif
3547     }
3548     xfree (netbuffer);
3549 }
3550
3551
3552 int cmd_cclparse(const char* arg) 
3553 {
3554     int error, pos;
3555     struct ccl_rpn_node *rpn=NULL;
3556     
3557     
3558     rpn = ccl_find_str (bibset, arg, &error, &pos);
3559     
3560     if (error) {
3561         printf ("%*s^ - ", 3+strlen(last_cmd)+1+pos, " ");
3562         printf ("%s\n", ccl_err_msg (error));
3563     }
3564     else
3565     {
3566         if (rpn)
3567         {       
3568             ccl_pr_tree(rpn, stdout); 
3569         }
3570     }
3571     if (rpn)
3572         ccl_rpn_delete(rpn);
3573     
3574     printf ("\n");
3575     
3576     return 0;
3577 }
3578
3579
3580 int cmd_set_otherinfo(const char* args)
3581 {
3582     char oid[101], otherinfoString[101];
3583     int otherinfoNo;
3584     int sscan_res;
3585     int oidval;
3586     
3587     sscan_res = sscanf (args, "%d %100[^ ] %100s", &otherinfoNo, oid, otherinfoString);
3588     if(sscan_res==1) {
3589         /* reset this otherinfo */
3590         if(otherinfoNo>=maxOtherInfosSupported) {
3591             printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3592         }
3593         extraOtherInfos[otherinfoNo].oidval = -1;
3594         if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);                        
3595         return 0;
3596     }
3597     if (sscan_res<3) {
3598         printf("Error in set_otherinfo command \n");
3599         return 0;
3600     }
3601     
3602     if(otherinfoNo>=maxOtherInfosSupported) {
3603         printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3604     }
3605     
3606     oidval = oid_getvalbyname (oid);
3607     if(oidval == -1 ) {
3608         printf("Error in set_otherinfo command unknown oid %s \n",oid);
3609         return 0;
3610     }
3611     extraOtherInfos[otherinfoNo].oidval = oidval;
3612     if(extraOtherInfos[otherinfoNo].value) free(extraOtherInfos[otherinfoNo].value);
3613     extraOtherInfos[otherinfoNo].value = strdup(otherinfoString);
3614     
3615     return 0;
3616 }
3617
3618 int cmd_list_otherinfo(const char* args)
3619 {
3620     int i;         
3621     
3622     if(strlen(args)>0) {
3623         i = atoi(args);
3624         if( i >= maxOtherInfosSupported ) {
3625             printf("Error otherinfo index to large (%d>%d)\n",i,maxOtherInfosSupported);
3626             return 0;
3627         }
3628
3629         if(extraOtherInfos[i].oidval != -1) 
3630             printf("  otherinfo %d %s %s\n",
3631                    i,
3632                    yaz_z3950_oid_value_to_str(
3633                        (enum oid_value) extraOtherInfos[i].oidval,
3634                        CLASS_RECSYN),
3635                    extraOtherInfos[i].value);
3636         
3637     } else {            
3638         for(i=0; i<maxOtherInfosSupported; ++i) {
3639             if(extraOtherInfos[i].oidval != -1) 
3640                 printf("  otherinfo %d %s %s\n",
3641                        i,
3642                        yaz_z3950_oid_value_to_str(
3643                            (enum oid_value) extraOtherInfos[i].oidval,
3644                            CLASS_RECSYN),
3645                        extraOtherInfos[i].value);
3646         }
3647         
3648     }
3649     return 0;
3650 }
3651
3652
3653 int cmd_list_all(const char* args) {
3654     int i;
3655     
3656     /* connection options */
3657     if(conn) {
3658         printf("Connected to         : %s\n",last_open_command);
3659     } else {
3660         if(last_open_command) 
3661             printf("Not connected to     : %s\n",last_open_command);
3662         else 
3663             printf("Not connected        : \n");
3664         
3665     }
3666     if(yazProxy) printf("using proxy          : %s\n",yazProxy);                
3667     
3668     printf("auto_reconnect       : %s\n",auto_reconnect?"on":"off");
3669     
3670     if (!auth) {
3671         printf("Authentication       : none\n");
3672     } else {
3673         switch(auth->which) {
3674         case Z_IdAuthentication_idPass:
3675             printf("Authentication       : IdPass\n"); 
3676             printf("    Login User       : %s\n",auth->u.idPass->userId?auth->u.idPass->userId:"");
3677             printf("    Login Group      : %s\n",auth->u.idPass->groupId?auth->u.idPass->groupId:"");
3678             printf("    Password         : %s\n",auth->u.idPass->password?auth->u.idPass->password:"");
3679             break;
3680         case Z_IdAuthentication_open:
3681             printf("Authentication       : psOpen\n");                  
3682             printf("    Open string      : %s\n",auth->u.open); 
3683             break;
3684         default:
3685             printf("Authentication       : Unknown\n");
3686         }
3687     }
3688     if (negotiationCharset)
3689         printf("Neg. Character set   : `%s'\n", negotiationCharset);
3690     
3691     /* bases */
3692     printf("Bases                : ");
3693     for (i = 0; i<num_databaseNames; i++) printf("%s ",databaseNames[i]);
3694     printf("\n");
3695     
3696     /* Query options */
3697     printf("CCL file             : %s\n",ccl_fields);
3698     printf("CQL file             : %s\n",cql_fields);
3699     printf("Query type           : %s\n",query_type_as_string(queryType));
3700     
3701     printf("Named Result Sets    : %s\n",setnumber==-1?"off":"on");
3702     
3703     /* piggy back options */
3704     printf("ssub/lslb/mspn       : %d/%d/%d\n",smallSetUpperBound,largeSetLowerBound,mediumSetPresentNumber);
3705     
3706     /* print present related options */
3707     printf("Format               : %s\n",yaz_z3950_oid_value_to_str(recordsyntax,CLASS_RECSYN));
3708     printf("Schema               : %s\n",record_schema ? record_schema : "not set");
3709     printf("Elements             : %s\n",elementSetNames?elementSetNames->u.generic:"");
3710     
3711     /* loging options */
3712     printf("APDU log             : %s\n",apdu_file?"on":"off");
3713     printf("Record log           : %s\n",marc_file?"on":"off");
3714     
3715     /* other infos */
3716     printf("Other Info: \n");
3717     cmd_list_otherinfo("");
3718     
3719     return 0;
3720 }
3721
3722 int cmd_clear_otherinfo(const char* args) 
3723 {
3724     if(strlen(args)>0) {
3725         int otherinfoNo;
3726         otherinfoNo = atoi(args);
3727         if( otherinfoNo >= maxOtherInfosSupported ) {
3728             printf("Error otherinfo index to large (%d>%d)\n",otherinfoNo,maxOtherInfosSupported);
3729             return 0;
3730         }
3731         
3732         if(extraOtherInfos[otherinfoNo].oidval != -1) {                 
3733             /* only clear if set. */
3734             extraOtherInfos[otherinfoNo].oidval=-1;
3735             free(extraOtherInfos[otherinfoNo].value);
3736         }
3737     } else {
3738         int i;
3739         
3740         for(i=0; i<maxOtherInfosSupported; ++i) {
3741             if (extraOtherInfos[i].oidval!=-1 ) {                               
3742                 extraOtherInfos[i].oidval=-1;
3743                 free(extraOtherInfos[i].value);
3744             }
3745         }
3746     }
3747     return 0;
3748 }
3749
3750 static int cmd_help (const char *line);
3751
3752 typedef char *(*completerFunctionType)(const char *text, int state);
3753
3754 static struct {
3755     char *cmd;
3756     int (*fun)(const char *arg);
3757     char *ad;
3758         completerFunctionType rl_completerfunction;
3759     int complete_filenames;
3760     char **local_tabcompletes;
3761 } cmd_array[] = {
3762     {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0,NULL},
3763     {"quit", cmd_quit, "",NULL,0,NULL},
3764     {"find", cmd_find, "<query>",NULL,0,NULL},
3765     {"delete", cmd_delete, "<setname>",NULL,0,NULL},
3766     {"base", cmd_base, "<base-name>",NULL,0,NULL},
3767     {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0,NULL},
3768     {"scan", cmd_scan, "<term>",NULL,0,NULL},
3769     {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3770     {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0,NULL},
3771     {"authentication", cmd_authentication, "<acctstring>",NULL,0,NULL},
3772     {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0,NULL},
3773     {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0,NULL},
3774     {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0,NULL},
3775     {"status", cmd_status, "",NULL,0,NULL},
3776     {"setnames", cmd_setnames, "",NULL,0,NULL},
3777     {"cancel", cmd_cancel, "",NULL,0,NULL},
3778     {"format", cmd_format, "<recordsyntax>",complete_format,0,NULL},
3779     {"schema", cmd_schema, "<schema>",complete_schema,0,NULL},
3780     {"elements", cmd_elements, "<elementSetName>",NULL,0,NULL},
3781     {"close", cmd_close, "",NULL,0,NULL},
3782     {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0,NULL},
3783     {"querytype", cmd_querytype, "<type>",complete_querytype,0,NULL},
3784     {"refid", cmd_refid, "<id>",NULL,0,NULL},
3785     {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0,NULL},
3786     {"update", cmd_update, "<action> <recid> [<file>]",NULL,0,NULL},
3787     {"update0", cmd_update0, "<action> <recid> [<file>]",NULL,0,NULL},
3788     {"packagename", cmd_packagename, "<packagename>",NULL,0,NULL},
3789     {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0,NULL},
3790     {"charset", cmd_charset, "<nego_charset> <output_charset>",NULL,0,NULL},
3791     {"marccharset", cmd_marccharset, "<charset_name>",NULL,0,NULL},
3792     {"lang", cmd_lang, "<language_code>",NULL,0,NULL},
3793     {".", cmd_source, "<filename>",NULL,1,NULL},
3794     {"!", cmd_subshell, "Subshell command",NULL,1,NULL},
3795     {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,1,NULL},
3796     {"set_berfile", cmd_set_berfile, "<filename>",NULL,1,NULL},
3797     {"set_marcdump", cmd_set_marcdump," <filename>",NULL,1,NULL},
3798     {"set_cclfile", cmd_set_cclfile," <filename>",NULL,1,NULL},
3799     {"set_cqlfile", cmd_set_cqlfile," <filename>",NULL,1,NULL},
3800     {"set_auto_reconnect", cmd_set_auto_reconnect," on|off",complete_auto_reconnect,1,NULL},
3801         {"set_otherinfo", cmd_set_otherinfo,"<otherinfoinddex> <oid> <string>",NULL,0,NULL},
3802     {"register_oid", cmd_register_oid,"<name> <class> <oid>",NULL,0,NULL},
3803     {"push_command", cmd_push_command,"<command>",command_generator,0,NULL},
3804     {"register_tab", cmd_register_tab,"<commandname> <tab>",command_generator,0,NULL},
3805     {"cclparse", cmd_cclparse,"<ccl find command>",NULL,0,NULL},
3806     {"list_otherinfo",cmd_list_otherinfo,"[otherinfoinddex]",NULL,0,NULL},
3807     {"list_all",cmd_list_all,"",NULL,0,NULL},
3808     {"clear_otherinfo",cmd_clear_otherinfo,"",NULL,0,NULL},
3809     /* Server Admin Functions */
3810     {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0,NULL},
3811     {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0,NULL},
3812     {"adm-create", cmd_adm_create, "",NULL,0,NULL},
3813     {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0,NULL},
3814     {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0,NULL},
3815     {"adm-refresh", cmd_adm_refresh, "",NULL,0,NULL},
3816     {"adm-commit", cmd_adm_commit, "",NULL,0,NULL},
3817     {"adm-shutdown", cmd_adm_shutdown, "",NULL,0,NULL},
3818     {"adm-startup", cmd_adm_startup, "",NULL,0,NULL},
3819     {"explain", cmd_explain, "", NULL, 0, NULL},
3820     {"options", cmd_options, "", NULL, 0, NULL},
3821     {"zversion", cmd_zversion, "", NULL, 0, NULL},
3822     {"help", cmd_help, "", NULL,0,NULL},
3823     {"init", cmd_init, "", NULL,0,NULL},
3824     {0,0,0,0,0,0}
3825 };
3826
3827 static int cmd_help (const char *line)
3828 {
3829     int i;
3830     char topic[21];
3831     
3832     *topic = 0;
3833     sscanf (line, "%20s", topic);
3834
3835     if (*topic == 0)
3836         printf("Commands:\n");
3837     for (i = 0; cmd_array[i].cmd; i++)
3838         if (*topic == 0 || strcmp (topic, cmd_array[i].cmd) == 0)
3839             printf("   %s %s\n", cmd_array[i].cmd, cmd_array[i].ad);
3840     if (strcmp (topic, "find") == 0)
3841     {
3842         printf ("RPN:\n");
3843         printf (" \"term\"                        Simple Term\n");
3844         printf (" @attr [attset] type=value op  Attribute\n");
3845         printf (" @and opl opr                  And\n");
3846         printf (" @or opl opr                   Or\n");
3847         printf (" @not opl opr                  And-Not\n");
3848         printf (" @set set                      Result set\n");
3849         printf ("\n");
3850         printf ("Bib-1 attribute types\n");
3851         printf ("1=Use:         ");
3852         printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
3853         printf ("2=Relation:    ");
3854         printf ("1<   2<=  3=  4>=  5>  6!=  102=Relevance\n");
3855         printf ("3=Position:    ");
3856         printf ("1=First in Field  2=First in subfield  3=Any position\n");
3857         printf ("4=Structure:   ");
3858         printf ("1=Phrase  2=Word  3=Key  4=Year  5=Date  6=WordList\n");
3859         printf ("5=Truncation:  ");
3860         printf ("1=Right  2=Left  3=L&R  100=No  101=#  102=Re-1  103=Re-2\n");
3861         printf ("6=Completeness:");
3862         printf ("1=Incomplete subfield  2=Complete subfield  3=Complete field\n");
3863     }
3864     return 1;
3865 }
3866
3867 int cmd_register_tab(const char* arg) {
3868         
3869     char command[101], tabargument[101];
3870     int i;
3871     int num_of_tabs;
3872     char** tabslist;
3873     
3874     if (sscanf (arg, "%100s %100s", command, tabargument) < 1) {
3875         return 0;
3876     }
3877     
3878     /* locate the amdn in the list */
3879     for (i = 0; cmd_array[i].cmd; i++) {
3880         if (!strncmp(cmd_array[i].cmd, command, strlen(command))) {
3881             break;
3882         }
3883     }
3884     
3885     if(!cmd_array[i].cmd) { 
3886         fprintf(stderr,"Unknown command %s\n",command);
3887         return 1;
3888     }
3889     
3890         
3891     if(!cmd_array[i].local_tabcompletes)
3892         cmd_array[i].local_tabcompletes = (char **) calloc(1,sizeof(char**));
3893     
3894     num_of_tabs=0;              
3895     
3896     tabslist = cmd_array[i].local_tabcompletes;
3897     for(;tabslist && *tabslist;tabslist++) {
3898         num_of_tabs++;
3899     }
3900     
3901     cmd_array[i].local_tabcompletes =  (char **)
3902         realloc(cmd_array[i].local_tabcompletes,(num_of_tabs+2)*sizeof(char**));
3903     tabslist=cmd_array[i].local_tabcompletes;
3904     tabslist[num_of_tabs]=strdup(tabargument);
3905     tabslist[num_of_tabs+1]=NULL;
3906     return 1;
3907 }
3908
3909
3910 void process_cmd_line(char* line)
3911 {  
3912     int i,res;
3913     char word[32], arg[1024];
3914     
3915 #if HAVE_GETTIMEOFDAY
3916     gettimeofday (&tv_start, 0);
3917 #endif
3918     
3919     if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
3920     {
3921         strcpy(word, last_cmd);
3922         *arg = '\0';
3923     }
3924     else if (res == 1)
3925         *arg = 0;
3926     strcpy(last_cmd, word);
3927     
3928     /* removed tailing spaces from the arg command */
3929     { 
3930         char* p = arg;
3931         char* lastnonspace=NULL;
3932         
3933         for(;*p; ++p) {
3934             if(!isspace(*p)) {
3935                 lastnonspace = p;
3936             }
3937         }
3938         if(lastnonspace) 
3939             *(++lastnonspace) = 0;
3940     }
3941     
3942     for (i = 0; cmd_array[i].cmd; i++)
3943         if (!strncmp(cmd_array[i].cmd, word, strlen(word)))
3944         {
3945             res = (*cmd_array[i].fun)(arg);
3946             break;
3947         }
3948     
3949     if (!cmd_array[i].cmd) /* dump our help-screen */
3950     {
3951         printf("Unknown command: %s.\n", word);
3952         printf("use help for list of commands\n");
3953         /* cmd_help (""); */
3954         res = 1;
3955     }
3956     
3957     if(apdu_file) fflush(apdu_file);
3958     
3959     if (res >= 2)
3960         wait_and_handle_response();
3961     
3962     if(apdu_file)
3963         fflush(apdu_file);
3964     if(marc_file)
3965         fflush(marc_file);
3966 }
3967
3968
3969 char *command_generator(const char *text, int state) 
3970 {
3971     static int idx; 
3972     if (state==0) {
3973         idx = 0;
3974     }
3975     for( ; cmd_array[idx].cmd; ++idx) {
3976         if (!strncmp(cmd_array[idx].cmd,text,strlen(text))) {
3977             ++idx;  /* skip this entry on the next run */
3978             return strdup(cmd_array[idx-1].cmd);
3979         }
3980     }
3981     return NULL;
3982 }
3983
3984
3985 /* 
3986    This function only known how to complete on the first word
3987 */
3988 char ** readline_completer(char *text, int start, int end) {
3989 #if HAVE_READLINE_READLINE_H
3990
3991         completerFunctionType completerToUse;
3992         
3993     if(start == 0) {
3994 #if HAVE_READLINE_RL_COMPLETION_MATCHES
3995         char** res=rl_completion_matches(text,
3996                                       command_generator); 
3997 #else
3998         char** res=completion_matches(text,
3999                                       (CPFunction*)command_generator); 
4000 #endif
4001         rl_attempted_completion_over = 1;
4002         return res;
4003     } else {
4004         char arg[1024],word[32];
4005         int i=0 ,res;
4006         if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {     
4007             rl_attempted_completion_over = 1;
4008             return NULL;
4009         }
4010         
4011         for (i = 0; cmd_array[i].cmd; i++) {
4012             if (!strncmp(cmd_array[i].cmd, word, strlen(word))) {
4013                 break;
4014             }
4015         }
4016         
4017         if(!cmd_array[i].cmd) return NULL;
4018         
4019         curret_global_list = cmd_array[i].local_tabcompletes;
4020         
4021         completerToUse = cmd_array[i].rl_completerfunction;
4022         if(completerToUse==NULL)  /* if no pr. command completer is defined use the default completer */
4023             completerToUse = default_completer;
4024         
4025         if(completerToUse) {
4026 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
4027             char** res=
4028                 rl_completion_matches(text,
4029                                       completerToUse);
4030 #else
4031             char** res=
4032                 completion_matches(text,
4033                                    (CPFunction*)completerToUse);
4034 #endif
4035             if(!cmd_array[i].complete_filenames) 
4036                 rl_attempted_completion_over = 1;
4037             return res;
4038         } else {
4039             if(!cmd_array[i].complete_filenames) 
4040                 rl_attempted_completion_over = 1;
4041             return 0;
4042         }
4043     }
4044 #else 
4045     return 0;
4046 #endif 
4047 }
4048
4049
4050 static void client(void)
4051 {
4052     char line[1024];
4053
4054     line[1023] = '\0';
4055
4056 #if HAVE_GETTIMEOFDAY
4057     gettimeofday (&tv_start, 0);
4058 #endif
4059
4060     while (1)
4061     {
4062         char *line_in = NULL;
4063 #if HAVE_READLINE_READLINE_H
4064         if (isatty(0))
4065         {
4066             line_in=readline(C_PROMPT);
4067             if (!line_in)
4068                 break;
4069 #if HAVE_READLINE_HISTORY_H
4070             if (*line_in)
4071                 add_history(line_in);
4072 #endif
4073             strncpy(line, line_in, 1023);
4074             free (line_in);
4075         }
4076 #endif 
4077         if (!line_in)
4078         {
4079             char *end_p;
4080             printf (C_PROMPT);
4081             fflush(stdout);
4082             if (!fgets(line, 1023, stdin))
4083                 break;
4084             if ((end_p = strchr (line, '\n')))
4085                 *end_p = '\0';
4086         }
4087         process_cmd_line(line);
4088     }
4089 }
4090
4091 static void show_version(void)
4092 {
4093     char vstr[20];
4094
4095     yaz_version(vstr, 0);
4096     printf ("YAZ version: %s\n", YAZ_VERSION);
4097     if (strcmp(vstr, YAZ_VERSION))
4098         printf ("YAZ DLL/SO: %s\n", vstr);
4099     exit(0);
4100 }
4101
4102 int main(int argc, char **argv)
4103 {
4104     char *prog = *argv;
4105     char *open_command = 0;
4106     char *auth_command = 0;
4107     char *arg;
4108     int ret;
4109     
4110 #if HAVE_LOCALE_H
4111     if (!setlocale(LC_CTYPE, ""))
4112         fprintf (stderr, "setlocale failed\n");
4113 #endif
4114 #if HAVE_LANGINFO_H
4115 #ifdef CODESET
4116     codeset = nl_langinfo(CODESET);
4117 #endif
4118 #endif
4119     if (codeset)
4120         outputCharset = xstrdup(codeset);
4121     
4122     ODR_MASK_SET(&z3950_options, Z_Options_search);
4123     ODR_MASK_SET(&z3950_options, Z_Options_present);
4124     ODR_MASK_SET(&z3950_options, Z_Options_namedResultSets);
4125     ODR_MASK_SET(&z3950_options, Z_Options_triggerResourceCtrl);
4126     ODR_MASK_SET(&z3950_options, Z_Options_scan);
4127     ODR_MASK_SET(&z3950_options, Z_Options_sort);
4128     ODR_MASK_SET(&z3950_options, Z_Options_extendedServices);
4129     ODR_MASK_SET(&z3950_options, Z_Options_delSet);
4130
4131     while ((ret = options("k:c:q:a:b:m:v:p:u:t:Vxd:", argv, argc, &arg)) != -2)
4132     {
4133         switch (ret)
4134         {
4135         case 0:
4136             if (!open_command)
4137             {
4138                 open_command = (char *) xmalloc (strlen(arg)+6);
4139                 strcpy (open_command, "open ");
4140                 strcat (open_command, arg);
4141             }
4142             break;
4143         case 'd':
4144             dump_file_prefix = arg;
4145             break;
4146         case 'k':
4147             kilobytes = atoi(arg);
4148             break;
4149         case 'm':
4150             if (!(marc_file = fopen (arg, "a")))
4151             {
4152                 perror (arg);
4153                 exit (1);
4154             }
4155             break;
4156         case 't':
4157             outputCharset = xstrdup(arg);
4158             break;
4159         case 'c':
4160             strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
4161             ccl_fields[sizeof(ccl_fields)-1] = '\0';
4162             break;
4163         case 'q':
4164             strncpy (cql_fields, arg, sizeof(cql_fields)-1);
4165             cql_fields[sizeof(cql_fields)-1] = '\0';
4166             break;
4167         case 'b':
4168             if (!strcmp(arg, "-"))
4169                 ber_file=stderr;
4170             else
4171                 ber_file=fopen(arg, "a");
4172             break;
4173         case 'a':
4174             if (!strcmp(arg, "-"))
4175                 apdu_file=stderr;
4176             else
4177                 apdu_file=fopen(arg, "a");
4178             break;
4179         case 'x':
4180             hex_dump = 1;
4181             break;
4182         case 'p':
4183             yazProxy=strdup(arg);
4184             break;
4185         case 'u':
4186             if (!auth_command)
4187             {
4188                 auth_command = (char *) xmalloc (strlen(arg)+6);
4189                 strcpy (auth_command, "auth ");
4190                 strcat (auth_command, arg);
4191             }
4192             break;
4193         case 'v':
4194             yaz_log_init(yaz_log_mask_str(arg), "", 0);
4195             break;
4196         case 'V':
4197             show_version();
4198             break;
4199         default:
4200             fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
4201                      "[-b berdump] [-c cclfields] \n"
4202                      "[-q cqlfields] [-p <proxy-addr>] [-u <auth>] "
4203                      "[-k size] [-d dump] [-V] [<server-addr>]\n",
4204                      prog);
4205             exit (1);
4206         }      
4207     }
4208     initialize();
4209     if (auth_command)
4210     {
4211 #ifdef HAVE_GETTIMEOFDAY
4212         gettimeofday (&tv_start, 0);
4213 #endif
4214         process_cmd_line (auth_command);
4215 #if HAVE_READLINE_HISTORY_H
4216         add_history(auth_command);
4217 #endif
4218         xfree(auth_command);
4219     }
4220     if (open_command)
4221     {
4222 #ifdef HAVE_GETTIMEOFDAY
4223         gettimeofday (&tv_start, 0);
4224 #endif
4225         process_cmd_line (open_command);
4226 #if HAVE_READLINE_HISTORY_H
4227         add_history(open_command);
4228 #endif
4229         xfree(open_command);
4230     }
4231     client ();
4232     exit (0);
4233 }
4234
4235 /*
4236  * Local variables:
4237  * tab-width: 8
4238  * c-basic-offset: 4
4239  * End:
4240  * vim600: sw=4 ts=8 fdm=marker
4241  * vim<600: sw=4 ts=8
4242  */