CCL always enabled
[yaz-moved-to-github.git] / client / client.c
1 /*
2  * Copyright (c) 1995-2002, Index Data
3  * See the file LICENSE for details.
4  *
5  * $Id: client.c,v 1.158 2002-06-10 11:07:57 adam Exp $
6  */
7
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <time.h>
11
12 #include <yaz/yaz-util.h>
13
14 #include <yaz/tcpip.h>
15 #ifdef USE_XTIMOSI
16 #include <yaz/xmosi.h>
17 #endif
18
19 #include <yaz/proto.h>
20 #include <yaz/marcdisp.h>
21 #include <yaz/diagbib1.h>
22 #include <yaz/otherinfo.h>
23 #include <yaz/charneg.h>
24
25 #include <yaz/pquery.h>
26 #include <yaz/sortspec.h>
27
28 #include <yaz/ill.h>
29
30 #include <yaz/yaz-ccl.h>
31
32 #if HAVE_READLINE_READLINE_H
33 #include <readline/readline.h>
34 #endif
35 #if HAVE_READLINE_HISTORY_H
36 #include <readline/history.h>
37 #endif
38
39 #include <sys/stat.h>
40
41
42 #include "admin.h"
43 #include "tabcomplete.h"
44
45 #define C_PROMPT "Z> "
46
47 static ODR out, in, print;              /* encoding and decoding streams */
48 static FILE *apdu_file = 0;
49 static COMSTACK conn = 0;               /* our z-association */
50 static Z_IdAuthentication *auth = 0;    /* our current auth definition */
51 char *databaseNames[128];
52 int num_databaseNames = 0;
53 static Z_External *record_last = 0;
54 static int setnumber = -1;               /* current result set number */
55 static int smallSetUpperBound = 0;
56 static int largeSetLowerBound = 1;
57 static int mediumSetPresentNumber = 0;
58 static Z_ElementSetNames *elementSetNames = 0; 
59 static int setno = 1;                   /* current set offset */
60 static enum oid_proto protocol = PROTO_Z3950;      /* current app protocol */
61 static enum oid_value recordsyntax = VAL_USMARC;
62 static enum oid_value schema = VAL_NONE;
63 static int sent_close = 0;
64 static NMEM session_mem = NULL;      /* memory handle for init-response */
65 static Z_InitResponse *session = 0;     /* session parameters */
66 static char last_scan_line[512] = "0";
67 static char last_scan_query[512] = "0";
68 static char ccl_fields[512] = "default.bib";
69 static char* esPackageName = 0;
70 static char* yazProxy = 0;
71 static int kilobytes = 1024;
72 static char* yazCharset = 0;
73 static char* yazLang = 0;
74
75 static char last_cmd[32] = "?";
76 static FILE *marcdump = 0;
77 static char *refid = NULL;
78
79 typedef enum {
80     QueryType_Prefix,
81     QueryType_CCL,
82     QueryType_CCL2RPN
83 } QueryType;
84
85 static QueryType queryType = QueryType_Prefix;
86
87 static CCL_bibset bibset;               /* CCL bibset handle */
88
89 #if HAVE_READLINE_COMPLETION_OVER
90
91 #else
92 /* readline doesn't have this var. Define it ourselves. */
93 int rl_attempted_completion_over = 0;
94 #endif
95
96 /* set this one to 1, to avoid decode of unknown MARCs  */
97 #define AVOID_MARC_DECODE 1
98
99 /* nice helper macro as extensive tabbing gives spaces at the en of the args lines */
100 #define REMOVE_TAILING_BLANKS(a) {\
101   char* args_end=(a)+strlen(a)-1; \
102   while(isspace(*args_end)) {*args_end=0;--args_end;}; \
103   }
104
105
106 void process_cmd_line(char* line);
107 char ** readline_completer(char *text, int start, int end);
108 char *command_generator(const char *text, int state);
109
110
111 ODR getODROutputStream()
112 {
113     return out;
114 }
115
116 void send_apdu(Z_APDU *a)
117 {
118     char *buf;
119     int len;
120
121     if (apdu_file)
122     {
123         z_APDU(print, &a, 0, 0);
124         odr_reset(print);
125     }
126     if (!z_APDU(out, &a, 0, 0))
127     {
128         odr_perror(out, "Encoding APDU");
129         exit(1);
130     }
131     buf = odr_getbuf(out, &len, 0);
132     /* printf ("sending APDU of size %d\n", len); */
133     if (cs_put(conn, buf, len) < 0)
134     {
135         fprintf(stderr, "cs_put: %s", cs_errmsg(cs_errno(conn)));
136         exit(1);
137     }
138     odr_reset(out); /* release the APDU structure  */
139 }
140
141 static void print_stringn(const unsigned char *buf, size_t len)
142 {
143    size_t i;
144    for (i = 0; i<len; i++)
145        if ((buf[i] <= 126 && buf[i] >= 32) || strchr ("\n\r\t\f", buf[i]))
146            printf ("%c", buf[i]);
147        else
148            printf ("\\X%02X", buf[i]);
149 }
150
151 static void print_refid (Z_ReferenceId *id)
152 {
153     if (id)
154     {
155         printf ("Reference Id: ");
156         print_stringn (id->buf, id->len);
157         printf ("\n");
158     }
159 }
160
161 static Z_ReferenceId *set_refid (ODR out)
162 {
163     Z_ReferenceId *id;
164     if (!refid)
165         return 0;
166     id = (Z_ReferenceId *) odr_malloc (out, sizeof(*id));
167     id->size = id->len = strlen(refid);
168     id->buf = (unsigned char *) odr_malloc (out, id->len);
169     memcpy (id->buf, refid, id->len);
170     return id;
171 }   
172
173 /* INIT SERVICE ------------------------------- */
174
175 static void send_initRequest(const char* type_and_host)
176 {
177     Z_APDU *apdu = zget_APDU(out, Z_APDU_initRequest);
178     Z_InitRequest *req = apdu->u.initRequest;
179
180     ODR_MASK_SET(req->options, Z_Options_search);
181     ODR_MASK_SET(req->options, Z_Options_present);
182     ODR_MASK_SET(req->options, Z_Options_namedResultSets);
183     ODR_MASK_SET(req->options, Z_Options_triggerResourceCtrl);
184     ODR_MASK_SET(req->options, Z_Options_scan);
185     ODR_MASK_SET(req->options, Z_Options_sort);
186     ODR_MASK_SET(req->options, Z_Options_extendedServices);
187     ODR_MASK_SET(req->options, Z_Options_delSet);
188
189     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_1);
190     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_2);
191     ODR_MASK_SET(req->protocolVersion, Z_ProtocolVersion_3);
192
193     *req->maximumRecordSize = 1024*kilobytes;
194     *req->preferredMessageSize = 1024*kilobytes;
195
196     req->idAuthentication = auth;
197
198     req->referenceId = set_refid (out);
199
200     if (yazProxy) 
201         yaz_oi_set_string_oidval(&req->otherInfo, out, VAL_PROXY,
202         1, type_and_host);
203     
204     if (yazCharset || yazLang) {
205         Z_OtherInformation **p;
206         Z_OtherInformationUnit *p0;
207         
208         yaz_oi_APDU(apdu, &p);
209         
210         if (p0=yaz_oi_update(p, out, NULL, 0, 0)) {
211                 ODR_MASK_SET(req->options, Z_Options_negotiationModel);
212                 
213                 p0->which = Z_OtherInfo_externallyDefinedInfo;
214                 p0->information.externallyDefinedInfo =
215                         yaz_set_proposal_charneg(out,
216                                 (const char**)&yazCharset, (yazCharset)?1:0,
217                                 (const char**)&yazLang, (yazLang)?1:0, 1);
218         }
219     }
220     
221     send_apdu(apdu);
222     printf("Sent initrequest.\n");
223 }
224
225 static int process_initResponse(Z_InitResponse *res)
226 {
227     /* save session parameters for later use */
228     session_mem = odr_extract_mem(in);
229     session = res;
230
231     if (!*res->result)
232         printf("Connection rejected by target.\n");
233     else
234         printf("Connection accepted by target.\n");
235     if (res->implementationId)
236         printf("ID     : %s\n", res->implementationId);
237     if (res->implementationName)
238         printf("Name   : %s\n", res->implementationName);
239     if (res->implementationVersion)
240         printf("Version: %s\n", res->implementationVersion);
241     if (res->userInformationField)
242     {
243         printf("UserInformationfield:\n");
244         if (!z_External(print, (Z_External**)&res-> userInformationField,
245             0, 0))
246         {
247             odr_perror(print, "Printing userinfo\n");
248             odr_reset(print);
249         }
250         if (res->userInformationField->which == Z_External_octet)
251         {
252             printf("Guessing visiblestring:\n");
253             printf("'%s'\n", res->userInformationField->u. octet_aligned->buf);
254         }
255         odr_reset (print);
256     }
257     printf ("Options:");
258     if (ODR_MASK_GET(res->options, Z_Options_search))
259         printf (" search");
260     if (ODR_MASK_GET(res->options, Z_Options_present))
261         printf (" present");
262     if (ODR_MASK_GET(res->options, Z_Options_delSet))
263         printf (" delSet");
264     if (ODR_MASK_GET(res->options, Z_Options_resourceReport))
265         printf (" resourceReport");
266     if (ODR_MASK_GET(res->options, Z_Options_resourceCtrl))
267         printf (" resourceCtrl");
268     if (ODR_MASK_GET(res->options, Z_Options_accessCtrl))
269         printf (" accessCtrl");
270     if (ODR_MASK_GET(res->options, Z_Options_scan))
271         printf (" scan");
272     if (ODR_MASK_GET(res->options, Z_Options_sort))
273         printf (" sort");
274     if (ODR_MASK_GET(res->options, Z_Options_extendedServices))
275         printf (" extendedServices");
276     if (ODR_MASK_GET(res->options, Z_Options_level_1Segmentation))
277         printf (" level1Segmentation");
278     if (ODR_MASK_GET(res->options, Z_Options_level_2Segmentation))
279         printf (" level2Segmentation");
280     if (ODR_MASK_GET(res->options, Z_Options_concurrentOperations))
281         printf (" concurrentOperations");
282     if (ODR_MASK_GET(res->options, Z_Options_namedResultSets))
283     {
284         printf (" namedResultSets");
285         setnumber = 0;
286     }
287     if (ODR_MASK_GET(res->options, Z_Options_encapsulation))
288         printf (" encapsulation");
289     if (ODR_MASK_GET(res->options, Z_Options_resultCount))
290         printf (" resultCount");
291     if (ODR_MASK_GET(res->options, Z_Options_negotiationModel))
292         printf (" negotiationModel");
293     if (ODR_MASK_GET(res->options, Z_Options_duplicateDetection))
294         printf (" duplicateDetection");
295     if (ODR_MASK_GET(res->options, Z_Options_queryType104))
296         printf (" queryType104");
297     printf ("\n");
298     
299     if (ODR_MASK_GET(res->options, Z_Options_negotiationModel)) {
300     
301         Z_CharSetandLanguageNegotiation *p =
302                 yaz_get_charneg_record(res->otherInfo);
303         
304         if (p) {
305         
306                 char *charset=NULL, *lang=NULL;
307                 int selected;
308                 
309                 yaz_get_response_charneg(session_mem, p, &charset, &lang, &selected);
310                 
311                 printf("Accepted character set : `%s'\n", charset);
312                 printf("Accepted code language : `%s'\n", lang);
313                 printf("Accepted records in ...: %d\n", selected );
314         }
315     }
316     fflush (stdout);
317     return 0;
318 }
319
320 static int cmd_base(char *arg)
321 {
322     int i;
323     char *cp;
324
325     if (!*arg)
326     {
327         printf("Usage: base <database> <database> ...\n");
328         return 0;
329     }
330     for (i = 0; i<num_databaseNames; i++)
331         xfree (databaseNames[i]);
332     num_databaseNames = 0;
333     while (1)
334     {
335         if (!(cp = strchr(arg, ' ')))
336             cp = arg + strlen(arg);
337         if (cp - arg < 1)
338             break;
339         databaseNames[num_databaseNames] = (char *)xmalloc (1 + cp - arg);
340         memcpy (databaseNames[num_databaseNames], arg, cp - arg);
341         databaseNames[num_databaseNames++][cp - arg] = '\0';
342         if (!*cp)
343             break;
344         arg = cp+1;
345     }
346     return 1;
347 }
348
349 int cmd_open(char *arg)
350 {
351     void *add;
352     char type_and_host[101], base[101];
353     CS_TYPE t;
354     
355     if (conn)
356     {
357         printf("Already connected.\n");
358         
359         cs_close (conn);
360         conn = NULL;
361         if (session_mem)
362         {
363             nmem_destroy (session_mem);
364             session_mem = NULL;
365         }
366     }
367         if (strncmp (arg, "unix:", 5) == 0)
368         {
369         base[0] = '\0';
370         conn = cs_create_host(arg, 1, &add);
371         }
372         else
373         {
374                 t = tcpip_type;
375                 base[0] = '\0';
376                 if (sscanf (arg, "%100[^/]/%100s", type_and_host, base) < 1)
377                         return 0;
378                 
379                 if(yazProxy) 
380                         conn = cs_create_host(yazProxy, 1, &add);
381                 else 
382                         conn = cs_create_host(type_and_host, 1, &add);
383                 
384     }
385     if (!conn)
386     {
387         printf ("Couldn't create comstack\n");
388         return 0;
389     }
390     printf("Connecting...");
391     fflush(stdout);
392     if (cs_connect(conn, add) < 0)
393     {
394         printf ("error = %s\n", cs_strerror(conn));
395         if (conn->cerrno == CSYSERR)
396             perror("system");
397         cs_close(conn);
398         conn = 0;
399         return 0;
400     }
401     printf("Ok.\n");
402     
403     send_initRequest(type_and_host);
404     if (*base)
405         cmd_base (base);
406     return 2;
407 }
408
409 int cmd_authentication(char *arg)
410 {
411     static Z_IdAuthentication au;
412     static char user[40], group[40], pass[40];
413     static Z_IdPass idPass;
414     int r;
415
416     if (!*arg)
417     {
418         printf("Auth field set to null\n");
419         auth = 0;
420         return 1;
421     }
422     r = sscanf (arg, "%39s %39s %39s", user, group, pass);
423     if (r == 0)
424     {
425         printf("Auth field set to null\n");
426         auth = 0;
427     }
428     if (r == 1)
429     {
430         auth = &au;
431         au.which = Z_IdAuthentication_open;
432         au.u.open = user;
433     }
434     if (r == 3)
435     {
436         auth = &au;
437         au.which = Z_IdAuthentication_idPass;
438         au.u.idPass = &idPass;
439         idPass.groupId = group;
440         idPass.userId = user;
441         idPass.password = pass;
442     }
443     return 1;
444 }
445
446 /* SEARCH SERVICE ------------------------------ */
447 static void display_record(Z_External *r);
448
449 static void display_variant(Z_Variant *v, int level)
450 {
451     int i;
452
453     for (i = 0; i < v->num_triples; i++)
454     {
455         printf("%*sclass=%d,type=%d", level * 4, "", *v->triples[i]->zclass,
456             *v->triples[i]->type);
457         if (v->triples[i]->which == Z_Triple_internationalString)
458             printf(",value=%s\n", v->triples[i]->value.internationalString);
459         else
460             printf("\n");
461     }
462 }
463
464 static void display_grs1(Z_GenericRecord *r, int level)
465 {
466     int i;
467
468     if (!r)
469     {
470         return;
471     }
472     for (i = 0; i < r->num_elements; i++)
473     {
474         Z_TaggedElement *t;
475
476         printf("%*s", level * 4, "");
477         t = r->elements[i];
478         printf("(");
479         if (t->tagType)
480             printf("%d,", *t->tagType);
481         else
482             printf("?,");
483         if (t->tagValue->which == Z_StringOrNumeric_numeric)
484             printf("%d) ", *t->tagValue->u.numeric);
485         else
486             printf("%s) ", t->tagValue->u.string);
487         if (t->content->which == Z_ElementData_subtree)
488         {
489             if (!t->content->u.subtree)
490                 printf (" (no subtree)\n");
491             else
492             {
493                 printf("\n");
494                 display_grs1(t->content->u.subtree, level+1);
495             }
496         }
497         else if (t->content->which == Z_ElementData_string)
498             printf("%s\n", t->content->u.string);
499         else if (t->content->which == Z_ElementData_numeric)
500             printf("%d\n", *t->content->u.numeric);
501         else if (t->content->which == Z_ElementData_oid)
502         {
503             int *ip = t->content->u.oid;
504             oident *oent;
505             
506             if ((oent = oid_getentbyoid(t->content->u.oid)))
507                 printf("OID: %s\n", oent->desc);
508             else
509             {
510                 printf("{");
511                 while (ip && *ip >= 0)
512                     printf(" %d", *(ip++));
513                 printf(" }\n");
514             }
515         }
516         else if (t->content->which == Z_ElementData_noDataRequested)
517             printf("[No data requested]\n");
518         else if (t->content->which == Z_ElementData_elementEmpty)
519             printf("[Element empty]\n");
520         else if (t->content->which == Z_ElementData_elementNotThere)
521             printf("[Element not there]\n");
522         else if (t->content->which == Z_ElementData_date)
523             printf("Date: %s\n", t->content->u.date);
524         else if (t->content->which == Z_ElementData_ext)
525         {
526             printf ("External\n");
527             display_record (t->content->u.ext);
528         } 
529         else
530             printf("? type = %d\n",t->content->which);
531         if (t->appliedVariant)
532             display_variant(t->appliedVariant, level+1);
533         if (t->metaData && t->metaData->supportedVariants)
534         {
535             int c;
536
537             printf("%*s---- variant list\n", (level+1)*4, "");
538             for (c = 0; c < t->metaData->num_supportedVariants; c++)
539             {
540                 printf("%*svariant #%d\n", (level+1)*4, "", c);
541                 display_variant(t->metaData->supportedVariants[c], level + 2);
542             }
543         }
544     }
545 }
546
547
548 static void print_record(const unsigned char *buf, size_t len)
549 {
550     size_t i = len;
551     print_stringn (buf, len);
552     /* add newline if not already added ... */
553     if (i <= 0 || buf[i-1] != '\n')
554         printf ("\n");
555 }
556
557 static void display_record(Z_External *r)
558 {
559     oident *ent = oid_getentbyoid(r->direct_reference);
560
561     record_last = r;
562     /*
563      * Tell the user what we got.
564      */
565     if (r->direct_reference)
566     {
567         printf("Record type: ");
568         if (ent)
569             printf("%s\n", ent->desc);
570         else if (!odr_oid(print, &r->direct_reference, 0, 0))
571         {
572             odr_perror(print, "print oid");
573             odr_reset(print);
574         }
575     }
576     /* Check if this is a known, ASN.1 type tucked away in an octet string */
577     if (ent && r->which == Z_External_octet)
578     {
579         Z_ext_typeent *type = z_ext_getentbyref(ent->value);
580         void *rr;
581
582         if (type)
583         {
584             /*
585              * Call the given decoder to process the record.
586              */
587             odr_setbuf(in, (char*)r->u.octet_aligned->buf,
588                 r->u.octet_aligned->len, 0);
589             if (!(*type->fun)(in, (char **)&rr, 0, 0))
590             {
591                 odr_perror(in, "Decoding constructed record.");
592                 fprintf(stderr, "[Near %d]\n", odr_offset(in));
593                 fprintf(stderr, "Packet dump:\n---------\n");
594                 odr_dumpBER(stderr, (char*)r->u.octet_aligned->buf,
595                     r->u.octet_aligned->len);
596                 fprintf(stderr, "---------\n");
597                 exit(1);
598             }
599             /*
600              * Note: we throw away the original, BER-encoded record here.
601              * Do something else with it if you want to keep it.
602              */
603             r->u.sutrs = (Z_SUTRS *) rr; /* we don't actually check the type here. */
604             r->which = type->what;
605         }
606     }
607     if (ent && ent->oclass != CLASS_RECSYN)
608         return;
609     if (ent && ent->value == VAL_SOIF)
610         print_record((const unsigned char *) r->u.octet_aligned->buf,
611                      r->u.octet_aligned->len);
612     else if (r->which == Z_External_octet && r->u.octet_aligned->len)
613     {
614         const char *octet_buf = (char*)r->u.octet_aligned->buf;
615         if (ent->value == VAL_TEXT_XML || ent->value == VAL_APPLICATION_XML ||
616             ent->value == VAL_HTML)
617         {
618             print_record((const unsigned char *) octet_buf,
619                          r->u.octet_aligned->len);
620         }
621         else if (ent->value == VAL_POSTSCRIPT)
622         {
623             int size = r->u.octet_aligned->len;
624             if (size > 100)
625                 size = 100;
626             print_record((const unsigned char *) octet_buf, size);
627         }
628         else
629         {
630             if ( 
631 #if AVOID_MARC_DECODE
632                 /* primitive check for a marc OID 5.1-29 except 16 */
633                 ent->oidsuffix[0] == 5 && ent->oidsuffix[1] < 30 &&
634                 ent->oidsuffix[1] != 16
635 #else
636                 1
637 #endif
638                 )
639             {
640                 if (marc_display_exl (octet_buf, NULL, 0 /* debug */,
641                                       r->u.octet_aligned->len) <= 0)
642                 {
643                     printf ("bad MARC. Dumping as it is:\n");
644                     print_record((const unsigned char*) octet_buf,
645                                  r->u.octet_aligned->len);
646                 }
647             }
648             else
649             {
650                 print_record((const unsigned char*) octet_buf,
651                              r->u.octet_aligned->len);
652             }
653         }
654         if (marcdump)
655             fwrite (octet_buf, 1, r->u.octet_aligned->len, marcdump);
656     }
657     else if (ent && ent->value == VAL_SUTRS)
658     {
659         if (r->which != Z_External_sutrs)
660         {
661             printf("Expecting single SUTRS type for SUTRS.\n");
662             return;
663         }
664         print_record(r->u.sutrs->buf, r->u.sutrs->len);
665     }
666     else if (ent && ent->value == VAL_GRS1)
667     {
668         if (r->which != Z_External_grs1)
669         {
670             printf("Expecting single GRS type for GRS.\n");
671             return;
672         }
673         display_grs1(r->u.grs1, 0);
674     }
675     else 
676     {
677         printf("Unknown record representation.\n");
678         if (!z_External(print, &r, 0, 0))
679         {
680             odr_perror(print, "Printing external");
681             odr_reset(print);
682         }
683     }
684 }
685
686 static void display_diagrecs(Z_DiagRec **pp, int num)
687 {
688     int i;
689     oident *ent;
690     Z_DefaultDiagFormat *r;
691
692     printf("Diagnostic message(s) from database:\n");
693     for (i = 0; i<num; i++)
694     {
695         Z_DiagRec *p = pp[i];
696         if (p->which != Z_DiagRec_defaultFormat)
697         {
698             printf("Diagnostic record not in default format.\n");
699             return;
700         }
701         else
702             r = p->u.defaultFormat;
703         if (!(ent = oid_getentbyoid(r->diagnosticSetId)) ||
704             ent->oclass != CLASS_DIAGSET || ent->value != VAL_BIB1)
705             printf("Missing or unknown diagset\n");
706         printf("    [%d] %s", *r->condition, diagbib1_str(*r->condition));
707         switch (r->which)
708         {
709         case Z_DefaultDiagFormat_v2Addinfo:
710             printf (" -- v2 addinfo '%s'\n", r->u.v2Addinfo);
711             break;
712         case Z_DefaultDiagFormat_v3Addinfo:
713             printf (" -- v3 addinfo '%s'\n", r->u.v3Addinfo);
714             break;
715         }
716     }
717 }
718
719
720 static void display_nameplusrecord(Z_NamePlusRecord *p)
721 {
722     if (p->databaseName)
723         printf("[%s]", p->databaseName);
724     if (p->which == Z_NamePlusRecord_surrogateDiagnostic)
725         display_diagrecs(&p->u.surrogateDiagnostic, 1);
726     else if (p->which == Z_NamePlusRecord_databaseRecord)
727         display_record(p->u.databaseRecord);
728 }
729
730 static void display_records(Z_Records *p)
731 {
732     int i;
733
734     if (p->which == Z_Records_NSD)
735     {
736         Z_DiagRec dr, *dr_p = &dr;
737         dr.which = Z_DiagRec_defaultFormat;
738         dr.u.defaultFormat = p->u.nonSurrogateDiagnostic;
739         display_diagrecs (&dr_p, 1);
740     }
741     else if (p->which == Z_Records_multipleNSD)
742         display_diagrecs (p->u.multipleNonSurDiagnostics->diagRecs,
743                           p->u.multipleNonSurDiagnostics->num_diagRecs);
744     else 
745     {
746         printf("Records: %d\n", p->u.databaseOrSurDiagnostics->num_records);
747         for (i = 0; i < p->u.databaseOrSurDiagnostics->num_records; i++)
748             display_nameplusrecord(p->u.databaseOrSurDiagnostics->records[i]);
749     }
750 }
751
752 static int send_deleteResultSetRequest(char *arg)
753 {
754     char names[8][32];
755     int i;
756
757     Z_APDU *apdu = zget_APDU(out, Z_APDU_deleteResultSetRequest);
758     Z_DeleteResultSetRequest *req = apdu->u.deleteResultSetRequest;
759
760     req->referenceId = set_refid (out);
761
762     req->num_resultSetList =
763         sscanf (arg, "%30s %30s %30s %30s %30s %30s %30s %30s",
764                 names[0], names[1], names[2], names[3],
765                 names[4], names[5], names[6], names[7]);
766
767     req->deleteFunction = (int *)
768         odr_malloc (out, sizeof(*req->deleteFunction));
769     if (req->num_resultSetList > 0)
770     {
771         *req->deleteFunction = Z_DeleteRequest_list;
772         req->resultSetList = (char **)
773             odr_malloc (out, sizeof(*req->resultSetList)*
774                         req->num_resultSetList);
775         for (i = 0; i<req->num_resultSetList; i++)
776             req->resultSetList[i] = names[i];
777     }
778     else
779     {
780         *req->deleteFunction = Z_DeleteRequest_all;
781         req->resultSetList = 0;
782     }
783     
784     send_apdu(apdu);
785     printf("Sent deleteResultSetRequest.\n");
786     return 2;
787 }
788
789 static int send_searchRequest(char *arg)
790 {
791     Z_APDU *apdu = zget_APDU(out, Z_APDU_searchRequest);
792     Z_SearchRequest *req = apdu->u.searchRequest;
793     Z_Query query;
794     int oid[OID_SIZE];
795     struct ccl_rpn_node *rpn = NULL;
796     int error, pos;
797     char setstring[100];
798     Z_RPNQuery *RPNquery;
799     Odr_oct ccl_query;
800
801     if (queryType == QueryType_CCL2RPN)
802     {
803         rpn = ccl_find_str(bibset, arg, &error, &pos);
804         if (error)
805         {
806             printf("CCL ERROR: %s\n", ccl_err_msg(error));
807             return 0;
808         }
809     }
810     req->referenceId = set_refid (out);
811     if (!strcmp(arg, "@big")) /* strictly for troublemaking */
812     {
813         static unsigned char big[2100];
814         static Odr_oct bigo;
815
816         /* send a very big referenceid to test transport stack etc. */
817         memset(big, 'A', 2100);
818         bigo.len = bigo.size = 2100;
819         bigo.buf = big;
820         req->referenceId = &bigo;
821     }
822     
823     if (setnumber >= 0)
824     {
825         sprintf(setstring, "%d", ++setnumber);
826         req->resultSetName = setstring;
827     }
828     *req->smallSetUpperBound = smallSetUpperBound;
829     *req->largeSetLowerBound = largeSetLowerBound;
830     *req->mediumSetPresentNumber = mediumSetPresentNumber;
831     if (smallSetUpperBound > 0 || (largeSetLowerBound > 1 &&
832         mediumSetPresentNumber > 0))
833     {
834         oident prefsyn;
835
836         prefsyn.proto = protocol;
837         prefsyn.oclass = CLASS_RECSYN;
838         prefsyn.value = recordsyntax;
839         req->preferredRecordSyntax =
840             odr_oiddup(out, oid_ent_to_oid(&prefsyn, oid));
841         req->smallSetElementSetNames =
842             req->mediumSetElementSetNames = elementSetNames;
843     }
844     req->num_databaseNames = num_databaseNames;
845     req->databaseNames = databaseNames;
846
847     req->query = &query;
848
849     switch (queryType)
850     {
851     case QueryType_Prefix:
852         query.which = Z_Query_type_1;
853         RPNquery = p_query_rpn (out, protocol, arg);
854         if (!RPNquery)
855         {
856             printf("Prefix query error\n");
857             return 0;
858         }
859         query.u.type_1 = RPNquery;
860         break;
861     case QueryType_CCL:
862         query.which = Z_Query_type_2;
863         query.u.type_2 = &ccl_query;
864         ccl_query.buf = (unsigned char*) arg;
865         ccl_query.len = strlen(arg);
866         break;
867     case QueryType_CCL2RPN:
868         query.which = Z_Query_type_1;
869         RPNquery = ccl_rpn_query(out, rpn);
870         if (!RPNquery)
871         {
872             printf ("Couldn't convert from CCL to RPN\n");
873             return 0;
874         }
875         query.u.type_1 = RPNquery;
876         ccl_rpn_delete (rpn);
877         break;
878     default:
879         printf ("Unsupported query type\n");
880         return 0;
881     }
882     send_apdu(apdu);
883     setno = 1;
884     printf("Sent searchRequest.\n");
885     return 2;
886 }
887
888 /* display Query Expression as part of searchResult-1 */
889 static void display_queryExpression (Z_QueryExpression *qe)
890 {
891     if (!qe)
892         return;
893     if (qe->which == Z_QueryExpression_term)
894     {
895         if (qe->u.term->queryTerm)
896         {
897             Z_Term *term = qe->u.term->queryTerm;
898             if (term->which == Z_Term_general)
899                 printf (" %.*s", term->u.general->len, term->u.general->buf);
900         }
901     }
902
903 }
904
905 /* see if we can find USR:SearchResult-1 */
906 static void display_searchResult (Z_OtherInformation *o)
907 {
908     int i;
909     if (!o)
910         return ;
911     for (i = 0; i < o->num_elements; i++)
912     {
913         if (o->list[i]->which == Z_OtherInfo_externallyDefinedInfo)
914         {
915             Z_External *ext = o->list[i]->information.externallyDefinedInfo;
916             
917             if (ext->which == Z_External_searchResult1)
918             {
919                 int j;
920                 Z_SearchInfoReport *sr = ext->u.searchResult1;
921                 printf ("SearchResult-1:");
922                 for (j = 0; j < sr->num; j++)
923                 {
924                     if (!sr->elements[j]->subqueryExpression)
925                         printf (" %d", j);
926                     display_queryExpression (
927                         sr->elements[j]->subqueryExpression);
928                     display_queryExpression (
929                         sr->elements[j]->subqueryInterpretation);
930                     display_queryExpression (
931                         sr->elements[j]->subqueryRecommendation);
932                     if (sr->elements[j]->subqueryCount)
933                         printf ("(%d)", *sr->elements[j]->subqueryCount);
934                 }
935                 printf ("\n");
936             }
937         }
938     }
939 }
940
941 static int process_searchResponse(Z_SearchResponse *res)
942 {
943     printf ("Received SearchResponse.\n");
944     print_refid (res->referenceId);
945     if (*res->searchStatus)
946         printf("Search was a success.\n");
947     else
948         printf("Search was a bloomin' failure.\n");
949     printf("Number of hits: %d", *res->resultCount);
950     if (setnumber >= 0)
951         printf (", setno %d", setnumber);
952     printf ("\n");
953     display_searchResult (res->additionalSearchInfo);
954     printf("records returned: %d\n",
955            *res->numberOfRecordsReturned);
956     setno += *res->numberOfRecordsReturned;
957     if (res->records)
958         display_records(res->records);
959     return 0;
960 }
961
962 static void print_level(int iLevel)
963 {
964     int i;
965     for (i = 0; i < iLevel * 4; i++)
966         printf(" ");
967 }
968
969 static void print_int(int iLevel, const char *pTag, int *pInt)
970 {
971     if (pInt != NULL)
972     {
973         print_level(iLevel);
974         printf("%s: %d\n", pTag, *pInt);
975     }
976 }
977
978 static void print_string(int iLevel, const char *pTag, const char *pString)
979 {
980     if (pString != NULL)
981     {
982         print_level(iLevel);
983         printf("%s: %s\n", pTag, pString);
984     }
985 }
986
987 static void print_oid(int iLevel, const char *pTag, Odr_oid *pOid)
988 {
989     if (pOid != NULL)
990     {
991         int *pInt = pOid;
992
993         print_level(iLevel);
994         printf("%s:", pTag);
995         for (; *pInt != -1; pInt++)
996             printf(" %d", *pInt);
997         printf("\n");
998     }
999 }
1000
1001 static void print_referenceId(int iLevel, Z_ReferenceId *referenceId)
1002 {
1003     if (referenceId != NULL)
1004     {
1005         int i;
1006
1007         print_level(iLevel);
1008         printf("Ref Id (%d, %d): ", referenceId->len, referenceId->size);
1009         for (i = 0; i < referenceId->len; i++)
1010             printf("%c", referenceId->buf[i]);
1011         printf("\n");
1012     }
1013 }
1014
1015 static void print_string_or_numeric(int iLevel, const char *pTag, Z_StringOrNumeric *pStringNumeric)
1016 {
1017     if (pStringNumeric != NULL)
1018     {
1019         switch (pStringNumeric->which)
1020         {
1021         case Z_StringOrNumeric_string:
1022             print_string(iLevel, pTag, pStringNumeric->u.string);
1023             break;
1024             
1025         case Z_StringOrNumeric_numeric:
1026             print_int(iLevel, pTag, pStringNumeric->u.numeric);
1027             break;
1028             
1029         default:
1030             print_level(iLevel);
1031             printf("%s: valid type for Z_StringOrNumeric\n", pTag);
1032             break;
1033         }
1034     }
1035 }
1036
1037 static void print_universe_report_duplicate(int iLevel, Z_UniverseReportDuplicate *pUniverseReportDuplicate)
1038 {
1039     if (pUniverseReportDuplicate != NULL)
1040     {
1041         print_level(iLevel);
1042         printf("Universe Report Duplicate: \n");
1043         iLevel++;
1044         print_string_or_numeric(iLevel, "Hit No",
1045                                 pUniverseReportDuplicate->hitno);
1046     }
1047 }
1048
1049 static void
1050 print_universe_report_hits(int iLevel,
1051                            Z_UniverseReportHits *pUniverseReportHits)
1052 {
1053     if (pUniverseReportHits != NULL)
1054     {
1055         print_level(iLevel);
1056         printf("Universe Report Hits: \n");
1057         iLevel++;
1058         print_string_or_numeric(iLevel, "Database",
1059                                 pUniverseReportHits->database);
1060         print_string_or_numeric(iLevel, "Hits", pUniverseReportHits->hits);
1061     }
1062 }
1063
1064 static void print_universe_report(int iLevel, Z_UniverseReport *pUniverseReport)
1065 {
1066     if (pUniverseReport != NULL)
1067     {
1068         print_level(iLevel);
1069         printf("Universe Report: \n");
1070         iLevel++;
1071         print_int(iLevel, "Total Hits", pUniverseReport->totalHits);
1072         switch (pUniverseReport->which)
1073         {
1074         case Z_UniverseReport_databaseHits:
1075             print_universe_report_hits(iLevel, pUniverseReport->u.databaseHits);
1076             break;
1077             
1078         case Z_UniverseReport_duplicate:
1079             print_universe_report_duplicate(iLevel, pUniverseReport->u.duplicate);
1080             break;
1081             
1082         default:
1083             print_level(iLevel);
1084             printf("Type: %d\n", pUniverseReport->which);
1085             break;
1086         }
1087     }
1088 }
1089
1090 static void print_external(int iLevel, Z_External *pExternal)
1091 {
1092     if (pExternal != NULL)
1093     {
1094         print_level(iLevel);
1095         printf("External: \n");
1096         iLevel++;
1097         print_oid(iLevel, "Direct Reference", pExternal->direct_reference);
1098         print_int(iLevel, "InDirect Reference", pExternal->indirect_reference);
1099         print_string(iLevel, "Descriptor", pExternal->descriptor);
1100         switch (pExternal->which)
1101         {
1102         case Z_External_universeReport:
1103             print_universe_report(iLevel, pExternal->u.universeReport);
1104             break;
1105             
1106         default:
1107             print_level(iLevel);
1108             printf("Type: %d\n", pExternal->which);
1109             break;
1110         }
1111     }
1112 }
1113
1114 static int process_resourceControlRequest (Z_ResourceControlRequest *req)
1115 {
1116     printf ("Received ResourceControlRequest.\n");
1117     print_referenceId(1, req->referenceId);
1118     print_int(1, "Suspended Flag", req->suspendedFlag);
1119     print_int(1, "Partial Results Available", req->partialResultsAvailable);
1120     print_int(1, "Response Required", req->responseRequired);
1121     print_int(1, "Triggered Request Flag", req->triggeredRequestFlag);
1122     print_external(1, req->resourceReport);
1123     return 0;
1124 }
1125
1126 void process_ESResponse(Z_ExtendedServicesResponse *res)
1127 {
1128     printf("Status: ");
1129     switch (*res->operationStatus)
1130     {
1131     case Z_ExtendedServicesResponse_done:
1132         printf ("done\n");
1133         break;
1134     case Z_ExtendedServicesResponse_accepted:
1135         printf ("accepted\n");
1136         break;
1137     case Z_ExtendedServicesResponse_failure:
1138         printf ("failure\n");
1139         display_diagrecs(res->diagnostics, res->num_diagnostics);
1140         break;
1141     default:
1142         printf ("unknown\n");
1143     }
1144     if ( (*res->operationStatus != Z_ExtendedServicesResponse_failure) &&
1145         (res->num_diagnostics != 0) ) {
1146         display_diagrecs(res->diagnostics, res->num_diagnostics);
1147     }
1148     print_refid (res->referenceId);
1149     if (res->taskPackage && 
1150         res->taskPackage->which == Z_External_extendedService)
1151     {
1152         Z_TaskPackage *taskPackage = res->taskPackage->u.extendedService;
1153         Odr_oct *id = taskPackage->targetReference;
1154         Z_External *ext = taskPackage->taskSpecificParameters;
1155         
1156         if (id)
1157         {
1158             printf ("Target Reference: ");
1159             print_stringn (id->buf, id->len);
1160             printf ("\n");
1161         }
1162         if (ext->which == Z_External_update)
1163         {
1164             Z_IUUpdateTaskPackage *utp = ext->u.update->u.taskPackage;
1165             if (utp && utp->targetPart)
1166             {
1167                 Z_IUTargetPart *targetPart = utp->targetPart;
1168                 int i;
1169
1170                 for (i = 0; i<targetPart->num_taskPackageRecords;  i++)
1171                 {
1172
1173                     Z_IUTaskPackageRecordStructure *tpr =
1174                         targetPart->taskPackageRecords[i];
1175                     printf ("task package record %d\n", i+1);
1176                     if (tpr->which == Z_IUTaskPackageRecordStructure_record)
1177                     {
1178                         display_record (tpr->u.record);
1179                     }
1180                     else
1181                     {
1182                         printf ("other type\n");
1183                     }
1184                 }
1185             }
1186         }
1187     }
1188 }
1189
1190 const char *get_ill_element (void *clientData, const char *element)
1191 {
1192     return 0;
1193 }
1194
1195 static Z_External *create_external_itemRequest()
1196 {
1197     struct ill_get_ctl ctl;
1198     ILL_ItemRequest *req;
1199     Z_External *r = 0;
1200     int item_request_size = 0;
1201     char *item_request_buf = 0;
1202
1203     ctl.odr = out;
1204     ctl.clientData = 0;
1205     ctl.f = get_ill_element;
1206     
1207     req = ill_get_ItemRequest(&ctl, "ill", 0);
1208     if (!req)
1209         printf ("ill_get_ItemRequest failed\n");
1210         
1211     if (!ill_ItemRequest (out, &req, 0, 0))
1212     {
1213         if (apdu_file)
1214         {
1215             ill_ItemRequest(print, &req, 0, 0);
1216             odr_reset(print);
1217         }
1218         item_request_buf = odr_getbuf (out, &item_request_size, 0);
1219         if (item_request_buf)
1220             odr_setbuf (out, item_request_buf, item_request_size, 1);
1221         printf ("Couldn't encode ItemRequest, size %d\n", item_request_size);
1222         return 0;
1223     }
1224     else
1225     {
1226         oident oid;
1227         
1228         item_request_buf = odr_getbuf (out, &item_request_size, 0);
1229         oid.proto = PROTO_GENERAL;
1230         oid.oclass = CLASS_GENERAL;
1231         oid.value = VAL_ISO_ILL_1;
1232         
1233         r = (Z_External *) odr_malloc (out, sizeof(*r));
1234         r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid)); 
1235         r->indirect_reference = 0;
1236         r->descriptor = 0;
1237         r->which = Z_External_single;
1238         
1239         r->u.single_ASN1_type = (Odr_oct *)
1240             odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1241         r->u.single_ASN1_type->buf = (unsigned char *)
1242         odr_malloc (out, item_request_size);
1243         r->u.single_ASN1_type->len = item_request_size;
1244         r->u.single_ASN1_type->size = item_request_size;
1245         memcpy (r->u.single_ASN1_type->buf, item_request_buf,
1246                 item_request_size);
1247         printf ("len = %d\n", item_request_size);
1248     }
1249     return r;
1250 }
1251
1252 static Z_External *create_external_ILL_APDU(int which)
1253 {
1254     struct ill_get_ctl ctl;
1255     ILL_APDU *ill_apdu;
1256     Z_External *r = 0;
1257     int ill_request_size = 0;
1258     char *ill_request_buf = 0;
1259         
1260     ctl.odr = out;
1261     ctl.clientData = 0;
1262     ctl.f = get_ill_element;
1263
1264     ill_apdu = ill_get_APDU(&ctl, "ill", 0);
1265
1266     if (!ill_APDU (out, &ill_apdu, 0, 0))
1267     {
1268         if (apdu_file)
1269         {
1270             printf ("-------------------\n");
1271             ill_APDU(print, &ill_apdu, 0, 0);
1272             odr_reset(print);
1273             printf ("-------------------\n");
1274         }
1275         ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1276         if (ill_request_buf)
1277             odr_setbuf (out, ill_request_buf, ill_request_size, 1);
1278         printf ("Couldn't encode ILL-Request, size %d\n", ill_request_size);
1279         return 0;
1280     }
1281     else
1282     {
1283         oident oid;
1284         ill_request_buf = odr_getbuf (out, &ill_request_size, 0);
1285         
1286         oid.proto = PROTO_GENERAL;
1287         oid.oclass = CLASS_GENERAL;
1288         oid.value = VAL_ISO_ILL_1;
1289         
1290         r = (Z_External *) odr_malloc (out, sizeof(*r));
1291         r->direct_reference = odr_oiddup(out,oid_getoidbyent(&oid)); 
1292         r->indirect_reference = 0;
1293         r->descriptor = 0;
1294         r->which = Z_External_single;
1295         
1296         r->u.single_ASN1_type = (Odr_oct *)
1297             odr_malloc (out, sizeof(*r->u.single_ASN1_type));
1298         r->u.single_ASN1_type->buf = (unsigned char *)
1299         odr_malloc (out, ill_request_size);
1300         r->u.single_ASN1_type->len = ill_request_size;
1301         r->u.single_ASN1_type->size = ill_request_size;
1302         memcpy (r->u.single_ASN1_type->buf, ill_request_buf, ill_request_size);
1303         printf ("len = %d\n", ill_request_size);
1304     }
1305     return r;
1306 }
1307
1308
1309 static Z_External *create_ItemOrderExternal(const char *type, int itemno)
1310 {
1311     Z_External *r = (Z_External *) odr_malloc(out, sizeof(Z_External));
1312     oident ItemOrderRequest;
1313   
1314     ItemOrderRequest.proto = PROTO_Z3950;
1315     ItemOrderRequest.oclass = CLASS_EXTSERV;
1316     ItemOrderRequest.value = VAL_ITEMORDER;
1317  
1318     r->direct_reference = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest)); 
1319     r->indirect_reference = 0;
1320     r->descriptor = 0;
1321
1322     r->which = Z_External_itemOrder;
1323
1324     r->u.itemOrder = (Z_ItemOrder *) odr_malloc(out,sizeof(Z_ItemOrder));
1325     memset(r->u.itemOrder, 0, sizeof(Z_ItemOrder));
1326     r->u.itemOrder->which=Z_IOItemOrder_esRequest;
1327
1328     r->u.itemOrder->u.esRequest = (Z_IORequest *) 
1329         odr_malloc(out,sizeof(Z_IORequest));
1330     memset(r->u.itemOrder->u.esRequest, 0, sizeof(Z_IORequest));
1331
1332     r->u.itemOrder->u.esRequest->toKeep = (Z_IOOriginPartToKeep *)
1333         odr_malloc(out,sizeof(Z_IOOriginPartToKeep));
1334     memset(r->u.itemOrder->u.esRequest->toKeep, 0, sizeof(Z_IOOriginPartToKeep));
1335     r->u.itemOrder->u.esRequest->notToKeep = (Z_IOOriginPartNotToKeep *)
1336         odr_malloc(out,sizeof(Z_IOOriginPartNotToKeep));
1337     memset(r->u.itemOrder->u.esRequest->notToKeep, 0, sizeof(Z_IOOriginPartNotToKeep));
1338
1339     r->u.itemOrder->u.esRequest->toKeep->supplDescription = NULL;
1340     r->u.itemOrder->u.esRequest->toKeep->contact = NULL;
1341     r->u.itemOrder->u.esRequest->toKeep->addlBilling = NULL;
1342
1343     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem =
1344         (Z_IOResultSetItem *) odr_malloc(out, sizeof(Z_IOResultSetItem));
1345     memset(r->u.itemOrder->u.esRequest->notToKeep->resultSetItem, 0, sizeof(Z_IOResultSetItem));
1346     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->resultSetId = "1";
1347
1348     r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item =
1349         (int *) odr_malloc(out, sizeof(int));
1350     *r->u.itemOrder->u.esRequest->notToKeep->resultSetItem->item = itemno;
1351
1352 #if YAZ_MODULE_ill
1353     if (!strcmp (type, "item") || !strcmp(type, "2"))
1354     {
1355         printf ("using item-request\n");
1356         r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 
1357             create_external_itemRequest();
1358     }
1359     else if (!strcmp(type, "ill") || !strcmp(type, "1"))
1360     {
1361         printf ("using ILL-request\n");
1362         r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 
1363             create_external_ILL_APDU(ILL_APDU_ILL_Request);
1364     }
1365     else if (!strcmp(type, "xml") || !strcmp(type, "3"))
1366     {
1367     const char *xml_buf =
1368         "<itemorder>\n"
1369         "  <type>request</type>\n"
1370         "  <libraryNo>000200</libraryNo>\n"
1371         "  <borrowerTicketNo> 1212 </borrowerTicketNo>\n"
1372         "</itemorder>";
1373         r->u.itemOrder->u.esRequest->notToKeep->itemRequest =
1374             z_ext_record (out, VAL_TEXT_XML, xml_buf, strlen(xml_buf));
1375     }
1376     else
1377         r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1378
1379 #else
1380     r->u.itemOrder->u.esRequest->notToKeep->itemRequest = 0;
1381 #endif
1382     return r;
1383 }
1384
1385 static int send_itemorder(const char *type, int itemno)
1386 {
1387     Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest);
1388     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1389     oident ItemOrderRequest;
1390
1391     ItemOrderRequest.proto = PROTO_Z3950;
1392     ItemOrderRequest.oclass = CLASS_EXTSERV;
1393     ItemOrderRequest.value = VAL_ITEMORDER;
1394     req->packageType = odr_oiddup(out,oid_getoidbyent(&ItemOrderRequest));
1395     req->packageName = esPackageName;
1396
1397     req->taskSpecificParameters = create_ItemOrderExternal(type, itemno);
1398
1399     send_apdu(apdu);
1400     return 0;
1401 }
1402
1403 static int cmd_update(char *arg)
1404 {
1405     Z_APDU *apdu = zget_APDU(out, Z_APDU_extendedServicesRequest );
1406     Z_ExtendedServicesRequest *req = apdu->u.extendedServicesRequest;
1407     Z_External *r;
1408     int oid[OID_SIZE];
1409     Z_IUOriginPartToKeep *toKeep;
1410     Z_IUSuppliedRecords *notToKeep;
1411     oident update_oid;
1412     printf ("Update request\n");
1413     fflush(stdout);
1414     
1415     if (!record_last)
1416         return 0;
1417     update_oid.proto = PROTO_Z3950;
1418     update_oid.oclass = CLASS_EXTSERV;
1419     update_oid.value = VAL_DBUPDATE;
1420     oid_ent_to_oid (&update_oid, oid);
1421     req->packageType = odr_oiddup(out,oid);
1422     req->packageName = esPackageName;
1423     
1424     req->referenceId = set_refid (out);
1425
1426     r = req->taskSpecificParameters = (Z_External *)
1427         odr_malloc (out, sizeof(*r));
1428     r->direct_reference = odr_oiddup(out,oid);
1429     r->indirect_reference = 0;
1430     r->descriptor = 0;
1431     r->which = Z_External_update;
1432     r->u.update = (Z_IUUpdate *) odr_malloc(out, sizeof(*r->u.update));
1433     r->u.update->which = Z_IUUpdate_esRequest;
1434     r->u.update->u.esRequest = (Z_IUUpdateEsRequest *)
1435         odr_malloc(out, sizeof(*r->u.update->u.esRequest));
1436     toKeep = r->u.update->u.esRequest->toKeep = (Z_IUOriginPartToKeep *)
1437         odr_malloc(out, sizeof(*r->u.update->u.esRequest->toKeep));
1438     toKeep->databaseName = databaseNames[0];
1439     toKeep->schema = 0;
1440     toKeep->elementSetName = 0;
1441     toKeep->actionQualifier = 0;
1442     toKeep->action = (int *) odr_malloc(out, sizeof(*toKeep->action));
1443     *toKeep->action = Z_IUOriginPartToKeep_recordInsert;
1444
1445     notToKeep = r->u.update->u.esRequest->notToKeep = (Z_IUSuppliedRecords *)
1446         odr_malloc(out, sizeof(*r->u.update->u.esRequest->notToKeep));
1447     notToKeep->num = 1;
1448     notToKeep->elements = (Z_IUSuppliedRecords_elem **)
1449         odr_malloc(out, sizeof(*notToKeep->elements));
1450     notToKeep->elements[0] = (Z_IUSuppliedRecords_elem *)
1451         odr_malloc(out, sizeof(**notToKeep->elements));
1452     notToKeep->elements[0]->u.number = 0;
1453     notToKeep->elements[0]->supplementalId = 0;
1454     notToKeep->elements[0]->correlationInfo = 0;
1455     notToKeep->elements[0]->record = record_last;
1456     
1457     send_apdu(apdu);
1458
1459     return 2;
1460 }
1461
1462 static int cmd_itemorder(char *arg)
1463 {
1464     char type[12];
1465     int itemno;
1466     
1467     if (sscanf (arg, "%10s %d", type, &itemno) != 2)
1468         return 0;
1469
1470     printf("Item order request\n");
1471     fflush(stdout);
1472     send_itemorder(type, itemno);
1473     return 2;
1474 }
1475
1476 static int cmd_find(char *arg)
1477 {
1478     if (!*arg)
1479     {
1480         printf("Find what?\n");
1481         return 0;
1482     }
1483     if (!conn)
1484     {
1485         printf("Not connected yet\n");
1486         return 0;
1487     }
1488     if (!send_searchRequest(arg))
1489         return 0;
1490     return 2;
1491 }
1492
1493 static int cmd_delete(char *arg)
1494 {
1495     if (!conn)
1496     {
1497         printf("Not connected yet\n");
1498         return 0;
1499     }
1500     if (!send_deleteResultSetRequest(arg))
1501         return 0;
1502     return 2;
1503 }
1504
1505 static int cmd_ssub(char *arg)
1506 {
1507     if (!(smallSetUpperBound = atoi(arg)))
1508         return 0;
1509     return 1;
1510 }
1511
1512 static int cmd_lslb(char *arg)
1513 {
1514     if (!(largeSetLowerBound = atoi(arg)))
1515         return 0;
1516     return 1;
1517 }
1518
1519 static int cmd_mspn(char *arg)
1520 {
1521     if (!(mediumSetPresentNumber = atoi(arg)))
1522         return 0;
1523     return 1;
1524 }
1525
1526 static int cmd_status(char *arg)
1527 {
1528     printf("smallSetUpperBound: %d\n", smallSetUpperBound);
1529     printf("largeSetLowerBound: %d\n", largeSetLowerBound);
1530     printf("mediumSetPresentNumber: %d\n", mediumSetPresentNumber);
1531     return 1;
1532 }
1533
1534 static int cmd_setnames(char *arg)
1535 {
1536     if (*arg == '1')         /* enable ? */
1537         setnumber = 0;
1538     else if (*arg == '0')    /* disable ? */
1539         setnumber = -1;
1540     else if (setnumber < 0)  /* no args, toggle .. */
1541         setnumber = 0;
1542     else
1543         setnumber = -1;
1544    
1545     if (setnumber >= 0)
1546         printf("Set numbering enabled.\n");
1547     else
1548         printf("Set numbering disabled.\n");
1549     return 1;
1550 }
1551
1552 /* PRESENT SERVICE ----------------------------- */
1553
1554 static int send_presentRequest(char *arg)
1555 {
1556     Z_APDU *apdu = zget_APDU(out, Z_APDU_presentRequest);
1557     Z_PresentRequest *req = apdu->u.presentRequest;
1558     Z_RecordComposition compo;
1559     oident prefsyn;
1560     int nos = 1;
1561     int oid[OID_SIZE];
1562     char *p;
1563     char setstring[100];
1564
1565     req->referenceId = set_refid (out);
1566     if ((p = strchr(arg, '+')))
1567     {
1568         nos = atoi(p + 1);
1569         *p = 0;
1570     }
1571     if (*arg)
1572         setno = atoi(arg);
1573     if (p && (p=strchr(p+1, '+')))
1574     {
1575         strcpy (setstring, p+1);
1576         req->resultSetId = setstring;
1577     }
1578     else if (setnumber >= 0)
1579     {
1580         sprintf(setstring, "%d", setnumber);
1581         req->resultSetId = setstring;
1582     }
1583     req->resultSetStartPoint = &setno;
1584     req->numberOfRecordsRequested = &nos;
1585     prefsyn.proto = protocol;
1586     prefsyn.oclass = CLASS_RECSYN;
1587     prefsyn.value = recordsyntax;
1588     req->preferredRecordSyntax =
1589         odr_oiddup (out, oid_ent_to_oid(&prefsyn, oid));
1590
1591     if (schema != VAL_NONE)
1592     {
1593         oident prefschema;
1594
1595         prefschema.proto = protocol;
1596         prefschema.oclass = CLASS_SCHEMA;
1597         prefschema.value = schema;
1598
1599         req->recordComposition = &compo;
1600         compo.which = Z_RecordComp_complex;
1601         compo.u.complex = (Z_CompSpec *)
1602             odr_malloc(out, sizeof(*compo.u.complex));
1603         compo.u.complex->selectAlternativeSyntax = (bool_t *) 
1604             odr_malloc(out, sizeof(bool_t));
1605         *compo.u.complex->selectAlternativeSyntax = 0;
1606
1607         compo.u.complex->generic = (Z_Specification *)
1608             odr_malloc(out, sizeof(*compo.u.complex->generic));
1609         compo.u.complex->generic->schema = (Odr_oid *)
1610             odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1611         if (!compo.u.complex->generic->schema)
1612         {
1613             /* OID wasn't a schema! Try record syntax instead. */
1614             prefschema.oclass = CLASS_RECSYN;
1615             compo.u.complex->generic->schema = (Odr_oid *)
1616                 odr_oiddup(out, oid_ent_to_oid(&prefschema, oid));
1617         }
1618         if (!elementSetNames)
1619             compo.u.complex->generic->elementSpec = 0;
1620         else
1621         {
1622             compo.u.complex->generic->elementSpec = (Z_ElementSpec *)
1623                 odr_malloc(out, sizeof(Z_ElementSpec));
1624             compo.u.complex->generic->elementSpec->which =
1625                 Z_ElementSpec_elementSetName;
1626             compo.u.complex->generic->elementSpec->u.elementSetName =
1627                 elementSetNames->u.generic;
1628         }
1629         compo.u.complex->num_dbSpecific = 0;
1630         compo.u.complex->dbSpecific = 0;
1631         compo.u.complex->num_recordSyntax = 0;
1632         compo.u.complex->recordSyntax = 0;
1633     }
1634     else if (elementSetNames)
1635     {
1636         req->recordComposition = &compo;
1637         compo.which = Z_RecordComp_simple;
1638         compo.u.simple = elementSetNames;
1639     }
1640     send_apdu(apdu);
1641     printf("Sent presentRequest (%d+%d).\n", setno, nos);
1642     return 2;
1643 }
1644     
1645 static void close_session (void)
1646 {
1647     cs_close (conn);
1648     conn = 0;
1649     if (session_mem)
1650     {
1651         nmem_destroy (session_mem);
1652         session_mem = NULL;
1653     }
1654     sent_close = 0;
1655 }
1656
1657 void process_close(Z_Close *req)
1658 {
1659     Z_APDU *apdu = zget_APDU(out, Z_APDU_close);
1660     Z_Close *res = apdu->u.close;
1661
1662     static char *reasons[] =
1663     {
1664         "finished",
1665         "shutdown",
1666         "system problem",
1667         "cost limit reached",
1668         "resources",
1669         "security violation",
1670         "protocolError",
1671         "lack of activity",
1672         "peer abort",
1673         "unspecified"
1674     };
1675
1676     printf("Reason: %s, message: %s\n", reasons[*req->closeReason],
1677         req->diagnosticInformation ? req->diagnosticInformation : "NULL");
1678     if (sent_close)
1679         close_session ();
1680     else
1681     {
1682         *res->closeReason = Z_Close_finished;
1683         send_apdu(apdu);
1684         printf("Sent response.\n");
1685         sent_close = 1;
1686     }
1687 }
1688
1689 static int cmd_show(char *arg)
1690 {
1691     if (!conn)
1692     {
1693         printf("Not connected yet\n");
1694         return 0;
1695     }
1696     if (!send_presentRequest(arg))
1697         return 0;
1698     return 2;
1699 }
1700
1701 int cmd_quit(char *arg)
1702 {
1703     printf("See you later, alligator.\n");
1704     xmalloc_trav ("");
1705     exit(0);
1706     return 0;
1707 }
1708
1709 int cmd_cancel(char *arg)
1710 {
1711     Z_APDU *apdu = zget_APDU(out, Z_APDU_triggerResourceControlRequest);
1712     Z_TriggerResourceControlRequest *req =
1713         apdu->u.triggerResourceControlRequest;
1714     bool_t rfalse = 0;
1715     
1716     if (!conn)
1717     {
1718         printf("Session not initialized yet\n");
1719         return 0;
1720     }
1721     if (!ODR_MASK_GET(session->options, Z_Options_triggerResourceCtrl))
1722     {
1723         printf("Target doesn't support cancel (trigger resource ctrl)\n");
1724         return 0;
1725     }
1726     *req->requestedAction = Z_TriggerResourceCtrl_cancel;
1727     req->resultSetWanted = &rfalse;
1728
1729     send_apdu(apdu);
1730     printf("Sent cancel request\n");
1731     return 2;
1732 }
1733
1734 int send_scanrequest(const char *query, int pp, int num, const char *term)
1735 {
1736     Z_APDU *apdu = zget_APDU(out, Z_APDU_scanRequest);
1737     Z_ScanRequest *req = apdu->u.scanRequest;
1738     int use_rpn = 1;
1739     int oid[OID_SIZE];
1740     
1741     if (queryType == QueryType_CCL2RPN)
1742     {
1743         oident bib1;
1744         int error, pos;
1745         struct ccl_rpn_node *rpn;
1746
1747         rpn = ccl_find_str (bibset,  query, &error, &pos);
1748         if (error)
1749         {
1750             printf("CCL ERROR: %s\n", ccl_err_msg(error));
1751             return -1;
1752         }
1753         use_rpn = 0;
1754         bib1.proto = PROTO_Z3950;
1755         bib1.oclass = CLASS_ATTSET;
1756         bib1.value = VAL_BIB1;
1757         req->attributeSet = oid_ent_to_oid (&bib1, oid);
1758         if (!(req->termListAndStartPoint = ccl_scan_query (out, rpn)))
1759         {
1760             printf("Couldn't convert CCL to Scan term\n");
1761             return -1;
1762         }
1763         ccl_rpn_delete (rpn);
1764     }
1765     if (use_rpn && !(req->termListAndStartPoint =
1766                      p_query_scan(out, protocol, &req->attributeSet, query)))
1767     {
1768         printf("Prefix query error\n");
1769         return -1;
1770     }
1771     if (term && *term)
1772     {
1773         if (req->termListAndStartPoint->term &&
1774             req->termListAndStartPoint->term->which == Z_Term_general &&
1775             req->termListAndStartPoint->term->u.general)
1776         {
1777             req->termListAndStartPoint->term->u.general->buf =
1778                 (unsigned char *) odr_strdup(out, term);
1779             req->termListAndStartPoint->term->u.general->len =
1780                 req->termListAndStartPoint->term->u.general->size =
1781                 strlen(term);
1782         }
1783     }
1784     req->referenceId = set_refid (out);
1785     req->num_databaseNames = num_databaseNames;
1786     req->databaseNames = databaseNames;
1787     req->numberOfTermsRequested = &num;
1788     req->preferredPositionInResponse = &pp;
1789     send_apdu(apdu);
1790     return 2;
1791 }
1792
1793 int send_sortrequest(char *arg, int newset)
1794 {
1795     Z_APDU *apdu = zget_APDU(out, Z_APDU_sortRequest);
1796     Z_SortRequest *req = apdu->u.sortRequest;
1797     Z_SortKeySpecList *sksl = (Z_SortKeySpecList *)
1798         odr_malloc (out, sizeof(*sksl));
1799     char setstring[32];
1800
1801     if (setnumber >= 0)
1802         sprintf (setstring, "%d", setnumber);
1803     else
1804         sprintf (setstring, "default");
1805
1806     req->referenceId = set_refid (out);
1807
1808     req->num_inputResultSetNames = 1;
1809     req->inputResultSetNames = (Z_InternationalString **)
1810         odr_malloc (out, sizeof(*req->inputResultSetNames));
1811     req->inputResultSetNames[0] = odr_strdup (out, setstring);
1812
1813     if (newset && setnumber >= 0)
1814         sprintf (setstring, "%d", ++setnumber);
1815
1816     req->sortedResultSetName = odr_strdup (out, setstring);
1817
1818     req->sortSequence = yaz_sort_spec (out, arg);
1819     if (!req->sortSequence)
1820     {
1821         printf ("Missing sort specifications\n");
1822         return -1;
1823     }
1824     send_apdu(apdu);
1825     return 2;
1826 }
1827
1828 void display_term(Z_TermInfo *t)
1829 {
1830     if (t->term->which == Z_Term_general)
1831     {
1832         printf("%.*s", t->term->u.general->len, t->term->u.general->buf);
1833         sprintf(last_scan_line, "%.*s", t->term->u.general->len,
1834             t->term->u.general->buf);
1835     }
1836     else
1837         printf("Term (not general)");
1838     if (t->globalOccurrences)
1839         printf (" (%d)\n", *t->globalOccurrences);
1840     else
1841         printf ("\n");
1842 }
1843
1844 void process_scanResponse(Z_ScanResponse *res)
1845 {
1846     int i;
1847     Z_Entry **entries = NULL;
1848     int num_entries = 0;
1849    
1850     printf("Received ScanResponse\n"); 
1851     print_refid (res->referenceId);
1852     printf("%d entries", *res->numberOfEntriesReturned);
1853     if (res->positionOfTerm)
1854         printf (", position=%d", *res->positionOfTerm); 
1855     printf ("\n");
1856     if (*res->scanStatus != Z_Scan_success)
1857         printf("Scan returned code %d\n", *res->scanStatus);
1858     if (!res->entries)
1859         return;
1860     if ((entries = res->entries->entries))
1861         num_entries = res->entries->num_entries;
1862     for (i = 0; i < num_entries; i++)
1863     {
1864         int pos_term = res->positionOfTerm ? *res->positionOfTerm : -1;
1865         if (entries[i]->which == Z_Entry_termInfo)
1866         {
1867             printf("%c ", i + 1 == pos_term ? '*' : ' ');
1868             display_term(entries[i]->u.termInfo);
1869         }
1870         else
1871             display_diagrecs(&entries[i]->u.surrogateDiagnostic, 1);
1872     }
1873     if (res->entries->nonsurrogateDiagnostics)
1874         display_diagrecs (res->entries->nonsurrogateDiagnostics,
1875                           res->entries->num_nonsurrogateDiagnostics);
1876 }
1877
1878 void process_sortResponse(Z_SortResponse *res)
1879 {
1880     printf("Received SortResponse: status=");
1881     switch (*res->sortStatus)
1882     {
1883     case Z_SortStatus_success:
1884         printf ("success"); break;
1885     case Z_SortStatus_partial_1:
1886         printf ("partial"); break;
1887     case Z_SortStatus_failure:
1888         printf ("failure"); break;
1889     default:
1890         printf ("unknown (%d)", *res->sortStatus);
1891     }
1892     printf ("\n");
1893     print_refid (res->referenceId);
1894     if (res->diagnostics)
1895         display_diagrecs(res->diagnostics,
1896                          res->num_diagnostics);
1897 }
1898
1899 void process_deleteResultSetResponse (Z_DeleteResultSetResponse *res)
1900 {
1901     printf("Got deleteResultSetResponse status=%d\n",
1902            *res->deleteOperationStatus);
1903     if (res->deleteListStatuses)
1904     {
1905         int i;
1906         for (i = 0; i < res->deleteListStatuses->num; i++)
1907         {
1908             printf ("%s status=%d\n", res->deleteListStatuses->elements[i]->id,
1909                     *res->deleteListStatuses->elements[i]->status);
1910         }
1911     }
1912 }
1913
1914 int cmd_sort_generic(char *arg, int newset)
1915 {
1916     if (!conn)
1917     {
1918         printf("Session not initialized yet\n");
1919         return 0;
1920     }
1921     if (!ODR_MASK_GET(session->options, Z_Options_sort))
1922     {
1923         printf("Target doesn't support sort\n");
1924         return 0;
1925     }
1926     if (*arg)
1927     {
1928         if (send_sortrequest(arg, newset) < 0)
1929             return 0;
1930         return 2;
1931     }
1932     return 0;
1933 }
1934
1935 int cmd_sort(char *arg)
1936 {
1937     return cmd_sort_generic (arg, 0);
1938 }
1939
1940 int cmd_sort_newset (char *arg)
1941 {
1942     return cmd_sort_generic (arg, 1);
1943 }
1944
1945 int cmd_scan(char *arg)
1946 {
1947     if (!conn)
1948     {
1949         printf("Session not initialized yet\n");
1950         return 0;
1951     }
1952     if (!ODR_MASK_GET(session->options, Z_Options_scan))
1953     {
1954         printf("Target doesn't support scan\n");
1955         return 0;
1956     }
1957     if (*arg)
1958     {
1959         strcpy (last_scan_query, arg);
1960         if (send_scanrequest(arg, 1, 20, 0) < 0)
1961             return 0;
1962     }
1963     else
1964     {
1965         if (send_scanrequest(last_scan_query, 1, 20, last_scan_line) < 0)
1966             return 0;
1967     }
1968     return 2;
1969 }
1970
1971 int cmd_schema(char *arg)
1972 {
1973     if (!arg || !*arg)
1974     {
1975         schema = VAL_NONE;
1976         return 1;
1977     }
1978     schema = oid_getvalbyname (arg);
1979     if (schema == VAL_NONE)
1980     {
1981         printf ("unknown schema\n");
1982         return 0;
1983     }
1984     return 1;
1985 }
1986
1987 int cmd_format(char *arg)
1988 {
1989     if (!arg || !*arg)
1990     {
1991         printf("Usage: format <recordsyntax>\n");
1992         return 0;
1993     }
1994     recordsyntax = oid_getvalbyname (arg);
1995     if (recordsyntax == VAL_NONE)
1996     {
1997         printf ("unknown record syntax\n");
1998         return 0;
1999     }
2000     return 1;
2001 }
2002
2003 int cmd_elements(char *arg)
2004 {
2005     static Z_ElementSetNames esn;
2006     static char what[100];
2007
2008     if (!arg || !*arg)
2009     {
2010         elementSetNames = 0;
2011         return 1;
2012     }
2013     strcpy(what, arg);
2014     esn.which = Z_ElementSetNames_generic;
2015     esn.u.generic = what;
2016     elementSetNames = &esn;
2017     return 1;
2018 }
2019
2020 int cmd_attributeset(char *arg)
2021 {
2022     char what[100];
2023
2024     if (!arg || !*arg)
2025     {
2026         printf("Usage: attributeset <setname>\n");
2027         return 0;
2028     }
2029     sscanf(arg, "%s", what);
2030     if (p_query_attset (what))
2031     {
2032         printf("Unknown attribute set name\n");
2033         return 0;
2034     }
2035     return 1;
2036 }
2037
2038 int cmd_querytype (char *arg)
2039 {
2040     if (!strcmp (arg, "ccl"))
2041         queryType = QueryType_CCL;
2042     else if (!strcmp (arg, "prefix") || !strcmp(arg, "rpn"))
2043         queryType = QueryType_Prefix;
2044     else if (!strcmp (arg, "ccl2rpn") || !strcmp (arg, "cclrpn"))
2045         queryType = QueryType_CCL2RPN;
2046     else
2047     {
2048         printf ("Querytype must be one of:\n");
2049         printf (" prefix         - Prefix query\n");
2050         printf (" ccl            - CCL query\n");
2051         printf (" ccl2rpn        - CCL query converted to RPN\n");
2052         return 0;
2053     }
2054     return 1;
2055 }
2056
2057 int cmd_refid (char *arg)
2058 {
2059     xfree (refid);
2060     refid = NULL;
2061     if (*arg)
2062     {
2063         refid = (char *) xmalloc (strlen(arg)+1);
2064         strcpy (refid, arg);
2065     }
2066     return 1;
2067 }
2068
2069 int cmd_close(char *arg)
2070 {
2071     Z_APDU *apdu;
2072     Z_Close *req;
2073     if (!conn)
2074         return 0;
2075
2076     apdu = zget_APDU(out, Z_APDU_close);
2077     req = apdu->u.close;
2078     *req->closeReason = Z_Close_finished;
2079     send_apdu(apdu);
2080     printf("Sent close request.\n");
2081     sent_close = 1;
2082     return 2;
2083 }
2084
2085 int cmd_packagename(char* arg)
2086 {
2087     xfree (esPackageName);
2088     esPackageName = NULL;
2089     if (*arg)
2090     {
2091         esPackageName = (char *) xmalloc (strlen(arg)+1);
2092         strcpy (esPackageName, arg);
2093     }
2094     return 1;
2095 }
2096
2097 int cmd_proxy(char* arg)
2098 {
2099     if (*arg == '\0') {
2100         printf("Current proxy is `%s'\n", (yazCharset)?yazProxy:NULL);
2101         return 1;
2102     }
2103     xfree (yazProxy);
2104     yazProxy = NULL;
2105     if (*arg)
2106     {
2107         yazProxy = (char *) xmalloc (strlen(arg)+1);
2108         strcpy (yazProxy, arg);
2109     } 
2110     return 1;
2111 }
2112
2113 int cmd_charset(char* arg)
2114 {
2115     if (*arg == '\0') {
2116         printf("Current character set is `%s'\n", (yazCharset)?yazCharset:NULL);
2117         return 1;
2118     }
2119     xfree (yazCharset);
2120     yazCharset = NULL;
2121     if (*arg)
2122     {
2123         yazCharset = (char *) xmalloc (strlen(arg)+1);
2124         strcpy (yazCharset, arg);
2125     } 
2126     return 1;
2127 }
2128
2129 int cmd_lang(char* arg)
2130 {
2131     if (*arg == '\0') {
2132         printf("Current language is `%s'\n", (yazLang)?yazLang:NULL);
2133         return 1;
2134     }
2135     xfree (yazLang);
2136     yazLang = NULL;
2137     if (*arg)
2138     {
2139         yazLang = (char *) xmalloc (strlen(arg)+1);
2140         strcpy (yazLang, arg);
2141     } 
2142     return 1;
2143 }
2144
2145 int cmd_source(char* arg) 
2146 {
2147     /* first should open the file and read one line at a time.. */
2148     FILE* includeFile;
2149     char line[1024], *cp;
2150
2151     {
2152         char* args_end=(arg)+strlen(arg)-1; 
2153         while(isspace(*args_end)) 
2154         {*args_end=0;
2155         --args_end;}; 
2156     }
2157
2158     REMOVE_TAILING_BLANKS(arg);
2159     
2160     if(strlen(arg)<1) {
2161         fprintf(stderr,"Error in source command use a filename\n");
2162         return -1;
2163     }
2164     
2165     includeFile = fopen (arg, "r");
2166     
2167     if(!includeFile) {
2168         fprintf(stderr,"Unable to open file %s for reading\n",arg);
2169         return -1;
2170     }
2171     
2172     while(!feof(includeFile)) {
2173         memset(line,0,sizeof(line));
2174         fgets(line,sizeof(line),includeFile);
2175         
2176         if(strlen(line) < 2) continue;
2177         if(line[0] == '#') continue;
2178         
2179         if ((cp = strrchr (line, '\n')))
2180             *cp = '\0';
2181         
2182         process_cmd_line(line);
2183     }
2184     
2185     if(fclose(includeFile)<0) {
2186         perror("unable to close include file");
2187         exit(1);
2188     }
2189     return 1;
2190 }
2191
2192 int cmd_subshell(char* args)
2193 {
2194     if(strlen(args)) 
2195         system(args);
2196     else 
2197         system(getenv("SHELL"));
2198     
2199     printf("\n");
2200     return 1;
2201 }
2202
2203 int cmd_set_apdufile(char* arg)
2204 {
2205     REMOVE_TAILING_BLANKS(arg);
2206   
2207     if(apdu_file && apdu_file != stderr) { /* don't close stdout*/
2208         perror("unable to close apdu log file");      
2209     }
2210     apdu_file=NULL;
2211   
2212     if(strlen(arg)<1) {
2213         return 1;
2214     }
2215   
2216     if(!strcmp(arg,"-")) 
2217         apdu_file=stderr;      
2218     else 
2219         apdu_file=fopen(arg, "a");
2220   
2221     if(!apdu_file) {
2222         perror("unable to open apdu log file no apdu log loaded");
2223     } else {
2224         odr_setprint(print, apdu_file); 
2225     }
2226   
2227     return 1;
2228 }
2229
2230 int cmd_set_cclfields(char* arg)
2231 {  
2232     FILE *inf;
2233
2234     REMOVE_TAILING_BLANKS(arg);
2235
2236     bibset = ccl_qual_mk (); 
2237     inf = fopen (arg, "r");
2238     if (inf)
2239     {
2240         ccl_qual_file (bibset, inf);
2241         fclose (inf);
2242     }
2243     
2244     return 1;
2245 }
2246
2247 int cmd_set_marcdump(char* arg)
2248 {
2249     if(marcdump && marcdump != stderr) { /* don't close stdout*/
2250         perror("unable to close apdu log file");      
2251     }
2252     marcdump=NULL;
2253     
2254     if(strlen(arg)<1) {
2255         return 1;
2256     }
2257   
2258     if(!strcmp(arg,"-")) 
2259         marcdump=stderr;      
2260     else 
2261         marcdump=fopen(arg, "a");
2262   
2263     if(!marcdump) {
2264         perror("unable to open apdu marcdump file no marcdump done\n");
2265     }
2266   
2267     return 1;
2268 }
2269
2270 int cmd_set_proxy(char* arg) {
2271     if(yazProxy) free(yazProxy);
2272     yazProxy=NULL;
2273
2274     if(strlen(arg) > 1) {
2275         yazProxy=strdup(arg);
2276     }
2277     return 1;
2278 }
2279
2280 /* 
2281    this command takes 3 arge {name class oid} 
2282  */
2283 int cmd_register_oid(char* args) {
2284     static struct {
2285         char* className;
2286         oid_class oclass;
2287     } oid_classes[] = {
2288         {"appctx",CLASS_APPCTX},
2289         {"absyn",CLASS_ABSYN},
2290         {"attset",CLASS_ATTSET},
2291         {"transyn",CLASS_TRANSYN},
2292         {"diagset",CLASS_DIAGSET},
2293         {"recsyn",CLASS_RECSYN},
2294         {"resform",CLASS_RESFORM},
2295         {"accform",CLASS_ACCFORM},
2296         {"extserv",CLASS_EXTSERV},
2297         {"userinfo",CLASS_USERINFO},
2298         {"elemspec",CLASS_ELEMSPEC},
2299         {"varset",CLASS_VARSET},
2300         {"schema",CLASS_SCHEMA},
2301         {"tagset",CLASS_TAGSET},
2302         {"general",CLASS_GENERAL},
2303         {0,0}
2304     };
2305     char oname_str[101], oclass_str[101], oid_str[101];  
2306     char* name;
2307     int i;
2308     oid_class oidclass = CLASS_GENERAL;
2309     int val = 0, oid[OID_SIZE];
2310     struct oident * new_oident=NULL;
2311     
2312     if (sscanf (args, "%100[^ ] %100[^ ] %100s",
2313                 oname_str,oclass_str, oid_str) < 1) {
2314         printf("Error in regristrate command \n");
2315         return 0;
2316     }
2317     
2318     for (i = 0; oid_classes[i].className; i++) {
2319         if (!strcmp(oid_classes[i].className, oclass_str))
2320         {
2321             oidclass=oid_classes[i].oclass;
2322             break;
2323         }
2324     }
2325     
2326     if(!(oid_classes[i].className)) {
2327         printf("Unknonwn oid class %s\n",oclass_str);
2328         return 0;
2329     }
2330
2331     i = 0;
2332     name = oid_str;
2333     val = 0;
2334     
2335     while (isdigit (*name))
2336     {
2337         val = val*10 + (*name - '0');
2338         name++;
2339         if (*name == '.')
2340         {
2341             if (i < OID_SIZE-1)
2342                 oid[i++] = val;
2343             val = 0;
2344             name++;
2345         }
2346     }
2347     oid[i] = val;
2348     oid[i+1] = -1;
2349     
2350     new_oident=oid_addent (oid,PROTO_GENERAL,oidclass,oname_str,VAL_DYNAMIC);  
2351     if(strcmp(new_oident->desc,oname_str)) {
2352         fprintf(stderr,"oid is already named as %s, regristration faild\n",
2353                 new_oident->desc);
2354     }
2355     return 1;  
2356 }
2357
2358 int cmd_push_command(char* arg) {
2359 #if HAVE_READLINE_HISTORY_H
2360     if(strlen(arg)>1) 
2361         add_history(arg);
2362 #else 
2363     fprintf(stderr,"Not compiled with the readline/history module\n");
2364 #endif
2365     return 1;
2366 }
2367
2368 void source_rcfile() {
2369     /*  Look for a $HOME/.yazclientrc and source it if it exists */
2370     struct stat statbuf;
2371     char buffer[1000];
2372     char* homedir=getenv("HOME");
2373     if(!homedir) return;
2374     
2375     sprintf(buffer,"%s/.yazclientrc",homedir);
2376     
2377     if(stat(buffer,&statbuf)==0) {
2378         cmd_source(buffer);
2379     }
2380     
2381     if(stat(".yazclientrc",&statbuf)==0) {
2382         cmd_source(".yazclientrc");
2383     }
2384 }
2385
2386
2387 static void initialize(void)
2388 {
2389 #if YAZ_MODULE_ccl
2390     FILE *inf;
2391 #endif
2392     if (!(out = odr_createmem(ODR_ENCODE)) ||
2393         !(in = odr_createmem(ODR_DECODE)) ||
2394         !(print = odr_createmem(ODR_PRINT)))
2395     {
2396         fprintf(stderr, "failed to allocate ODR streams\n");
2397         exit(1);
2398     }
2399     oid_init();
2400
2401     setvbuf(stdout, 0, _IONBF, 0);
2402     if (apdu_file)
2403         odr_setprint(print, apdu_file);
2404
2405 #if YAZ_MODULE_ccl
2406     bibset = ccl_qual_mk (); 
2407     inf = fopen (ccl_fields, "r");
2408     if (inf)
2409     {
2410         ccl_qual_file (bibset, inf);
2411         fclose (inf);
2412     }
2413 #endif
2414     cmd_base("Default");
2415
2416 #if HAVE_READLINE_READLINE_H
2417     rl_attempted_completion_function = (CPPFunction*)readline_completer;
2418 #endif
2419
2420     source_rcfile();
2421 }
2422
2423
2424 #if HAVE_GETTIMEOFDAY
2425 struct timeval tv_start, tv_end;
2426 #endif
2427
2428 void wait_and_handle_responce() 
2429 {
2430     
2431     int res;
2432     char *netbuffer= 0;
2433     int netbufferlen = 0;
2434     Z_APDU *apdu;
2435     
2436     
2437     if (conn)
2438     {
2439         do
2440         {
2441             if ((res = cs_get(conn, &netbuffer, &netbufferlen)) < 0)
2442             {
2443                 printf("Target closed connection\n");
2444                 close_session ();
2445                 break;
2446             }
2447             if (!res)
2448             {
2449                 printf("Target closed connection.\n");
2450                 close_session ();
2451                 break;
2452             }
2453             odr_reset(in); /* release APDU from last round */
2454             record_last = 0;
2455             odr_setbuf(in, netbuffer, res, 0);
2456             if (!z_APDU(in, &apdu, 0, 0))
2457             {
2458                 odr_perror(in, "Decoding incoming APDU");
2459                 fprintf(stderr, "[Near %d]\n", odr_offset(in));
2460                 fprintf(stderr, "Packet dump:\n---------\n");
2461                 odr_dumpBER(stderr, netbuffer, res);
2462                 fprintf(stderr, "---------\n");
2463                 if (apdu_file)
2464                     z_APDU(print, &apdu, 0, 0);
2465                 close_session ();
2466                 break;
2467             }
2468             if (apdu_file && !z_APDU(print, &apdu, 0, 0))
2469             {
2470                 odr_perror(print, "Failed to print incoming APDU");
2471                 odr_reset(print);
2472                 continue;
2473             }
2474             switch(apdu->which)
2475             {
2476             case Z_APDU_initResponse:
2477                 process_initResponse(apdu->u.initResponse);
2478                 break;
2479             case Z_APDU_searchResponse:
2480                 process_searchResponse(apdu->u.searchResponse);
2481                 break;
2482             case Z_APDU_scanResponse:
2483                 process_scanResponse(apdu->u.scanResponse);
2484                 break;
2485             case Z_APDU_presentResponse:
2486                 print_refid (apdu->u.presentResponse->referenceId);
2487                 setno +=
2488                     *apdu->u.presentResponse->numberOfRecordsReturned;
2489                 if (apdu->u.presentResponse->records)
2490                     display_records(apdu->u.presentResponse->records);
2491                 else
2492                     printf("No records.\n");
2493                 printf ("nextResultSetPosition = %d\n",
2494                         *apdu->u.presentResponse->nextResultSetPosition);
2495                 break;
2496             case Z_APDU_sortResponse:
2497                 process_sortResponse(apdu->u.sortResponse);
2498                 break;
2499             case Z_APDU_extendedServicesResponse:
2500                 printf("Got extended services response\n");
2501                 process_ESResponse(apdu->u.extendedServicesResponse);
2502                 break;
2503             case Z_APDU_close:
2504                 printf("Target has closed the association.\n");
2505                 process_close(apdu->u.close);
2506                 break;
2507             case Z_APDU_resourceControlRequest:
2508                 process_resourceControlRequest
2509                     (apdu->u.resourceControlRequest);
2510                 break;
2511             case Z_APDU_deleteResultSetResponse:
2512                 process_deleteResultSetResponse(apdu->u.
2513                                                 deleteResultSetResponse);
2514                 break;
2515             default:
2516                 printf("Received unknown APDU type (%d).\n", 
2517                        apdu->which);
2518                 close_session ();
2519             }
2520         }
2521         while (conn && cs_more(conn));
2522 #if HAVE_GETTIMEOFDAY
2523         gettimeofday (&tv_end, 0);
2524 #if 0
2525         printf ("S/U S/U=%ld/%ld %ld/%ld",
2526                 (long) tv_start.tv_sec,
2527                 (long) tv_start.tv_usec,
2528                 (long) tv_end.tv_sec,
2529                 (long) tv_end.tv_usec);
2530 #endif
2531         printf ("Elapsed: %.6f\n",
2532                 (double) tv_end.tv_usec / 1e6 + tv_end.tv_sec -
2533                 ((double) tv_start.tv_usec / 1e6 + tv_start.tv_sec));
2534 #endif
2535     }
2536     xfree (netbuffer);
2537 }
2538
2539
2540 static int cmd_help (char *line);
2541
2542 static struct {
2543     char *cmd;
2544     int (*fun)(char *arg);
2545     char *ad;
2546     char *(*rl_completerfunction)(const char *text, int state);
2547     int complete_filenames;
2548 } cmd[] = {
2549     {"open", cmd_open, "('tcp'|'ssl')':<host>[':'<port>][/<db>]",NULL,0},
2550     {"quit", cmd_quit, "",NULL,0},
2551     {"find", cmd_find, "<query>",NULL,0},
2552     {"delete", cmd_delete, "<setname>",NULL,0},
2553     {"base", cmd_base, "<base-name>",NULL,0},
2554     {"show", cmd_show, "<rec#>['+'<#recs>['+'<setname>]]",NULL,0},
2555     {"scan", cmd_scan, "<term>",NULL,0},
2556     {"sort", cmd_sort, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0},
2557     {"sort+", cmd_sort_newset, "<sortkey> <flag> <sortkey> <flag> ...",NULL,0},
2558     {"authentication", cmd_authentication, "<acctstring>",NULL,0},
2559     {"lslb", cmd_lslb, "<largeSetLowerBound>",NULL,0},
2560     {"ssub", cmd_ssub, "<smallSetUpperBound>",NULL,0},
2561     {"mspn", cmd_mspn, "<mediumSetPresentNumber>",NULL,0},
2562     {"status", cmd_status, "",NULL,0},
2563     {"setnames", cmd_setnames, "",NULL,0},
2564     {"cancel", cmd_cancel, "",NULL,0},
2565     {"format", cmd_format, "<recordsyntax>",complete_format,0},
2566     {"schema", cmd_schema, "<schema>",complete_schema,0},
2567     {"elements", cmd_elements, "<elementSetName>",NULL,0},
2568     {"close", cmd_close, "",NULL,0},
2569     {"attributeset", cmd_attributeset, "<attrset>",complete_attributeset,0},
2570     {"querytype", cmd_querytype, "<type>",complete_querytype,0},
2571     {"refid", cmd_refid, "<id>",NULL,0},
2572     {"itemorder", cmd_itemorder, "ill|item <itemno>",NULL,0},
2573     {"update", cmd_update, "<item>",NULL,0},
2574     {"packagename", cmd_packagename, "<packagename>",NULL,0},
2575     {"proxy", cmd_proxy, "[('tcp'|'ssl')]<host>[':'<port>]",NULL,0},
2576     {"charset", cmd_charset, "<charset_name>",NULL,0},
2577     {"lang", cmd_lang, "<language_code>",NULL,0},
2578     {".", cmd_source, "<filename>",NULL,1},
2579     {"!", cmd_subshell, "Subshell command",NULL,0},
2580     {"set_apdufile", cmd_set_apdufile, "<filename>",NULL,0},
2581     {"set_marcdump", cmd_set_marcdump," <filename>",NULL,0},
2582     {"set_cclfields", cmd_set_cclfields,"<filename>",NULL,1}, 
2583     {"register_oid",cmd_register_oid,"<name> <class> <oid>",NULL,0},
2584     {"push_command",cmd_push_command,"<command>",command_generator,0},
2585     /* Server Admin Functions */
2586     {"adm-reindex", cmd_adm_reindex, "<database-name>",NULL,0},
2587     {"adm-truncate", cmd_adm_truncate, "('database'|'index')<object-name>",NULL,0},
2588     {"adm-create", cmd_adm_create, "",NULL,0},
2589     {"adm-drop", cmd_adm_drop, "('database'|'index')<object-name>",NULL,0},
2590     {"adm-import", cmd_adm_import, "<record-type> <dir> <pattern>",NULL,0},
2591     {"adm-refresh", cmd_adm_refresh, "",NULL,0},
2592     {"adm-commit", cmd_adm_commit, "",NULL,0},
2593     {"adm-shutdown", cmd_adm_shutdown, "",NULL,0},
2594     {"adm-startup", cmd_adm_startup, "",NULL,0},
2595     {"help", cmd_help, "", NULL},
2596     {0,0,0,0,0}
2597 };
2598
2599 static int cmd_help (char *line)
2600 {
2601     int i;
2602     char topic[21];
2603     
2604     *topic = 0;
2605     sscanf (line, "%20s", topic);
2606
2607     if (*topic == 0)
2608         printf("Commands:\n");
2609     for (i = 0; cmd[i].cmd; i++)
2610         if (*topic == 0 || strcmp (topic, cmd[i].cmd) == 0)
2611             printf("   %s %s\n", cmd[i].cmd, cmd[i].ad);
2612     if (strcmp (topic, "find") == 0)
2613     {
2614         printf ("RPN:\n");
2615         printf (" \"term\"                        Simple Term\n");
2616         printf (" @attr [attset] type=value op  Attribute\n");
2617         printf (" @and opl opr                  And\n");
2618         printf (" @or opl opr                   Or\n");
2619         printf (" @not opl opr                  And-Not\n");
2620         printf (" @set set                      Result set\n");
2621         printf ("\n");
2622         printf ("Bib-1 attribute types\n");
2623         printf ("1=Use:         ");
2624         printf ("4=Title 7=ISBN 8=ISSN 30=Date 62=Abstract 1003=Author 1016=Any\n");
2625         printf ("2=Relation:    ");
2626         printf ("1<   2<=  3=  4>=  5>  6!=  102=Relevance\n");
2627         printf ("3=Position:    ");
2628         printf ("1=First in Field  2=First in subfield  3=Any position\n");
2629         printf ("4=Structure:   ");
2630         printf ("1=Phrase  2=Word  3=Key  4=Year  5=Date  6=WordList\n");
2631         printf ("5=Truncation:  ");
2632         printf ("1=Right  2=Left  3=L&R  100=No  101=#  102=Re-1  103=Re-2\n");
2633         printf ("6=Completeness:");
2634         printf ("1=Incomplete subfield  2=Complete subfield  3=Complete field\n");
2635     }
2636     return 1;
2637 }
2638
2639 void process_cmd_line(char* line)
2640 {  
2641     int i,res;
2642     char word[32], arg[1024];
2643     
2644 #if HAVE_GETTIMEOFDAY
2645     gettimeofday (&tv_start, 0);
2646 #endif
2647     
2648     if ((res = sscanf(line, "%31s %1023[^;]", word, arg)) <= 0)
2649     {
2650         strcpy(word, last_cmd);
2651         *arg = '\0';
2652     }
2653     else if (res == 1)
2654         *arg = 0;
2655     strcpy(last_cmd, word);
2656     
2657     /* removed tailing spaces from the arg command */
2658     { 
2659         char* p;
2660         char* lastnonspace=NULL;
2661         p = arg;
2662         
2663         for(;*p; ++p) {
2664             if(!isspace(*p)) {
2665                 lastnonspace = p;
2666             }
2667         }
2668         if(lastnonspace) 
2669             *(++lastnonspace) = 0;
2670     }
2671     
2672
2673     for (i = 0; cmd[i].cmd; i++)
2674         if (!strncmp(cmd[i].cmd, word, strlen(word)))
2675         {
2676             res = (*cmd[i].fun)(arg);
2677             break;
2678         }
2679
2680     if (!cmd[i].cmd) /* dump our help-screen */
2681     {
2682         printf("Unknown command: %s.\n", word);
2683         cmd_help ("");
2684         res = 1;
2685     }
2686
2687     if(apdu_file) fflush(apdu_file);
2688     
2689     if (res >= 2)
2690         wait_and_handle_responce();
2691
2692     if(apdu_file)
2693         fflush(apdu_file);
2694     if(marcdump)
2695         fflush(marcdump);
2696 }
2697
2698
2699 char *command_generator(const char *text, int state) 
2700 {
2701     static int idx; 
2702     if (state==0) {
2703         idx = 0;
2704     }
2705     for( ; cmd[idx].cmd; ++idx) {
2706         if (!strncmp(cmd[idx].cmd,text,strlen(text))) {
2707             ++idx;  /* skip this entry on the next run */
2708             return strdup(cmd[idx-1].cmd);
2709         }
2710     }
2711     return NULL;
2712 }
2713
2714
2715 /* 
2716    This function only known how to complete on the first word
2717 */
2718 char ** readline_completer(char *text, int start, int end) {
2719 #if HAVE_READLINE_READLINE_H
2720
2721     if(start == 0) {
2722 #if HAVE_READLINE_RL_COMPLETION_MATCHES
2723         char** res=rl_completion_matches(text,
2724                                       command_generator); 
2725 #else
2726         char** res=completion_matches(text,
2727                                       (CPFunction*)command_generator); 
2728 #endif
2729         rl_attempted_completion_over = 1;
2730         return res;
2731     } else {
2732         char arg[1024],word[32];
2733         int i=0 ,res;
2734         if ((res = sscanf(rl_line_buffer, "%31s %1023[^;]", word, arg)) <= 0) {     
2735             rl_attempted_completion_over = 1;
2736             return NULL;
2737         }
2738     
2739         if(start != strlen(word) +1 ) {
2740             rl_attempted_completion_over = 1;
2741             return 0;
2742         }
2743         for (i = 0; cmd[i].cmd; i++) {
2744             if (!strncmp(cmd[i].cmd, word, strlen(word))) {
2745                 break;
2746             }
2747         }
2748     
2749
2750         if(!cmd[i].complete_filenames) 
2751             rl_attempted_completion_over = 1;    
2752         if(cmd[i].rl_completerfunction) {
2753 #ifdef HAVE_READLINE_RL_COMPLETION_MATCHES
2754             char** res=
2755                 rl_completion_matches(text,
2756                                    cmd[i].rl_completerfunction);
2757 #else
2758             char** res=
2759                 completion_matches(text,
2760                                    (CPFunction*)cmd[i].rl_completerfunction);
2761 #endif
2762             rl_attempted_completion_over = 1;    
2763             return res;
2764         } else {
2765             rl_attempted_completion_over = 1;
2766             return 0;
2767         }
2768     }
2769 #else 
2770     return 0;
2771 #endif 
2772 }
2773
2774
2775 static void client(void)
2776 {
2777     char line[1024];
2778
2779     line[1023] = '\0';
2780
2781 #if HAVE_GETTIMEOFDAY
2782     gettimeofday (&tv_start, 0);
2783 #endif
2784
2785     while (1)
2786     {
2787         char *line_in = NULL;
2788 #if HAVE_READLINE_READLINE_H
2789         if (isatty(0))
2790         {
2791             line_in=readline(C_PROMPT);
2792             if (!line_in)
2793                 break;
2794 #if HAVE_READLINE_HISTORY_H
2795             if (*line_in)
2796                 add_history(line_in);
2797 #endif
2798             strncpy(line, line_in, 1023);
2799             free (line_in);
2800         }
2801 #endif 
2802         if (!line_in)
2803         {
2804             char *end_p;
2805             printf (C_PROMPT);
2806             fflush(stdout);
2807             if (!fgets(line, 1023, stdin))
2808                 break;
2809             if ((end_p = strchr (line, '\n')))
2810                 *end_p = '\0';
2811         }
2812         process_cmd_line(line);
2813     }
2814 }
2815
2816 int main(int argc, char **argv)
2817 {
2818     char *prog = *argv;
2819     char *open_command = 0;
2820     char *auth_command = 0;
2821     char *arg;
2822     int ret;
2823     
2824     while ((ret = options("k:c:a:m:v:p:u:", argv, argc, &arg)) != -2)
2825     {
2826         switch (ret)
2827         {
2828         case 0:
2829             if (!open_command)
2830             {
2831                 open_command = (char *) xmalloc (strlen(arg)+6);
2832                 strcpy (open_command, "open ");
2833                 strcat (open_command, arg);
2834             }
2835             break;
2836         case 'k':
2837             kilobytes = atoi(arg);
2838             break;
2839         case 'm':
2840             if (!(marcdump = fopen (arg, "a")))
2841             {
2842                 perror (arg);
2843                 exit (1);
2844             }
2845             break;
2846     case 'c':
2847         strncpy (ccl_fields, arg, sizeof(ccl_fields)-1);
2848         ccl_fields[sizeof(ccl_fields)-1] = '\0';
2849         break;
2850         case 'a':
2851             if (!strcmp(arg, "-"))
2852                 apdu_file=stderr;
2853             else
2854                 apdu_file=fopen(arg, "a");
2855             break;
2856     case 'p':
2857         yazProxy=strdup(arg);
2858         break;
2859         case 'u':
2860             if (!auth_command)
2861             {
2862                 auth_command = (char *) xmalloc (strlen(arg)+6);
2863                 strcpy (auth_command, "auth ");
2864                 strcat (auth_command, arg);
2865             }
2866             break;
2867         case 'v':
2868             yaz_log_init (yaz_log_mask_str(arg), "", NULL);
2869             break;
2870         default:
2871             fprintf (stderr, "Usage: %s [-m <marclog>] [ -a <apdulog>] "
2872                      "[-c cclfields]\n      [-p <proxy-addr>] [-u <auth>] "
2873                      "[-k size] [<server-addr>]\n",
2874                      prog);
2875             exit (1);
2876         }      
2877     }
2878     initialize();
2879     if (auth_command)
2880     {
2881 #ifdef HAVE_GETTIMEOFDAY
2882         gettimeofday (&tv_start, 0);
2883 #endif
2884         process_cmd_line (auth_command);
2885 #if HAVE_READLINE_HISTORY_H
2886         add_history(auth_command);
2887 #endif
2888         xfree(auth_command);
2889     }
2890     if (open_command)
2891     {
2892 #ifdef HAVE_GETTIMEOFDAY
2893         gettimeofday (&tv_start, 0);
2894 #endif
2895         process_cmd_line (open_command);
2896 #if HAVE_READLINE_HISTORY_H
2897         add_history(open_command);
2898 #endif
2899         xfree(open_command);
2900     }
2901     client ();
2902     exit (0);
2903 }
2904
2905
2906 /*
2907  * Local variables:
2908  * tab-width: 4
2909  * c-basic-offset: 4
2910  * End:
2911  */