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